diff --git a/README.md b/README.md
index e4f88e22f099275429e1d607908c65c31407d879..a12aa02697b677c6879c12311e57957f1590b691 100644
--- a/README.md
+++ b/README.md
@@ -799,68 +799,37 @@ dataset revision you used (`cba82611210e401dc0155cb78fcf456a385ecef4`).
## Part E: SO101 pick and place
-### What it is
-
-Follow-on work to the paper, not part of it. A camera policy (the "student") for a real SO101 arm picks a 30 mm cube
-and places it on a plate. Every training step ran inside a contact NRD of the arm and the cube (the design of Part C,
-trained on CPU MuJoCo 3.15.0 episodes): a state teacher trained with PPO in the NRD, then the student trained in the
-NRD with ray-traced images of a calibrated copy of the real scene (online DAgger). No real image was a training
-sample. On the real arm the student placed the cube in 36 of 50 stress-test episodes (72 %; 95 % interval 58–83 %).
-The training, the results and the commands are in
-[`so101_pick_place/` of the code repository](https://github.com/uwsbel/NeDM/tree/main/so101_pick_place).
+Follow-on work to the paper. CPU MuJoCo arm-and-cube dynamics were distilled into a contact NRD, then a state
+teacher and a camera student were trained inside it. The student placed a cube on a plate on a real SO101 arm
+in **36/50 stress-test episodes (72 %; Wilson 95 % interval 58–83 %)**. No real image was a training sample;
+real recordings informed calibration, later training rounds and student selection.
-### Layout
+The NeDM [study summary](https://github.com/uwsbel/NeDM/tree/main/so101_pick_place) contains results and limitations.
+The implementation, configs and full training guide are hosted here under
+[`so101_pick_place/code/`](https://huggingface.co/datasets/harryzhang1018/NeDM/tree/main/so101_pick_place/code).
-| Path | Contents |
+| Path under `so101_pick_place/` | Contents |
|---|---|
-| `so101_pick_place/nrd/c1_s62/`, `nrd/c0_s62/` | The policy NRD (every teacher and student stage ran in it) and its base: `best.pt` loads with `nedm.contact_nrd.model.load_model`; `original/best.pt` is the file as trained (two training-only heads more); the training records |
-| `so101_pick_place/nrd_data/` | The 4 NRD training data parts (93,494 episodes; `unified_data.npz`, `system.json`, `manifest.json`), and the 7 PPO policies behind `policy_v3` |
-| `so101_pick_place/nrd_test/` | The sealed scripted test set (3,050 episodes) |
-| `so101_pick_place/teacher/`, `student/` | Every teacher (T0-T6) and student (S0-S5) checkpoint of the chain with its run record; the teacher's expert data |
-| `so101_pick_place/rl_inputs/` | Task sets, start banks, geometry, the task sets of the sim checks |
-| `so101_pick_place/results/` | The sealed NRD test, the sim-check results and selection rules, the per-episode robot results |
-| `so101_pick_place/robot/` | Raw logs of 19 robot sessions (102 policy episodes), 52 videos of the student's input images, 2 LeRobot teleop recordings |
-| `so101_pick_place/bundle/` | The folder installed on the robot computer, and its tarball |
-| `so101_pick_place/scene_calib/`, `provenance/` | Camera calibration, scene and servo fit (also in the code repository); code snapshots that are in no commit |
-| `so101_pick_place/release_manifest.json` | Size and SHA-256 of every file; provenance (commits, runs, sources) |
-
-Total 13.3 GB (NRD data 10.6 GB).
-
-### What the files contain
-
-- NRD data (`unified_data.npz`, uncompressed): `arm` [N, 601, 12] (6 joint angles, 6 joint rates), `cube` [N, 601,
- 13] (position, quaternion wxyz, velocity, angular velocity), `action` [N, 601, 6] (joint position targets),
- `contacts` [N, 600, 3] (fixed jaw - cube, moving jaw - cube, cube - table), `lengths`, `splits` (0 train,
- 1 validation, 2 test), `family`, `phase`, contact force, impulse and depth, ids, seeds and outcome fields. Records
- are 10 ms apart, episodes 4 s.
-- Checkpoints: PyTorch files. Teachers: MLP state policies with privileged inputs. Students: two ResNet18 image
- encoders (external camera crop and wrist camera, 224 x 224 RGB), joint angles and rates, a chunk of 10 joint
- targets as output.
-- Robot logs: per session `session.json` (command line, typed outcome per episode) and `first_frames.npz`; per
- episode `episode_live.json` (setup, guard, latency, outcome) and `episode_live.npz` (50 Hz joints and commands,
- each policy query with its action chunk and the two input images at 112 px).
-
-### Download and use
-
-```bash
-scripts/so101_pick_place/reproduce.sh full --steps download # in the code repository; checks every SHA-256
-```
-
-The code repository's `so101_pick_place/release_manifest.json` pins the Hub revision; `--with-nrd-data` and
-`--with-robot` add the large folders. The MuJoCo Menagerie SO101 model is not in this dataset: the code repository
-fetches it at a pinned revision.
-
-### Known limitations
-
-- **One robot, one lab, one cube and plate.** The outcome is typed by the operator; the stress protocol was not fixed
- in advance, and the student was chosen with robot results.
-- **The NRD test set has only scripted families** and is not fully blind (run once before on an older NRD design).
-- **Lab content.** The robot logs hold lab background images, the robot computer's user path and the USB adapter
- serial. The videos show the student's input images as logged on the robot (112 px; the student sees 224 px);
- there is no full-resolution video.
-
-### License and citation
-
-BSD-3-Clause, the same as Part A and the code. The MuJoCo Menagerie model is not hosted here. The SO101 pick and place
-has no publication yet: please cite the NeDM paper (Part A) and name the dataset revision you used (the
-`hf_revision` of `so101_pick_place/release_manifest.json` in the code repository).
+| `code/` | Browsable source, configs, requirements, full study README, source manifest and `source.tar.gz` overlay; start with `code/REPRODUCE.md` |
+| `nrd/`, `nrd_data/`, `nrd_test/` | Base and policy NRDs, 93,494 training episodes and the 3,050-episode scripted test |
+| `teacher/`, `student/`, `rl_inputs/` | Training-chain checkpoints, run records, expert data, task sets and geometry |
+| `results/` | NRD evaluations, simulation checks, selection rules and robot result records |
+| `robot/` | 19 session logs, 52 videos and two LeRobot calibration/replay recordings |
+| `bundle/`, `scene_calib/`, `provenance/` | Tested robot bundle, scene and servo calibration, available historical code snapshots |
+| `release_manifest.json` | Original 503-file data manifest: sizes, SHA-256 values and stage provenance |
+
+The original data release is about 13.3 GB, unchanged. The NeDM study's compact `release_manifest.json` pins the
+source revision and original data revision separately. Download the source archive using the checksum-verified
+command in the study summary, apply it over its pinned base Git checkout, then follow the full archived README.
+The restored `scripts/so101_pick_place/reproduce.sh` downloads the data and checks every selected file's size
+and SHA-256. Its `full --steps download,robot` command rebuilds result tables from archived logs.
+
+Limits: one robot and lab; operator-labelled placements; student selection used robot screening; the stress
+protocol was not fixed in advance. tb10 failed its original frozen sim rule and there is no sealed student test.
+The NRD's 0.22/4.13 mm median/p95 1 s cube error scores 2,000 selected-family episodes; p95 over all 3,050 is
+4.61 mm. That scripted NRD test was previously used on an older design. Videos are the logged 112 px student
+inputs. Some historical stages permit recipe-only reruns. Robot logs contain the previously released lab
+images, paths and USB identifiers.
+
+BSD-3-Clause, as for Part A and the code. The MuJoCo Menagerie model remains fetched from its pinned upstream
+revision. This study has no publication yet; cite the NeDM paper and the data and source revisions used.
diff --git a/so101_pick_place/code/README.md b/so101_pick_place/code/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..062628061f05704c7073a6b18bcbdfc5665c6591
--- /dev/null
+++ b/so101_pick_place/code/README.md
@@ -0,0 +1,198 @@
+# NeDM — Neural Reduced Dynamics for Complex Robot Control
+
+Code and artifacts for *Learning the Right Abstraction: Neural Reduced Dynamics
+for Complex Robot Control* (Zhang and Negrut).
+
+**Project page: ** — figures, and the nine
+side-by-side Chrono rollouts behind the Study Case I result. Its source is
+[`web/`](web/README.md).
+
+High-fidelity Chrono trajectories are distilled into a task-specific neural
+reduced dynamics model (NN-ROM); the model is frozen and replicated into a
+vectorized environment where a control policy is trained with PPO; the trained
+policy is then returned to the full Chrono system for closed-loop validation.
+
+Two study cases instantiate the pipeline across three control tasks:
+
+- **Study Case I** — terrain-aware HMMWV trajectory tracking on rigid, bumpy and
+ deformable CRM terrain. A 15-D reduced state carries body motion plus a
+ per-wheel terramechanics block; a two-class terrain code resolves the
+ rigid-vs-CRM ambiguity. One policy trained inside the conditioned model beats
+ both single-terrain specialists on all three terrains, including zero-shot
+ bumpy.
+- **Study Case II** — an M113 tracked vehicle with a front-mounted 4-DOF arm,
+ driven by two independent tasks. A 3-D planar state serves base goal reaching
+ (100/100 goals in Chrono at 0.75 m); an 8-D joint-space state serves arm
+ end-effector reaching (97/100 at 0.05 m, zero contacts or joint-limit
+ violations), with the end-effector recovered by forward kinematics rather than
+ learned.
+
+**Follow-on work, not part of the paper:** [`traversing/`](traversing/README.md)
+records an off-road traversing study. A learned route-risk planner picks routes
+across generated hill-and-crater terrain in Chrono, on rigid ground and CRM
+soil, with results that vary by vehicle and ground. Separately, a route tracker
+trained with PPO inside a learned reduced dynamics model is compared with PID:
+it tracks routes more closely on rigid ground but completes fewer routes on
+soil. The folder records milestones, evidence and limits through 2026-09-28.
+The study's data and models are in the `traversing/` folder of the Hugging Face
+dataset; its training and evaluation code is in `src/nedm/traversing/`.
+
+**Follow-on work, not part of the paper:** [`contact_nrd/`](contact_nrd/README.md)
+extends neural reduced dynamics (NRD) to contacts that start and stop: a bouncing ball, two pool balls,
+an SO101 arm that pushes a T, and a Unitree G1 humanoid that a frozen walking policy drives in MuJoCo.
+A core network, a collision network and a contact network, with one design for all four cases, predict
+each 20 ms step. The first three cases share one training config; G1 has its own. The data, test sets
+and trained models are in the `contact_nrd/` folder of the Hugging Face dataset; the code is in
+`src/nedm/contact_nrd/`.
+
+**Follow-on work, not part of the paper:** [`so101_push_rl/`](so101_push_rl/README.md)
+trains one PPO policy inside a contact NRD of the SO101 arm and the T, then
+checks it in Chrono: it pushes the T to small and large translation and rotation
+goals (82–96 % of the sealed test goals of each trained goal type). The NRD, its
+training data, the RL inputs, the policies and the Chrono evaluations are in the
+`so101_push_rl/` folder of the Hugging Face dataset; the code is in
+`src/nedm/so101_push_rl/`, `scripts/so101_push_rl/` and `configs/so101_push_rl/`.
+
+**Follow-on work, not part of the paper:** [`g1_footstep_rl/`](g1_footstep_rl/README.md)
+trains a footstep policy with PPO inside the G1 contact NRD, then checks it in MuJoCo. The policy sets
+the velocity command of the frozen walking policy (HOMIE) so that the feet land on given footprints, on
+a flat floor and on planks with gaps: it completes 92–100 % of the development courses of each course
+type, a hand-written footstep controller 0–28 %. The policies, RL inputs, MuJoCo results and videos are
+in the `g1_footstep_rl/` folder of the Hugging Face dataset; the code is in `src/nedm/g1_footstep_rl/`,
+`scripts/g1_footstep_rl/` and `configs/g1_footstep_rl/`.
+
+**Follow-on work, not part of the paper:** [`so101_pick_place/`](so101_pick_place/README.md)
+trains a camera policy for a real SO101 arm only inside a contact NRD of the arm and a cube: a state
+teacher with PPO, then a camera student with online DAgger on ray-traced images of a calibrated copy of
+the real scene. With no real image in training, the student placed the cube on the plate in 36 of 50
+episodes of a stress test on the real arm (72 %; 95 % interval 58–83 %). The NRD, its data and sealed
+test set, every teacher and student checkpoint, the robot bundle, the robot logs and videos are in the
+`so101_pick_place/` folder of the Hugging Face dataset; the code is in `src/nedm/so101_policy/`,
+`src/nedm/render/`, `src/nedm/contact_nrd/collect/`, `scripts/so101_pick_place/` and `scripts/so101_policy/`.
+
+**[docs/progress.md](docs/progress.md) is the reproduction record** — every stage
+output with the artifact that produced it and the command that regenerates it.
+Start there.
+
+## Environment
+
+```bash
+conda env create -f environment.nedm.yml
+conda activate nedm
+git lfs install && git lfs pull
+```
+
+`environment.nedm.yml` (env `nedm`, pychrono 10.0.0 from the `projectchrono`
+channel) is what everything runs in: data collection, training, RL, and
+Chrono-backed evaluation. `environment.yml` (env `tutorial`, pychrono 9.0.1) and
+`environment.lock.yml` are retained for the earliest datasets, which were
+collected under it.
+
+Project Chrono itself is a local dependency, not vendored — collection configs
+expect a checkout at `chrono/` and read `chrono/data` for vehicle assets.
+
+## Layout
+
+Code, scripts and configs are grouped by study. `core` holds what both paper studies share.
+
+| Path | Contents |
+|---|---|
+| `src/nedm/core/` | Shared by both paper studies: preprocessing, the causal-transformer dynamics model and the trainer with rollout-based checkpoint selection (`training/`); the frozen NN-ROM loader and default paths (`rl/`); the scenario generator, the Hugging Face release helpers and the Blender export |
+| `src/nedm/hmmwv/` | Study Case I: HMMWV scene builders and data collectors (`hmmwv_data`, `hmmwv_crm`); the vectorized NN-ROM tracking environment, its Chrono-backed twins and the reference sets (`rl/`) |
+| `src/nedm/tracked_arm/` | Study Case II: M113 and arm data collectors (`tracked_vehicle_data`, `arm_data`); the 4-DOF gripper arm imported from SolidWorks (`arm_model/`); the goal and arm environments, arm forward kinematics and the clearance shield (`rl/`) |
+| `src/nedm/traversing/` | Traversing study code: model training (`training/`) and the Chrono evaluation class (`evaluation/`) |
+| `src/nedm/contact_nrd/` | Contact NRD: the three networks, training, test scores and the data download |
+| `src/nedm/so101_push_rl/` | SO101 push-T PPO inside the contact NRD: the NRD environment, action decoder, arm kinematics, reward and rules |
+| `src/nedm/g1_footstep_rl/` | G1 footstep PPO inside the contact NRD: courses and scorer, the NRD environment, the HOMIE copy, leg kinematics, the MuJoCo scene and runner, the hand-written footstep baseline (H-FS) |
+| `configs/hmmwv/`, `configs/tracked_arm/` | Collection and training configs |
+| `configs/contact_nrd/` | Training configs of the contact NRD (one for the first three cases, one for G1) and the G1 evaluation block |
+| `configs/so101_push_rl/` | Environment config, the two PPO curricula and the arm and T settings |
+| `configs/g1_footstep_rl/` | Environment config, PPO curriculum, MuJoCo scene and HOMIE sources of the G1 footstep study |
+| `traversing/` | Traversing study documents, results and release manifest |
+| `contact_nrd/` | Contact NRD design, results, the four study cases, the G1 data format and release manifest |
+| `so101_push_rl/` | SO101 push-T PPO study: results, the NRD it used and release manifest |
+| `g1_footstep_rl/` | G1 footstep PPO study: results, training, the NRD and HOMIE, release manifest |
+| `artifacts/` | Checkpoints, run metadata and Chrono evaluation output (datasets are on Hugging Face, see below) |
+
+`scripts/` is organised by study (`core/`, `hmmwv/`, `tracked_arm/`, `traversing/`, `so101_push_rl/`,
+`g1_footstep_rl/`), then by pipeline stage, in the order you would run them:
+
+| Path | Contents |
+|---|---|
+| `scripts/hmmwv/collection/` | Shard planners and Chrono collectors for the flat, bumpy and CRM datasets, plus their validators and small-scale smoke tests |
+| `scripts/tracked_arm/collection/` | The M113 drive collector (the arm collector is `python -m nedm.tracked_arm.arm_data`) |
+| `scripts/core/preprocess/` | Raw episodes → processed caches (all three dynamics models) |
+| `scripts/hmmwv/preprocess/`, `scripts/tracked_arm/preprocess/` | RL reference-set builders; arm FK geometry extraction |
+| `scripts/core/training/` | The dynamics trainer (all three dynamics models) |
+| `scripts/hmmwv/training/`, `scripts/tracked_arm/training/` | The three PPO trainers, and the launchers holding each run's exact hyperparameters |
+| `scripts/hmmwv/ablations/`, `scripts/tracked_arm/ablations/` | Config generation, sweep runners and ranking for Appendices C–E and the specialist comparison; the arm q-input probe |
+| `scripts/core/evaluation/` | Open-loop rollout eval of a dynamics checkpoint |
+| `scripts/hmmwv/evaluation/`, `scripts/tracked_arm/evaluation/` | Chrono closed-loop transfer, open-loop arm eval, and the seeded 100-goal benchmarks |
+| `scripts/hmmwv/figures/`, `scripts/tracked_arm/figures/` | The eleven generators behind the manuscript's plotted figures, plus the Blender renderers |
+| `scripts/core/throughput/`, `scripts/hmmwv/throughput/` | Chrono and NN-ROM throughput probes (Appendix A) and the context-truncation sweep |
+| `scripts/hmmwv/cluster/`, `scripts/tracked_arm/cluster/` | SLURM array jobs for the collections that only run at cluster scale |
+| `scripts/so101_push_rl/` | The SO101 push-T PPO trainer and `reproduce.sh` (download, training, NRD validation) |
+| `scripts/g1_footstep_rl/` | The G1 footstep PPO trainer, the MuJoCo evaluation, the H-FS parameter search, the bank builders, the HOMIE fetch and `reproduce.sh` |
+| `scripts/hmmwv/validation/` | Chrono validation harnesses for the tire-force channels (not a unit-test suite) |
+| `scripts/core/release/` | The Hugging Face dataset release: raw CSV → Parquet export, validation, upload, and the download/rehydrate helper |
+| `scripts/traversing/` | The traversing study's result recount (`analysis/`) and release download/verification (`release/`) |
+
+Every script under `scripts/core/`, `scripts/hmmwv/` and `scripts/tracked_arm/` reproduces something the paper
+reports; nothing else is kept. The ablation *artifacts* and *configs* keep their original `ablation_ofat` name
+because it is recorded inside the run metadata.
+
+The paper was produced with the earlier stage-first layout (`scripts//`, `src/nedm/{training,rl}/`,
+`src/arm_model/`, `test/`, `blender-render/`). That layout is kept at the GitHub tag
+[`paper-v1`](https://github.com/uwsbel/NeDM/tree/paper-v1); the Hugging Face dataset card
+(`docs/hf_dataset_card.md`, mirrored on the Hub) still names its paths.
+
+## Datasets
+
+All five datasets the paper's dynamics models train on are published at
+**** (70 GB: every recorded channel as
+float32 Parquet plus the four processed training caches; the dataset card documents schemas,
+splits and provenance). Nothing needs to be re-collected:
+
+```bash
+conda activate nedm
+# the exact .npy caches the deployed models trained on -> artifacts/training_datasets/
+PYTHONPATH=src python scripts/core/release/download_nedm_datasets.py --dataset all --no-raw --processed
+# a raw dataset as the collectors' per-episode CSV tree -> artifacts/datasets/ (preprocess etc. run unchanged)
+PYTHONPATH=src python scripts/core/release/download_nedm_datasets.py --dataset tracked --rehydrate
+```
+
+`docs/hf_dataset_card.md` is the source of the Hub README; `scripts/core/release/export_hf_dataset.py`
++ `validate_hf_export.py` + `upload_hf_dataset.sh` regenerate and publish the release.
+
+## Quick start
+
+Collect a small dataset, build its cache, and train:
+
+```bash
+conda activate nedm
+python scripts/hmmwv/collection/collect_hmmwv_dataset.py --config configs/hmmwv/hmmwv_overfit_v1.json
+python scripts/core/preprocess/build_hmmwv_training_dataset.py --help
+PYTHONPATH=src python scripts/core/training/train_hmmwv_dynamics.py \
+ --config configs/hmmwv/hmmwv_transformer_v07_tire_normal_force_omega_300g_crm2000_mix25_rebal_rollout_onehot.json
+```
+
+The full flat collection is cluster-scale (~305 GB of CSV; download it from Hugging Face
+instead, see above); `scripts/hmmwv/cluster/collect_hmmwv_tire300g.sh` is the job that produced it and
+`scripts/hmmwv/collection/smoke_test_hmmwv_bumpy10g.sh` rehearses the same path at small scale.
+
+Evaluate a trained policy back in Chrono:
+
+```bash
+PYTHONPATH=src python scripts/hmmwv/evaluation/eval_hmmwv_rl_chrono_tracking.py --help # Study Case I
+PYTHONPATH=src python scripts/tracked_arm/evaluation/benchmark_tracked_goal_chrono.py --help # Study Case II, base
+PYTHONPATH=src python scripts/tracked_arm/evaluation/benchmark_arm_reach_chrono.py --help # Study Case II, arm
+```
+
+## Further reading
+
+- [docs/model_checkpoints.md](docs/model_checkpoints.md) — the deployed checkpoints and how to load them
+- [docs/data_collection_pipeline.md](docs/data_collection_pipeline.md), [docs/hmmwv_crm_data_collection_pipeline.md](docs/hmmwv_crm_data_collection_pipeline.md) — collection design
+- [docs/hmmwv_training_pipeline.md](docs/hmmwv_training_pipeline.md), [docs/rl_tracking.md](docs/rl_tracking.md) — Study Case I
+- [docs/arm-dyn-model.md](docs/arm-dyn-model.md), [docs/arm-reaching-rl-plan.md](docs/arm-reaching-rl-plan.md), [docs/tracked_vehicle_nn_rom_rl_plan.md](docs/tracked_vehicle_nn_rom_rl_plan.md) — Study Case II
+- [docs/ablation_ofat_plan.md](docs/ablation_ofat_plan.md) — the ablation protocol
+- [deep-research-report-vehicle.md](deep-research-report-vehicle.md) — background survey on learned vehicle dynamics
diff --git a/so101_pick_place/code/REPRODUCE.md b/so101_pick_place/code/REPRODUCE.md
new file mode 100644
index 0000000000000000000000000000000000000000..c7573be9b0aab0c941fb79afb0131942bef2b829
--- /dev/null
+++ b/so101_pick_place/code/REPRODUCE.md
@@ -0,0 +1,44 @@
+# SO101 pick-and-place source release
+
+The study implementation, configs, requirements, full study README and original data manifest live here.
+The NeDM pull request keeps the results and pinned links. Source commit: `9363774e428a844540c525d3a6458beeb3e39e4d`; base: `dacc64968c006340393f60e7f1e15a2b65fc4aa7`.
+The 95 browsable source files retain their original paths and bytes. `source.tar.gz` contains the same files,
+including executable modes, and `source_manifest.json` records their sizes, SHA-256 values and Git modes.
+
+## Restore the study checkout
+
+Use the pinned download and checksum command in the NeDM study's
+[results README](https://github.com/uwsbel/NeDM/blob/so101-pick-place/so101_pick_place/README.md).
+It downloads this archive at the exact `code.hf_revision` of the compact GitHub release manifest.
+Then, from the directory containing the downloaded `source.tar.gz`:
+
+```bash
+GIT_LFS_SKIP_SMUDGE=1 git clone --no-checkout https://github.com/uwsbel/NeDM.git so101-study
+cd so101-study
+GIT_LFS_SKIP_SMUDGE=1 git checkout --detach dacc64968c006340393f60e7f1e15a2b65fc4aa7
+tar -xzf ../source.tar.gz --strip-components=1
+git fetch origin so101-pick-place-study
+```
+
+The base checkout supplies the existing NeDM contact-NRD model, training and evaluation code. The overlay supplies
+the whole study implementation, so it must be unpacked at the repository root. Git history is needed for the NRD
+retraining and equivalence steps; the historical study branch remains available for those steps.
+
+Read `so101_pick_place/README.md` in the restored checkout for the complete training chain, original validation,
+dependencies, deployment instructions and limitations. Install the GPU's torch/torchvision build, then this
+study's `requirements-so101-pick-place.txt`. Use `bash` to invoke scripts downloaded individually from the Hub,
+because Hub downloads do not preserve executable permissions; the tar archive does preserve them.
+
+```bash
+bash scripts/so101_pick_place/reproduce.sh --help
+bash scripts/so101_pick_place/reproduce.sh full --steps download,robot
+bash scripts/so101_pick_place/reproduce.sh full --steps download,nrd_test
+```
+
+The `robot` step above only rebuilds result tables from archived logs. Training and live robot operation are
+separate steps described in the full study README. The source archive preserves the original pinned data revision
+`dcb873bc5da3da8ad5abdec6137c77ef46038f43`; existing datasets, checkpoints, logs and videos are unchanged.
+
+The archived README and source comments describe the original code release. For current NeDM repository contents,
+use the results README linked above. Some older stages are recipe-only reruns, as documented there and in the
+full README; this source release does not change that limitation.
diff --git a/so101_pick_place/code/configs/contact_nrd/collection/so101_grasp.json b/so101_pick_place/code/configs/contact_nrd/collection/so101_grasp.json
new file mode 100644
index 0000000000000000000000000000000000000000..12d12e7f51d48ad0958c261232e7aad4fbbcaab9
--- /dev/null
+++ b/so101_pick_place/code/configs/contact_nrd/collection/so101_grasp.json
@@ -0,0 +1,344 @@
+{
+ "name": "so101_grasp",
+ "source_manifest": "contact_nrd/so101_grasp/source_manifest.json",
+ "record_step_s": 0.01,
+ "control_step_s": 0.02,
+ "model_step_s": 0.02,
+ "records_per_episode": 601,
+ "target_time_s": 4.0,
+ "warmup_s": 0.3,
+ "physics": {
+ "timestep_s": 0.0005,
+ "integrator": "implicitfast",
+ "cone": "elliptic",
+ "impratio": 10.0,
+ "solver": "newton",
+ "iterations": 100,
+ "ls_iterations": 50,
+ "tolerance": 1e-10,
+ "noslip_iterations": 0
+ },
+ "tight_solver": {
+ "iterations": 200,
+ "ls_iterations": 100,
+ "tolerance": 1e-12
+ },
+ "convergence": {
+ "master_seed": 20261085,
+ "episodes": {
+ "nominal": 16,
+ "off_centre": 4,
+ "one_sided": 4,
+ "near_miss": 4,
+ "weak_closure": 8,
+ "drop": 8,
+ "push": 4,
+ "free_arm": 2,
+ "cube_flight": 32,
+ "cube_table": 8,
+ "jaw_fixed": 8,
+ "jaw_moving": 8
+ }
+ },
+ "table": {
+ "center_xy_m": [
+ 0.25,
+ 0.0
+ ],
+ "size_xy_m": [
+ 1.2,
+ 1.2
+ ],
+ "thickness_m": 0.04,
+ "friction": [
+ 0.5,
+ 0.005,
+ 0.0001
+ ],
+ "condim": 3,
+ "solref": [
+ 0.005,
+ 1.0
+ ],
+ "solimp": [
+ 0.9,
+ 0.95,
+ 0.001,
+ 0.5,
+ 2.0
+ ],
+ "edge_margin_m": 0.05
+ },
+ "cube": {
+ "size_m": 0.03,
+ "mass_kg": 0.03,
+ "friction": [
+ 0.5,
+ 0.005,
+ 0.0001
+ ],
+ "condim": 3,
+ "solref": [
+ 0.005,
+ 1.0
+ ],
+ "solimp": [
+ 0.9,
+ 0.95,
+ 0.001,
+ 0.5,
+ 2.0
+ ],
+ "park_xy_m": [
+ 0.7,
+ 0.45
+ ]
+ },
+ "contact_threshold_n": 0.01,
+ "visual_overlap": {
+ "threshold_m": 0.001,
+ "grid_m": 0.0005,
+ "point_spacing_m": 0.002,
+ "cube_points_per_edge": 11
+ },
+ "joint_target_margin_rad": 0.05,
+ "palm_geoms": [
+ "gripper_collision0",
+ "fixed_jaw_box1",
+ "fixed_jaw_box2",
+ "moving_jaw_box1"
+ ],
+ "grasp_point_m": [
+ 0.0105,
+ 0.0,
+ -0.092
+ ],
+ "workspace": {
+ "pan_axis_xy_m": [
+ 0.0388,
+ 0.0
+ ],
+ "r_m": [
+ 0.15,
+ 0.27
+ ],
+ "angle_deg": [
+ -75,
+ 75
+ ]
+ },
+ "throw_region": {
+ "x_m": [
+ 0.45,
+ 0.7
+ ],
+ "y_m": [
+ -0.35,
+ 0.35
+ ]
+ },
+ "speed_rad_s": {
+ "arm": [
+ 1.0,
+ 2.0
+ ],
+ "jaw": 4.5,
+ "arm_max": 3.0
+ },
+ "ik": {
+ "position_tol_m": 0.0005,
+ "angle_tol_deg": 2.0
+ },
+ "workers": 6,
+ "campaigns": {
+ "pilot": {
+ "master_seed": 20261008,
+ "task_scale": 1.0,
+ "probe_scale": 1.0,
+ "note": "512 task episodes and the probes the coverage targets need; splits 0/1 by family"
+ },
+ "production": {
+ "master_seed": 20261021,
+ "task_scale": 35.15625,
+ "probe_scale": 10.0,
+ "note": "18,000 task episodes (nominal and difficult in the pilot ratio) and the probes at 10 times their pilot counts; splits 0/1, 90/10 inside each family: 16,197 + 1,803 task and 9,450 + 1,050 probe episodes"
+ },
+ "test": {
+ "master_seed": 20261034,
+ "task_scale": 3.90625,
+ "probe_scale": 1.0,
+ "note": "sealed test: 2,000 task episodes and the probes at their pilot counts; all split 2"
+ },
+ "extra": {
+ "master_seed": 20261123,
+ "task_scale": 70.3125,
+ "probe_scale": 1.0,
+ "note": "supplementary training data (2026-10-10): twice the production count of each task family (collect with --families for the hard ones); all split 0, so the production validation episodes stay the validation set"
+ },
+ "noisy_v1": {
+ "master_seed": 20261147,
+ "task_scale": 1.0,
+ "probe_scale": 1.0,
+ "families": [
+ "noisy_nominal",
+ "noisy_off_centre",
+ "noisy_carry",
+ "noisy_offset"
+ ],
+ "note": "NRD data round of the SO101 policy study (2026-10-11): scripted plans with policy-like commands (OU noise on the 5 arm targets, stationary std 5-20 mrad, time constant 0.1-0.4 s, a constant jaw-target offset of +-30 mrad, rate-limited like the data) and grasp-point targets 1-8 mm off the cube centre; 10,000 task episodes, splits 0/1 90/10 inside each family. Master seed new (not pilot, production, test 20261034, convergence, extra, critic noise 20261011)"
+ }
+ },
+ "families": [
+ {
+ "name": "nominal",
+ "group": "nominal",
+ "select": true,
+ "episodes": 320,
+ "records": 601,
+ "note": "approach, descend, close, lift to a random height, hold, move while holding (half), lower, release, retreat"
+ },
+ {
+ "name": "off_centre",
+ "group": "difficult",
+ "select": true,
+ "episodes": 32,
+ "records": 601,
+ "note": "grasp offset along the jaw width, the closing axis and the height; the cube can turn or slip in the grasp"
+ },
+ {
+ "name": "one_sided",
+ "group": "difficult",
+ "select": true,
+ "episodes": 32,
+ "records": 601,
+ "note": "only one jaw touches the cube on the table: a fixed-jaw side push, a moving-jaw swat or a fingertip tap"
+ },
+ {
+ "name": "near_miss",
+ "group": "difficult",
+ "select": true,
+ "episodes": 32,
+ "records": 601,
+ "note": "the jaws close 15-35 mm off the cube centre: an edge graze or nothing; lift, lower, release"
+ },
+ {
+ "name": "weak_closure",
+ "group": "difficult",
+ "select": true,
+ "episodes": 32,
+ "records": 601,
+ "note": "the jaw target is set at the measured contact angle plus a small opening; fast lift and shake; slip or drop"
+ },
+ {
+ "name": "drop",
+ "group": "difficult",
+ "select": true,
+ "episodes": 32,
+ "records": 601,
+ "note": "grasp and lift, then the jaw opens in the air: cube flight, table impact and tumbling"
+ },
+ {
+ "name": "push",
+ "group": "difficult",
+ "select": true,
+ "episodes": 32,
+ "records": 601,
+ "note": "closed jaws lowered beside the cube push it across the table"
+ },
+ {
+ "name": "free_arm",
+ "group": "probe",
+ "select": false,
+ "episodes": 100,
+ "records": 601,
+ "note": "random joint-space motion of the arm; the cube rests out of reach"
+ },
+ {
+ "name": "cube_flight",
+ "group": "probe",
+ "select": false,
+ "episodes": 650,
+ "records": 101,
+ "note": "cube thrown upwards above the table (1-2.2 m/s, spin up to 25 rad/s, landings up to about 2.6 m/s): flight, impacts, tumbling until it rests (1 s); the arm moves freely"
+ },
+ {
+ "name": "cube_table",
+ "group": "probe",
+ "select": false,
+ "episodes": 100,
+ "records": 101,
+ "note": "cube released just above the table with sliding velocity and spin: impacts, sliding, settling (1 s)"
+ },
+ {
+ "name": "jaw_fixed",
+ "group": "probe",
+ "select": false,
+ "episodes": 100,
+ "records": 201,
+ "note": "cube released just above the fixed jaw's inner face (held up, sloped along the finger), in the air; it rests or slides, then a fast arm move tips the face over: the cube falls to the table (or onto the arm base, which ends the episode) or stays on the gripper against a palm block"
+ },
+ {
+ "name": "jaw_moving",
+ "group": "probe",
+ "select": false,
+ "episodes": 100,
+ "records": 201,
+ "note": "cube released just above the moving jaw's inner face (held up, sloped along the finger), in the air; it rests or slides, then a fast arm move tips the face over: the cube falls to the table (or onto the arm base, which ends the episode) or stays on the gripper against a palm block"
+ },
+ {
+ "name": "step_arm",
+ "group": "probe",
+ "select": false,
+ "episodes": 3000,
+ "records": 201,
+ "note": "step commands of the arm joints and the jaw (held 0.1-0.6 s), servo saturation without contact; the cube rests out of reach (2 s). Only in campaign extra. The 2026-10-10 collection drew targets 0.05 rad inside the limits (15 % of its episodes passed a limit by up to 33 mrad); the code now keeps 0.12 rad",
+ "campaigns": [
+ "extra"
+ ]
+ },
+ {
+ "name": "noisy_nominal",
+ "group": "noisy",
+ "select": true,
+ "episodes": 2500,
+ "records": 601,
+ "campaigns": [
+ "noisy_v1"
+ ],
+ "note": "the nominal script (grasp at the cube centre, lift, hold, move while holding (half), lower, release, retreat); then policy-like commands: OU noise on the 5 arm targets (stationary std U(5, 20) mrad, time constant U(0.1, 0.4) s, per episode, independent per joint, from 0), a constant jaw-target offset U(-30, 30) mrad, clipped to the target range and rate-limited to 0.06 rad (arm) and 0.09 rad (jaw) per 20 ms (noisy_commands). Campaign noisy_v1 only"
+ },
+ {
+ "name": "noisy_off_centre",
+ "group": "noisy",
+ "select": true,
+ "episodes": 1500,
+ "records": 601,
+ "campaigns": [
+ "noisy_v1"
+ ],
+ "note": "the off_centre script (grasp offset 4-12 mm along the jaw width, +-3 mm along the closing axis, 0-12 mm higher); then policy-like commands: OU noise on the 5 arm targets (stationary std U(5, 20) mrad, time constant U(0.1, 0.4) s, per episode, independent per joint, from 0), a constant jaw-target offset U(-30, 30) mrad, clipped to the target range and rate-limited to 0.06 rad (arm) and 0.09 rad (jaw) per 20 ms (noisy_commands). Campaign noisy_v1 only"
+ },
+ {
+ "name": "noisy_carry",
+ "group": "noisy",
+ "select": true,
+ "episodes": 3000,
+ "records": 601,
+ "campaigns": [
+ "noisy_v1"
+ ],
+ "note": "carry and place: the nominal script with the move while holding always drawn (realised when it fits in 6 s and is reachable); then policy-like commands: OU noise on the 5 arm targets (stationary std U(5, 20) mrad, time constant U(0.1, 0.4) s, per episode, independent per joint, from 0), a constant jaw-target offset U(-30, 30) mrad, clipped to the target range and rate-limited to 0.06 rad (arm) and 0.09 rad (jaw) per 20 ms (noisy_commands). Campaign noisy_v1 only"
+ },
+ {
+ "name": "noisy_offset",
+ "group": "noisy",
+ "select": true,
+ "episodes": 3000,
+ "records": 601,
+ "campaigns": [
+ "noisy_v1"
+ ],
+ "note": "the nominal script with the grasp-point target 1-8 mm off the cube centre in a random horizontal direction (policy-like imprecision); then policy-like commands: OU noise on the 5 arm targets (stationary std U(5, 20) mrad, time constant U(0.1, 0.4) s, per episode, independent per joint, from 0), a constant jaw-target offset U(-30, 30) mrad, clipped to the target range and rate-limited to 0.06 rad (arm) and 0.09 rad (jaw) per 20 ms (noisy_commands). Campaign noisy_v1 only"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/so101_pick_place/code/configs/so101_pick_place/calib_v1.json b/so101_pick_place/code/configs/so101_pick_place/calib_v1.json
new file mode 100644
index 0000000000000000000000000000000000000000..f38702f13fdac737a6af78a16e03d0a274abdd48
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_pick_place/calib_v1.json
@@ -0,0 +1,1526 @@
+{
+ "version": "calib_v1",
+ "joint_map": {
+ "names": [
+ "shoulder_pan",
+ "shoulder_lift",
+ "elbow_flex",
+ "wrist_flex",
+ "wrist_roll",
+ "gripper"
+ ],
+ "sign": [
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1
+ ],
+ "offset_rad": [
+ 0.0,
+ -0.03189816653157993,
+ -0.14769081483654048,
+ -0.019577445234141684,
+ -1.3227713329150206,
+ 0.0
+ ],
+ "gripper_lin": [
+ 0.022960654771994715,
+ -0.1915981705843725
+ ],
+ "offset_deg": [
+ 0.0,
+ -1.8276303164649856,
+ -8.462060362981891,
+ -1.1217049855648262,
+ -75.78921463692504,
+ 0.0
+ ],
+ "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).",
+ "alternatives": {
+ "flat_table": {
+ "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",
+ "offset_deg": [
+ 0.0,
+ -3.122641288667537,
+ -8.38954493189108,
+ -0.7644935735601069,
+ -75.66093676419115,
+ 0.0
+ ],
+ "table_plane_coef": [
+ -0.008009308889286833,
+ -2.1491765199895853e-05,
+ 0.009612408187844257
+ ]
+ },
+ "gripper_lin_hold_width": {
+ "gripper_lin": [
+ 0.022960654771994715,
+ -0.15105075691406578
+ ],
+ "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)"
+ },
+ "gripper_lin_servo_slope": {
+ "gripper_lin": [
+ 0.023282692221604357,
+ -0.19964910682461356
+ ],
+ "note": "1:1 servo slope (1.334 deg/unit), offset matched at g = 25 (the middle of the observed range)"
+ }
+ }
+ },
+ "cameras": {
+ "external": {
+ "model": "opencv_fisheye",
+ "width": 640,
+ "height": 480,
+ "K": [
+ 270.9954603103234,
+ 261.8734348229722,
+ 327.2984559297393,
+ 242.2070590246824
+ ],
+ "D": [
+ 0.05934478263356295,
+ -0.06552001554295192,
+ 0.018633618776505437,
+ 0.0
+ ],
+ "parent": "world",
+ "T_parent_cam": [
+ 0.31363691894620577,
+ -0.4029396077403384,
+ 0.46435950260329845,
+ 0.36013966124320823,
+ -0.9273343294895559,
+ 0.05535449661100124,
+ -0.08536009286971218
+ ],
+ "rms_px": 1.2592991515134293,
+ "n_points": 380,
+ "holdout_rms_px": 2.068731133844219,
+ "rms_by_kind": {
+ "es": {
+ "n": 30,
+ "rms": 1.562940528989659,
+ "median": 1.351876056710025,
+ "p90": 2.1875282323495315
+ },
+ "ec": {
+ "n": 286,
+ "rms": 1.2340633600326392,
+ "median": 0.7186424447329098,
+ "p90": 2.09558948136562
+ },
+ "ep": {
+ "n": 60,
+ "rms": 1.1216415671467188,
+ "median": 0.810191148406559,
+ "p90": 1.6395210247420884
+ },
+ "em": {
+ "n": 4,
+ "rms": 2.1386814405510273,
+ "median": 1.817326270603266,
+ "p90": 2.98687427880641
+ },
+ "line": {
+ "n": 489,
+ "rms": 0.372576986624876,
+ "median": 0.11467553210897949,
+ "p90": 0.3616200999534955
+ }
+ },
+ "holdout_by_kind": {
+ "es": {
+ "n": 6,
+ "rms": 1.7000158762747766,
+ "median": 1.706206797407797,
+ "p90": 2.1722019728207553
+ },
+ "ec": {
+ "n": 8,
+ "rms": 3.147731448080604,
+ "median": 2.858126041312958,
+ "p90": 4.054635838769286
+ },
+ "ep": {
+ "n": 12,
+ "rms": 1.1054724131995697,
+ "median": 1.0500067829916078,
+ "p90": 1.505015106251997
+ }
+ },
+ "field_of_view_deg": {
+ "horizontal": 134.2678287247104,
+ "vertical": 103.25719491947129,
+ "off_axis_angle_at": {
+ "left": 68.8428372260975,
+ "right": 65.4249914986129,
+ "top": 52.22183194012677,
+ "bottom": 51.03536297934451,
+ "tl": 85.94877022230551,
+ "tr": 83.77159508343836,
+ "bl": 85.36151345130384,
+ "br": 83.12978831098856
+ }
+ },
+ "monotonic_up_to_deg": 100.0
+ },
+ "wrist": {
+ "model": "opencv_fisheye",
+ "width": 640,
+ "height": 480,
+ "K": [
+ 270.3644876253468,
+ 269.3012989566298,
+ 320.8374595779736,
+ 247.34515999152364
+ ],
+ "D": [
+ 0.019374438138353576,
+ -0.013656734022638041,
+ 0.0,
+ 0.0
+ ],
+ "parent": "camera_mount",
+ "T_parent_cam": [
+ 0.007351691658097521,
+ 0.07103337062823585,
+ -0.005855746112084782,
+ 0.2150442533481458,
+ 0.975426158417913,
+ -0.046165552522736186,
+ -0.012981538286402914
+ ],
+ "rms_px": 3.2624611907480996,
+ "n_points": 11359,
+ "holdout_rms_px": 4.5798765265510655,
+ "rms_by_kind": {
+ "ws": {
+ "n": 2497,
+ "rms": 2.1190160729947656,
+ "median": 1.4863094104400525,
+ "p90": 3.3104130226497133
+ },
+ "wp": {
+ "n": 3468,
+ "rms": 2.6963133412348492,
+ "median": 2.017160729970648,
+ "p90": 4.230368986949722
+ },
+ "wm": {
+ "n": 5379,
+ "rms": 3.962202165156834,
+ "median": 2.733035025328462,
+ "p90": 6.667430097384301
+ },
+ "wc": {
+ "n": 15,
+ "rms": 1.4435558030725049,
+ "median": 0.36865684647750446,
+ "p90": 2.6545733167704513
+ }
+ },
+ "holdout_by_kind": {
+ "ws": {
+ "n": 504,
+ "rms": 6.548088395063642,
+ "median": 5.253529952974112,
+ "p90": 9.769261065314838
+ },
+ "wp": {
+ "n": 712,
+ "rms": 3.604175570470226,
+ "median": 2.7215718884717535,
+ "p90": 5.6021889074205555
+ },
+ "wc": {
+ "n": 3,
+ "rms": 10.083291990676772,
+ "median": 11.39883195508622,
+ "p90": 12.54352280111784
+ },
+ "wm": {
+ "n": 1213,
+ "rms": 4.045053073976811,
+ "median": 2.648599720729882,
+ "p90": 6.769268538306048
+ }
+ },
+ "field_of_view_deg": {
+ "horizontal": 135.3573319369848,
+ "vertical": 101.22620821512568,
+ "off_axis_angle_at": {
+ "left": 67.97759774649298,
+ "right": 67.37973419049182,
+ "top": 52.276060549439066,
+ "bottom": 48.950147665686615,
+ "tl": 88.85736878036911,
+ "tr": 88.25990251286534,
+ "bl": 86.23506804399645,
+ "br": 85.65130448187536
+ }
+ },
+ "monotonic_up_to_deg": 100.0
+ }
+ },
+ "time_offset_frames": {
+ "external": -1.4277886844891619,
+ "wrist": -1.2727768244696938
+ },
+ "episodes": [
+ {
+ "dataset": "green_cube_red_plate",
+ "episode": 0,
+ "cube_start_xyz": [
+ 0.2922240844678056,
+ -0.08237138900679891,
+ -0.001833608455945452
+ ],
+ "cube_start_yaw_deg": -13.08489835802935,
+ "cube_start_yaw_silhouette_deg": 28.07915925002419,
+ "plate_xy": [
+ 0.25192569147494603,
+ 0.1331498858001346
+ ],
+ "plate_yaw_deg": -1.6740143854602323,
+ "grasp_frame": 175,
+ "release_frame": 296,
+ "cube_end_xyz": [
+ 0.24741904110977161,
+ 0.1285688428628516,
+ 0.007574393866097578
+ ],
+ "cube_end_yaw_deg": 2.8982100687915704,
+ "cube_end_yaw_silhouette_deg": -3.1184593369744107,
+ "p_grip": [
+ 0.0059446855238881186,
+ -0.004504709202517019,
+ -0.09322332889544027
+ ],
+ "n_frames": 454,
+ "start_pose_deg": [
+ 1.4065934419631958,
+ -88.21977996826172,
+ 84.57142639160156,
+ 57.89011001586914,
+ 1.3626374006271362,
+ 30.895915985107422
+ ],
+ "sim_check": {
+ "cube_r": 0.2664747873913306,
+ "cube_angle_deg": -18.005912319982592,
+ "cube_in_annulus": true,
+ "plate_r": 0.2512995273677664,
+ "plate_angle_deg": 31.995006283950232,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.21925642606822884,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": 11.410883972569117,
+ "turn_within_30": true,
+ "task_in_sim_distribution": true
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate",
+ "episode": 1,
+ "cube_start_xyz": [
+ 0.36177125454191705,
+ 0.10925312674967667,
+ -0.0008469495547748368
+ ],
+ "cube_start_yaw_deg": 4.334782135288606,
+ "cube_start_yaw_silhouette_deg": 43.08942589811704,
+ "plate_xy": [
+ 0.2515983620370499,
+ 0.13046661958289843
+ ],
+ "plate_yaw_deg": -0.725114887527873,
+ "grasp_frame": 265,
+ "release_frame": 438,
+ "cube_end_xyz": [
+ 0.2521431014955,
+ 0.13400820634125934,
+ 0.007502277115549797
+ ],
+ "cube_end_yaw_deg": 4.392105835124141,
+ "cube_end_yaw_silhouette_deg": -25.570433378754842,
+ "p_grip": [
+ 0.006802686869003093,
+ 0.0015230349977821786,
+ -0.10768474370877577
+ ],
+ "n_frames": 618,
+ "start_pose_deg": [
+ 2.549450635910034,
+ -88.13186645507812,
+ 81.05494689941406,
+ 68.87911987304688,
+ -0.9230769276618958,
+ 31.225296020507812
+ ],
+ "sim_check": {
+ "cube_r": 0.3409496692548047,
+ "cube_angle_deg": 18.68939699205513,
+ "cube_in_annulus": false,
+ "plate_r": 0.24960905775039513,
+ "plate_angle_deg": 31.51245064324276,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.11219660654883537,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -5.059897022816479,
+ "turn_within_30": true,
+ "task_in_sim_distribution": false
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate",
+ "episode": 2,
+ "cube_start_xyz": [
+ 0.24830345776541993,
+ -0.0687186101373142,
+ 1.6230182825906214e-05
+ ],
+ "cube_start_yaw_deg": 4.917583034467697,
+ "cube_start_yaw_silhouette_deg": -41.88437002726664,
+ "plate_xy": [
+ 0.25285443485312337,
+ 0.13266698860698123
+ ],
+ "plate_yaw_deg": -2.0603295571042324,
+ "grasp_frame": 113,
+ "release_frame": 228,
+ "cube_end_xyz": [
+ 0.2549004415358194,
+ 0.12579343252907302,
+ 0.00725103408286417
+ ],
+ "cube_end_yaw_deg": 1.3960516259329552,
+ "cube_end_yaw_silhouette_deg": -17.24840737508157,
+ "p_grip": [
+ 0.006331398171498901,
+ -0.0031136446511145772,
+ -0.10366927506225715
+ ],
+ "n_frames": 373,
+ "start_pose_deg": [
+ -4.131868362426758,
+ -88.21977996826172,
+ 82.10989379882812,
+ 65.18681335449219,
+ -4.9670329093933105,
+ 32.015811920166016
+ ],
+ "sim_check": {
+ "cube_r": 0.22048570519394511,
+ "cube_angle_deg": -18.159854916278015,
+ "cube_in_annulus": true,
+ "plate_r": 0.25183294253598937,
+ "plate_angle_deg": 31.78987085334917,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.20143701440909803,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -6.977912591571936,
+ "turn_within_30": true,
+ "task_in_sim_distribution": true
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate",
+ "episode": 3,
+ "cube_start_xyz": [
+ 0.18466875758532686,
+ 0.04716400265690074,
+ 0.00446111621746428
+ ],
+ "cube_start_yaw_deg": -2.1670829558666895,
+ "cube_start_yaw_silhouette_deg": -15.657193476388784,
+ "plate_xy": [
+ 0.2514778596791974,
+ 0.13148083796407223
+ ],
+ "plate_yaw_deg": -1.3396439474038928,
+ "grasp_frame": 149,
+ "release_frame": 263,
+ "cube_end_xyz": [
+ 0.24371158457013986,
+ 0.1174070462330751,
+ 0.007504414344891259
+ ],
+ "cube_end_yaw_deg": 0.27668448000747503,
+ "cube_end_yaw_silhouette_deg": 5.685983209525148,
+ "p_grip": [
+ 0.006375063365364854,
+ 0.011869139608925073,
+ -0.08624019095690287
+ ],
+ "n_frames": 410,
+ "start_pose_deg": [
+ 6.769230842590332,
+ -88.13186645507812,
+ 81.23076629638672,
+ 67.82417297363281,
+ 4.439560413360596,
+ 39.525691986083984
+ ],
+ "sim_check": {
+ "cube_r": 0.15330406904615088,
+ "cube_angle_deg": 17.91766779264547,
+ "cube_in_annulus": true,
+ "plate_r": 0.250038162586152,
+ "plate_angle_deg": 31.72501645689727,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.1075768787370497,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": 0.8274390084627967,
+ "turn_within_30": true,
+ "task_in_sim_distribution": true
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate",
+ "episode": 4,
+ "cube_start_xyz": [
+ 0.34814450267731467,
+ 0.020158225264894875,
+ -0.0019868733547590348
+ ],
+ "cube_start_yaw_deg": 1.4161929174319425,
+ "cube_start_yaw_silhouette_deg": -25.502347522400267,
+ "plate_xy": [
+ 0.2519098724004053,
+ 0.1333224186841573
+ ],
+ "plate_yaw_deg": -0.7336327571526198,
+ "grasp_frame": 129,
+ "release_frame": 237,
+ "cube_end_xyz": [
+ 0.24041476801432177,
+ 0.13120653890355088,
+ 0.007877852786357796
+ ],
+ "cube_end_yaw_deg": 17.838345302111094,
+ "cube_end_yaw_silhouette_deg": -2.0988315791528294,
+ "p_grip": [
+ 0.006794340565046262,
+ 0.005454148916516266,
+ -0.10315095660370299
+ ],
+ "n_frames": 347,
+ "start_pose_deg": [
+ 9.670330047607422,
+ -87.86813354492188,
+ 83.69230651855469,
+ 59.82417678833008,
+ 12.615385055541992,
+ 39.06455993652344
+ ],
+ "sim_check": {
+ "cube_r": 0.3100006054550626,
+ "cube_angle_deg": 3.728369308776301,
+ "cube_in_annulus": false,
+ "plate_r": 0.2513775746527736,
+ "plate_angle_deg": 32.030267944957906,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.1485504585545453,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -2.1498256745845623,
+ "turn_within_30": true,
+ "task_in_sim_distribution": false
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 0,
+ "cube_start_xyz": [
+ 0.3362984123885602,
+ 0.03362302211608906,
+ -0.0013083058566654288
+ ],
+ "cube_start_yaw_deg": 17.231553510337662,
+ "cube_start_yaw_silhouette_deg": 3.4619090812536797,
+ "plate_xy": [
+ 0.23775179307229014,
+ 0.09426941804957464
+ ],
+ "plate_yaw_deg": -0.8671598522726214,
+ "grasp_frame": 227,
+ "release_frame": 523,
+ "cube_end_xyz": [
+ 0.23745046908400183,
+ 0.08135624656505,
+ 0.007070370607670854
+ ],
+ "cube_end_yaw_deg": 25.02836142856748,
+ "cube_end_yaw_silhouette_deg": 34.94908225053723,
+ "p_grip": [
+ 0.006871078695017272,
+ 0.005258328341525626,
+ -0.09552328563980401
+ ],
+ "n_frames": 721,
+ "start_pose_deg": [
+ -3.780219793319702,
+ -88.13186645507812,
+ 86.5054931640625,
+ 51.736263275146484,
+ 2.3296704292297363,
+ 5.731225490570068
+ ],
+ "sim_check": {
+ "cube_r": 0.29939240636651565,
+ "cube_angle_deg": 6.44815922199851,
+ "cube_in_annulus": false,
+ "plate_r": 0.2201557156788913,
+ "plate_angle_deg": 25.35301905515907,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.11571266792528355,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -18.098713362610283,
+ "turn_within_30": true,
+ "task_in_sim_distribution": false
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 1,
+ "cube_start_xyz": [
+ 0.24310267523306428,
+ 0.03441436148265043,
+ 0.002099439797836814
+ ],
+ "cube_start_yaw_deg": 7.173328412449337,
+ "cube_start_yaw_silhouette_deg": -30.695586552993007,
+ "plate_xy": [
+ 0.2463060534247659,
+ -0.06612282182324314
+ ],
+ "plate_yaw_deg": -1.635638213195314,
+ "grasp_frame": 246,
+ "release_frame": 485,
+ "cube_end_xyz": [
+ 0.2451054841944107,
+ -0.07432431001874013,
+ 0.00393286163497124
+ ],
+ "cube_end_yaw_deg": -0.5444850378216728,
+ "cube_end_yaw_silhouette_deg": 28.35088977874102,
+ "p_grip": [
+ 0.007171254664335991,
+ 0.011681074044125066,
+ -0.09421128301367335
+ ],
+ "n_frames": 667,
+ "start_pose_deg": [
+ 6.769230842590332,
+ -88.21977996826172,
+ 84.04395294189453,
+ 68.35164642333984,
+ 2.9450550079345703,
+ 0.7246376872062683
+ ],
+ "sim_check": {
+ "cube_r": 0.20718091462208935,
+ "cube_angle_deg": 9.561593615070922,
+ "cube_in_annulus": true,
+ "plate_r": 0.21778656931452442,
+ "plate_angle_deg": -17.674734843066297,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.10058820437268931,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -8.80896662564465,
+ "turn_within_30": true,
+ "task_in_sim_distribution": true
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 2,
+ "cube_start_xyz": [
+ 0.32817551420492297,
+ -0.08364074027858599,
+ -0.003165892909052233
+ ],
+ "cube_start_yaw_deg": 1.544501346832135,
+ "cube_start_yaw_silhouette_deg": 43.80362067343265,
+ "plate_xy": [
+ 0.3160766805373744,
+ 0.04638385584626384
+ ],
+ "plate_yaw_deg": -6.643819453476887,
+ "grasp_frame": 251,
+ "release_frame": 452,
+ "cube_end_xyz": [
+ 0.31606217386098107,
+ 0.03924854224960805,
+ 0.003434922175829155
+ ],
+ "cube_end_yaw_deg": 3.729485391724751,
+ "cube_end_yaw_silhouette_deg": -11.573424331640126,
+ "p_grip": [
+ 0.006658822937748594,
+ 0.0024152636397525937,
+ -0.09584952728272615
+ ],
+ "n_frames": 625,
+ "start_pose_deg": [
+ 15.032966613769531,
+ -88.30769348144531,
+ 80.35164642333984,
+ 73.71428680419922,
+ 5.406593322753906,
+ 1.383399248123169
+ ],
+ "sim_check": {
+ "cube_r": 0.3012207855638675,
+ "cube_angle_deg": -16.121343545617613,
+ "cube_in_annulus": false,
+ "plate_r": 0.28112954247640387,
+ "plate_angle_deg": 9.496714017855188,
+ "plate_in_annulus": false,
+ "cube_plate_dist": 0.1305862832518995,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -8.188320800309022,
+ "turn_within_30": true,
+ "task_in_sim_distribution": false
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 3,
+ "cube_start_xyz": [
+ 0.23693331324341219,
+ 0.11404958195243715,
+ 0.003786421016462217
+ ],
+ "cube_start_yaw_deg": 9.509931596053292,
+ "cube_start_yaw_silhouette_deg": 1.585706222508179,
+ "plate_xy": [
+ 0.21896506094674684,
+ -0.09300922065067556
+ ],
+ "plate_yaw_deg": -5.738457255660862,
+ "grasp_frame": 275,
+ "release_frame": 614,
+ "cube_end_xyz": [
+ 0.2129822983387097,
+ -0.10022411664794635,
+ 0.0046268487689335065
+ ],
+ "cube_end_yaw_deg": -5.3548402780715065,
+ "cube_end_yaw_silhouette_deg": 20.468108046783527,
+ "p_grip": [
+ 0.005881383552392475,
+ -0.0003234354715301664,
+ -0.08855879013053385
+ ],
+ "n_frames": 769,
+ "start_pose_deg": [
+ 12.131868362426758,
+ -87.95604705810547,
+ 79.82417297363281,
+ 75.38461303710938,
+ 5.758241653442383,
+ 0.7246376872062683
+ ],
+ "sim_check": {
+ "cube_r": 0.2286134662707728,
+ "cube_angle_deg": 29.925609736612984,
+ "cube_in_annulus": true,
+ "plate_r": 0.20275641620425,
+ "plate_angle_deg": -27.304795831132388,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.2078369693438379,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -15.248388851714157,
+ "turn_within_30": true,
+ "task_in_sim_distribution": true
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 4,
+ "cube_start_xyz": [
+ 0.21193264031596862,
+ -0.10428216999188723,
+ 0.0006874141944178958
+ ],
+ "cube_start_yaw_deg": 5.806186887957097,
+ "cube_start_yaw_silhouette_deg": 21.93948538973359,
+ "plate_xy": [
+ 0.3350434767604382,
+ -0.05952046219217152
+ ],
+ "plate_yaw_deg": -5.146533225050717,
+ "grasp_frame": 259,
+ "release_frame": 461,
+ "cube_end_xyz": [
+ 0.3372310339033622,
+ -0.07075477507605178,
+ 0.0006441606276854188
+ ],
+ "cube_end_yaw_deg": 18.872738044470168,
+ "cube_end_yaw_silhouette_deg": -30.60400972439311,
+ "p_grip": [
+ 0.006366142270968058,
+ 0.0017110546234158633,
+ -0.09914164438208337
+ ],
+ "n_frames": 719,
+ "start_pose_deg": [
+ 13.362637519836426,
+ -87.95604705810547,
+ 80.43955993652344,
+ 71.69230651855469,
+ 3.2087912559509277,
+ 0.5928853750228882
+ ],
+ "sim_check": {
+ "cube_r": 0.20211304292646584,
+ "cube_angle_deg": -31.061619301920906,
+ "cube_in_annulus": true,
+ "plate_r": 0.30216366913095627,
+ "plate_angle_deg": -11.360463746915734,
+ "plate_in_annulus": false,
+ "cube_plate_dist": 0.13099575769926322,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -10.952720113007814,
+ "turn_within_30": true,
+ "task_in_sim_distribution": false
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 5,
+ "cube_start_xyz": [
+ 0.3134928060010325,
+ -0.05422882329767086,
+ -0.0020912052763076873
+ ],
+ "cube_start_yaw_deg": 8.641153443739185,
+ "cube_start_yaw_silhouette_deg": -8.436737907580891,
+ "plate_xy": [
+ 0.15766258264189403,
+ 0.1346439771632627
+ ],
+ "plate_yaw_deg": -4.384619095841259,
+ "grasp_frame": 215,
+ "release_frame": 492,
+ "cube_end_xyz": [
+ 0.16115728431797743,
+ 0.12884156858252127,
+ 0.010720153062789117
+ ],
+ "cube_end_yaw_deg": 40.9672705439051,
+ "cube_end_yaw_silhouette_deg": -3.4406897443341222,
+ "p_grip": [
+ 0.006503568456744795,
+ 0.00409745151635252,
+ -0.09070305582845196
+ ],
+ "n_frames": 662,
+ "start_pose_deg": [
+ 11.780220031738281,
+ -88.13186645507812,
+ 81.05494689941406,
+ 73.0988998413086,
+ 3.912087917327881,
+ 0.7246376872062683
+ ],
+ "sim_check": {
+ "cube_r": 0.2799944694899721,
+ "cube_angle_deg": -11.167517729365366,
+ "cube_in_annulus": false,
+ "plate_r": 0.1796032130521119,
+ "plate_angle_deg": 48.562203543461514,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.2448591294318319,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -13.025772539580444,
+ "turn_within_30": true,
+ "task_in_sim_distribution": false
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 6,
+ "cube_start_xyz": [
+ 0.32511099449985625,
+ 0.040601883662711995,
+ -0.0007728228538362823
+ ],
+ "cube_start_yaw_deg": 13.573430330752245,
+ "cube_start_yaw_silhouette_deg": -37.601592450039334,
+ "plate_xy": [
+ 0.20170285802793997,
+ -0.13275250337582703
+ ],
+ "plate_yaw_deg": -4.832110736310625,
+ "grasp_frame": 235,
+ "release_frame": 535,
+ "cube_end_xyz": [
+ 0.20221573717492425,
+ -0.1373753136656336,
+ 0.004336639428636529
+ ],
+ "cube_end_yaw_deg": -10.98473776596893,
+ "cube_end_yaw_silhouette_deg": 29.31948243336774,
+ "p_grip": [
+ 0.006644944584108808,
+ 0.006780973739959127,
+ -0.09070852660906625
+ ],
+ "n_frames": 738,
+ "start_pose_deg": [
+ 7.208791255950928,
+ -88.04395294189453,
+ 80.0,
+ 73.18681335449219,
+ 2.4175825119018555,
+ 0.7246376872062683
+ ],
+ "sim_check": {
+ "cube_r": 0.2891755496726117,
+ "cube_angle_deg": 8.071320666313655,
+ "cube_in_annulus": false,
+ "plate_r": 0.21014416077117187,
+ "plate_angle_deg": -39.177217673241394,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.21279405925208228,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -18.40554106706287,
+ "turn_within_30": true,
+ "task_in_sim_distribution": false
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 7,
+ "cube_start_xyz": [
+ 0.3358569124310158,
+ -0.04939976482839293,
+ -0.0028167951824430403
+ ],
+ "cube_start_yaw_deg": 4.948931371879411,
+ "cube_start_yaw_silhouette_deg": -34.71620852640831,
+ "plate_xy": [
+ 0.16382104319681312,
+ 0.03666171711010693
+ ],
+ "plate_yaw_deg": -6.144857392913153,
+ "grasp_frame": 250,
+ "release_frame": 466,
+ "cube_end_xyz": [
+ 0.16226090422382297,
+ 0.03480294570318543,
+ 0.008953120618880534
+ ],
+ "cube_end_yaw_deg": 6.517096960009326,
+ "cube_end_yaw_silhouette_deg": 7.156521236313893,
+ "p_grip": [
+ 0.006360686653333365,
+ 0.0001542840366439142,
+ -0.09936972528821529
+ ],
+ "n_frames": 683,
+ "start_pose_deg": [
+ 8.263736724853516,
+ -88.21977996826172,
+ 79.03296661376953,
+ 76.79120635986328,
+ 5.758241653442383,
+ 0.7246376872062683
+ ],
+ "sim_check": {
+ "cube_r": 0.30113642421359244,
+ "cube_angle_deg": -9.441730241532468,
+ "cube_in_annulus": false,
+ "plate_r": 0.13028561986451506,
+ "plate_angle_deg": 16.343478076455444,
+ "plate_in_annulus": false,
+ "cube_plate_dist": 0.19236142798549408,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -11.093788764792563,
+ "turn_within_30": true,
+ "task_in_sim_distribution": false
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 8,
+ "cube_start_xyz": [
+ 0.22600836460100854,
+ 0.13419560045529497,
+ 0.004554138786007456
+ ],
+ "cube_start_yaw_deg": 9.655842462625984,
+ "cube_start_yaw_silhouette_deg": -10.124904042255366,
+ "plate_xy": [
+ 0.1877809533535277,
+ -0.08890757867773201
+ ],
+ "plate_yaw_deg": -5.147258848310777,
+ "grasp_frame": 238,
+ "release_frame": 414,
+ "cube_end_xyz": [
+ 0.18693319596072389,
+ -0.0916222193040863,
+ 0.005733243034075623
+ ],
+ "cube_end_yaw_deg": -3.2933907345142046,
+ "cube_end_yaw_silhouette_deg": 11.907414960267488,
+ "p_grip": [
+ 0.006347298849924511,
+ 0.006755526159009365,
+ -0.09130915095186147
+ ],
+ "n_frames": 525,
+ "start_pose_deg": [
+ 8.527472496032715,
+ -88.21977996826172,
+ 80.43955993652344,
+ 72.21977996826172,
+ 3.912087917327881,
+ 0.7246376872062683
+ ],
+ "sim_check": {
+ "cube_r": 0.23033764555135425,
+ "cube_angle_deg": 35.63389316744528,
+ "cube_in_annulus": true,
+ "plate_r": 0.1734931756826853,
+ "plate_angle_deg": -30.827546138227383,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.2263545084816018,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -14.80310131093676,
+ "turn_within_30": true,
+ "task_in_sim_distribution": true
+ }
+ },
+ {
+ "dataset": "green_cube_red_plate_1",
+ "episode": 9,
+ "cube_start_xyz": [
+ 0.3339740883823542,
+ -0.04216628504553652,
+ -0.002615412576366962
+ ],
+ "cube_start_yaw_deg": 8.689959188177355,
+ "cube_start_yaw_silhouette_deg": -3.719106369436304,
+ "plate_xy": [
+ 0.18194602497979362,
+ -0.13559693220556127
+ ],
+ "plate_yaw_deg": -5.986317204415101,
+ "grasp_frame": 191,
+ "release_frame": 361,
+ "cube_end_xyz": [
+ 0.18463537950243214,
+ -0.1365156133112859,
+ 0.004992519054821343
+ ],
+ "cube_end_yaw_deg": -6.559622628092129,
+ "cube_end_yaw_silhouette_deg": 22.289686286406322,
+ "p_grip": [
+ 0.006450193202969755,
+ 0.005320314744372343,
+ -0.09915379507440343
+ ],
+ "n_frames": 523,
+ "start_pose_deg": [
+ 13.01098918914795,
+ -88.04395294189453,
+ 79.20879364013672,
+ 76.26373291015625,
+ 7.780219554901123,
+ 0.7246376872062683
+ ],
+ "sim_check": {
+ "cube_r": 0.2981706525580532,
+ "cube_angle_deg": -8.12982807314328,
+ "cube_in_annulus": false,
+ "plate_r": 0.19717330572639713,
+ "plate_angle_deg": -43.44865873344575,
+ "plate_in_annulus": true,
+ "cube_plate_dist": 0.1784427580224931,
+ "dist_in_6_30cm": true,
+ "yaw_turn_deg": -14.676276392592456,
+ "turn_within_30": true,
+ "task_in_sim_distribution": false
+ }
+ }
+ ],
+ "scene": {
+ "mat": {
+ "corners_xy": [
+ [
+ 0.4415421393776707,
+ 0.2154313577822069
+ ],
+ [
+ 0.13464808253175026,
+ 0.2361415190848988
+ ],
+ [
+ 0.10367857174908096,
+ -0.22278097136385888
+ ],
+ [
+ 0.4105726285950014,
+ -0.24349113266655079
+ ]
+ ],
+ "center_xy": [
+ 0.2726103555633758,
+ -0.00367480679082599
+ ],
+ "yaw_deg": -3.8606433112404153,
+ "size_xy": [
+ 0.30759205599061,
+ 0.45996626271696056
+ ],
+ "z": 0.001
+ },
+ "plate_top_z": 0.0039031332928005,
+ "plate_thickness": 0.0039031332928005,
+ "plate_size": 0.05,
+ "cube_size": 0.03,
+ "table_plane": {
+ "coef": [
+ -0.004681260916979778,
+ -0.03640954226125585,
+ 0.01836320115536056
+ ],
+ "meaning": "table top z = c0 + c1 * x + c2 * y in the arm-base frame (m)",
+ "tilt_deg": [
+ -2.086113105573168,
+ 1.0521339245519172
+ ]
+ },
+ "colors_srgb": {
+ "external": {
+ "cube": {
+ "mean_srgb": [
+ 18.4,
+ 104.0,
+ 42.3
+ ],
+ "median_srgb": [
+ 15.0,
+ 105.0,
+ 41.0
+ ],
+ "mean_linear": [
+ 0.0063,
+ 0.1384,
+ 0.0235
+ ],
+ "n_pixels": 34326,
+ "n_frames": 266
+ },
+ "plate": {
+ "mean_srgb": [
+ 151.9,
+ 18.1,
+ 25.9
+ ],
+ "median_srgb": [
+ 151.0,
+ 16.0,
+ 25.0
+ ],
+ "mean_linear": [
+ 0.3136,
+ 0.0061,
+ 0.0102
+ ],
+ "n_pixels": 66214,
+ "n_frames": 256
+ },
+ "mat": {
+ "mean_srgb": [
+ 23.5,
+ 26.9,
+ 20.0
+ ],
+ "median_srgb": [
+ 23.0,
+ 25.0,
+ 18.0
+ ],
+ "mean_linear": [
+ 0.0089,
+ 0.0109,
+ 0.007
+ ],
+ "n_pixels": 4033810,
+ "n_frames": 268
+ },
+ "floor": {
+ "mean_srgb": [
+ 165.7,
+ 171.0,
+ 165.5
+ ],
+ "median_srgb": [
+ 166.0,
+ 169.0,
+ 165.0
+ ],
+ "mean_linear": [
+ 0.3797,
+ 0.4072,
+ 0.3786
+ ],
+ "n_pixels": 2727704,
+ "n_frames": 268
+ },
+ "arm_white": {
+ "mean_srgb": [
+ 133.9,
+ 135.7,
+ 115.5
+ ],
+ "median_srgb": [
+ 131.0,
+ 133.0,
+ 113.0
+ ],
+ "mean_linear": [
+ 0.2381,
+ 0.2451,
+ 0.1732
+ ],
+ "n_pixels": 64104,
+ "n_frames": 30
+ },
+ "servo_black": {
+ "mean_srgb": [
+ 19.2,
+ 20.3,
+ 10.2
+ ],
+ "median_srgb": [
+ 14.0,
+ 15.0,
+ 4.0
+ ],
+ "mean_linear": [
+ 0.0066,
+ 0.0072,
+ 0.0031
+ ],
+ "n_pixels": 22631,
+ "n_frames": 30
+ }
+ },
+ "wrist": {
+ "cube": {
+ "mean_srgb": [
+ 17.3,
+ 169.8,
+ 81.1
+ ],
+ "median_srgb": [
+ 16.0,
+ 175.0,
+ 84.0
+ ],
+ "mean_linear": [
+ 0.0057,
+ 0.4008,
+ 0.0825
+ ],
+ "n_pixels": 761124,
+ "n_frames": 268
+ },
+ "plate": {
+ "mean_srgb": [
+ 217.2,
+ 36.2,
+ 38.6
+ ],
+ "median_srgb": [
+ 209.0,
+ 28.0,
+ 30.0
+ ],
+ "mean_linear": [
+ 0.6956,
+ 0.0178,
+ 0.02
+ ],
+ "n_pixels": 565562,
+ "n_frames": 239
+ },
+ "mat": {
+ "mean_srgb": [
+ 44.1,
+ 48.7,
+ 42.9
+ ],
+ "median_srgb": [
+ 41.0,
+ 46.0,
+ 41.0
+ ],
+ "mean_linear": [
+ 0.0252,
+ 0.0303,
+ 0.0241
+ ],
+ "n_pixels": 31770838,
+ "n_frames": 268
+ },
+ "floor": {
+ "mean_srgb": [
+ 227.4,
+ 231.1,
+ 229.1
+ ],
+ "median_srgb": [
+ 233.0,
+ 237.0,
+ 238.0
+ ],
+ "mean_linear": [
+ 0.7714,
+ 0.7995,
+ 0.7845
+ ],
+ "n_pixels": 7946048,
+ "n_frames": 268
+ },
+ "arm_white": {
+ "mean_srgb": [
+ 224.1,
+ 221.7,
+ 211.2
+ ],
+ "median_srgb": [
+ 232.0,
+ 228.0,
+ 217.0
+ ],
+ "mean_linear": [
+ 0.7459,
+ 0.7281,
+ 0.6527
+ ],
+ "n_pixels": 3867581,
+ "n_frames": 267
+ },
+ "servo_black": {
+ "mean_srgb": [
+ 33.8,
+ 35.2,
+ 29.0
+ ],
+ "median_srgb": [
+ 34.0,
+ 34.0,
+ 28.0
+ ],
+ "mean_linear": [
+ 0.0158,
+ 0.017,
+ 0.0123
+ ],
+ "n_pixels": 1524759,
+ "n_frames": 268
+ }
+ },
+ "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"
+ },
+ "tent_edges_on_table": {
+ "back_left_vertical": {
+ "mean_xy": [
+ -2.234706001456275,
+ 6.98376444778672
+ ],
+ "direction_deg": 109.08381857975152,
+ "end_a": [
+ -0.021687390447613808,
+ 0.5871060353188051
+ ],
+ "end_b": [
+ -48.69972327331576,
+ 141.28938760837914
+ ],
+ "note": "vertical edge: the table-plane intersection is not meaningful"
+ },
+ "back_floor": {
+ "mean_xy": [
+ 0.30721218712751286,
+ 0.4567102786016847
+ ],
+ "direction_deg": -3.7004140781073005,
+ "end_a": [
+ 0.0084632714954897,
+ 0.4760316724527963
+ ],
+ "end_b": [
+ 0.5825967452130373,
+ 0.4388999595381722
+ ],
+ "note": "on the table plane"
+ },
+ "back_right_vertical": {
+ "mean_xy": [
+ 0.9756942034541046,
+ 1.4019532616387078
+ ],
+ "direction_deg": 69.71156536833297,
+ "end_a": [
+ 0.6557709144107051,
+ 0.5365514200079403
+ ],
+ "end_b": [
+ 1.7179692999327356,
+ 3.40982907902605
+ ],
+ "note": "vertical edge: the table-plane intersection is not meaningful"
+ },
+ "right_floor": {
+ "mean_xy": [
+ 0.5876447776861765,
+ -0.10260227903720404
+ ],
+ "direction_deg": 86.70338202892243,
+ "end_a": [
+ 0.569074900570323,
+ -0.4249936638565325
+ ],
+ "end_b": [
+ 0.6147059702089496,
+ 0.36720671742788813
+ ],
+ "note": "on the table plane"
+ },
+ "table_edge_left": {
+ "mean_xy": [
+ -0.04226150334414614,
+ -0.21611951812681693
+ ],
+ "direction_deg": 83.6005831319696,
+ "end_a": [
+ -0.061883061925573496,
+ -0.39106572733405925
+ ],
+ "end_b": [
+ -0.030536527553528495,
+ -0.11157939920084983
+ ],
+ "note": "on the table plane"
+ },
+ "front_floor": {
+ "mean_xy": [
+ 0.27012521237733517,
+ -0.45649238436423
+ ],
+ "direction_deg": -3.716054733062346,
+ "end_a": [
+ -0.005963368187689111,
+ -0.43856084960281133
+ ],
+ "end_b": [
+ 0.539232197708343,
+ -0.4739704750991963
+ ],
+ "note": "on the table plane"
+ },
+ "mat_top": {
+ "mean_xy": [
+ 0.2861046520066711,
+ 0.23055037181577712
+ ],
+ "direction_deg": -2.737206262162437,
+ "end_a": [
+ 0.16402190284641244,
+ 0.23638710396283494
+ ],
+ "end_b": [
+ 0.4075864354175589,
+ 0.2247423716241574
+ ],
+ "note": "on the table plane"
+ },
+ "mat_right": {
+ "mean_xy": [
+ 0.42148444966605875,
+ -0.046558767729531846
+ ],
+ "direction_deg": 86.45692253859843,
+ "end_a": [
+ 0.41113510721034996,
+ -0.21370656978292524
+ ],
+ "end_b": [
+ 0.43455407082900666,
+ 0.16452309185781186
+ ],
+ "note": "on the table plane"
+ },
+ "mat_bottom": {
+ "mean_xy": [
+ 0.2552528264025261,
+ -0.23683183930144378
+ ],
+ "direction_deg": -3.8099873219972737,
+ "end_a": [
+ 0.1257419110986377,
+ -0.22820705868060664
+ ],
+ "end_b": [
+ 0.3814098086244724,
+ -0.24523326471719378
+ ],
+ "note": "on the table plane"
+ },
+ "mat_left": {
+ "mean_xy": [
+ 0.11482926580671213,
+ -0.026502364341103993
+ ],
+ "direction_deg": 85.91625620665677,
+ "end_a": [
+ 0.10287798261399214,
+ -0.193897329196473
+ ],
+ "end_b": [
+ 0.12966845983645967,
+ 0.1813419585684814
+ ],
+ "note": "on the table plane"
+ }
+ },
+ "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."
+ },
+ "real_start_pose": {
+ "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)"
+ },
+ "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.",
+ "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.",
+ "uncertainties": [
+ "pan offset unobservable (gauge), held 0; tent edges suggest ~+3.5 deg, homing pose -6.9 deg",
+ "table tilt (2.1 deg) and shoulder_lift offset partly interchangeable; flat-table alternative 14 % worse (joint_map.alternatives.flat_table)",
+ "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",
+ "real wrist camera 4.7 cm further back / 1.7 cm further out than the MJCF wrist_cam, optical axis 10 deg different",
+ "MJCF jaw geometry: hold width differs ~2.3 deg (alternatives.gripper_lin_hold_width)",
+ "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",
+ "external holdout samples small (6 static, 8 carry, 12 plate corners); wrist intrinsics beyond ~70 deg off-axis extrapolated",
+ "both cameras auto-expose: colours drift with the view"
+ ],
+ "overlays": [
+ "overlay_external_0.png",
+ "overlay_external_1.png",
+ "overlay_external_zoom_0.png",
+ "overlay_external_zoom_1.png",
+ "overlay_wrist_0.png",
+ "overlay_wrist_1.png",
+ "evidence_roll_offset_external.png"
+ ]
+}
\ No newline at end of file
diff --git a/so101_pick_place/code/configs/so101_pick_place/dyn_fit_d2q.json b/so101_pick_place/code/configs/so101_pick_place/dyn_fit_d2q.json
new file mode 100644
index 0000000000000000000000000000000000000000..cd6f4c1fcf5f2cf50b2cbc3dd078d1f14dd179e7
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_pick_place/dyn_fit_d2q.json
@@ -0,0 +1,77 @@
+{
+ "d": 2,
+ "jitter": 0.4,
+ "i_time_s": 0.2,
+ "i_max_deg": 3.0,
+ "i_e_max_deg": 1.0,
+ "i_v_min": 0.02,
+ "servo": {
+ "delay_ms": [
+ 25,
+ 25,
+ 20,
+ 25,
+ 20,
+ 45
+ ],
+ "tau_ms": [
+ 50,
+ 50,
+ 45,
+ 40,
+ 40,
+ 45
+ ],
+ "deadband_deg": [
+ 0.35,
+ 0.3,
+ 0.74,
+ 0.37,
+ 0.44,
+ 0.37
+ ],
+ "deadband_per_Nm_deg": [
+ 0.0,
+ 1.7,
+ 1.3,
+ 0.8,
+ 0.0,
+ 0.0
+ ],
+ "breakaway_extra_deg": [
+ 0.14,
+ 0.0,
+ 0.02,
+ 0.09,
+ 0.09,
+ 0.29
+ ],
+ "compliance_rad_per_Nm": [
+ 0.0,
+ 0.06,
+ 0.055,
+ 0.055,
+ 0.0,
+ 0.0
+ ],
+ "bias_deg": [
+ -0.07,
+ -0.22,
+ 0.18,
+ 0.0,
+ -0.07,
+ 0.03
+ ],
+ "vmax_rad_s": [
+ 3.0,
+ 2.3,
+ 3.0,
+ 3.0,
+ 1.0,
+ 2.2
+ ],
+ "cube_mass_kg": 0.03
+ },
+ "note": "fitted servo evaluation setting (servo_fit_params.json proposed) + robot loop delay d 2 jitter 0.4 + guard integral",
+ "delay_mode": "queue"
+}
\ No newline at end of file
diff --git a/so101_pick_place/code/configs/so101_pick_place/nrd/base_c0.json b/so101_pick_place/code/configs/so101_pick_place/nrd/base_c0.json
new file mode 100644
index 0000000000000000000000000000000000000000..daacb0ecacf8f062c0d26ee967e9b2bdb40c5f8a
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_pick_place/nrd/base_c0.json
@@ -0,0 +1,81 @@
+{
+ "seed": 61,
+ "model_step_s": 0.02,
+ "history": 4,
+ "network": {
+ "width": 128,
+ "heads": 4,
+ "ffn": 512,
+ "layers": 4
+ },
+ "integrate_kinds": [
+ "sphere",
+ "rigid",
+ "articulated"
+ ],
+ "check_episodes": 1500,
+ "evaluate_every": 10000,
+ "free_phase_step": 5,
+ "core_bins": 8,
+ "ridge": 1e-06,
+ "near_negative_s": 0.05,
+ "collision": {
+ "lr": 0.001,
+ "updates": 30000,
+ "batch": 2048,
+ "warmup": 1000
+ },
+ "skip_ridge": 0.001,
+ "push_prob": 0.5,
+ "push_start": 0.25,
+ "push_max_steps": 3,
+ "push_max_dev": 0.5,
+ "rollout_scale_factor": 4.0,
+ "cotrain": {
+ "updates": 120000,
+ "lr": 0.001,
+ "warmup": 2000,
+ "core_batch": 4096,
+ "contact_batch": 4096,
+ "traj_every": 8,
+ "traj_batch": 128,
+ "horizon_start_s": 0.1,
+ "horizon_max_s": 1.0,
+ "horizon_ramp": 0.5,
+ "traj_ramp": 0.25
+ },
+ "push_guard": {
+ "unit": "all_hit",
+ "bodies": "affected"
+ },
+ "history_noise": {
+ "floor_step_rms": 0.05,
+ "rate_kick": {
+ "size": 1.0,
+ "mix": [
+ 0.1,
+ 4.0
+ ]
+ }
+ },
+ "loss_scale": {
+ "rule": "step_type"
+ },
+ "contact_huber": 1.0,
+ "contact_sampling": "sqrt_groups",
+ "collision_cotrain": {
+ "weight": 1.0
+ },
+ "aux_geometry": {
+ "fk": "configs/contact_nrd/derived/so101_grasp_fk.json",
+ "body": "cube",
+ "frame": "arm",
+ "pairs": [
+ "fixed_jaw_cube",
+ "moving_jaw_cube"
+ ],
+ "weight": 1.0,
+ "generated": true
+ },
+ "collision_sampling": "sqrt_families"
+}
\ No newline at end of file
diff --git a/so101_pick_place/code/configs/so101_pick_place/nrd/ft_c1_s62.json b/so101_pick_place/code/configs/so101_pick_place/nrd/ft_c1_s62.json
new file mode 100644
index 0000000000000000000000000000000000000000..f188ed7c7f6e50b2aa535f322123c5d8e059ecc6
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_pick_place/nrd/ft_c1_s62.json
@@ -0,0 +1,90 @@
+{
+ "seed": 62,
+ "model_step_s": 0.02,
+ "history": 4,
+ "network": {
+ "width": 128,
+ "heads": 4,
+ "ffn": 512,
+ "layers": 4
+ },
+ "integrate_kinds": [
+ "sphere",
+ "rigid",
+ "articulated"
+ ],
+ "check_episodes": 1500,
+ "evaluate_every": 2500,
+ "free_phase_step": 5,
+ "core_bins": 8,
+ "ridge": 1e-06,
+ "near_negative_s": 0.05,
+ "collision": {
+ "lr": 0.001,
+ "updates": 3000,
+ "batch": 2048,
+ "warmup": 100
+ },
+ "skip_ridge": 0.001,
+ "push_prob": 0.5,
+ "push_start": 0.0,
+ "push_max_steps": 3,
+ "push_max_dev": 0.5,
+ "rollout_scale_factor": 4.0,
+ "cotrain": {
+ "updates": 20000,
+ "lr": 0.0001,
+ "warmup": 500,
+ "core_batch": 4096,
+ "contact_batch": 4096,
+ "traj_every": 8,
+ "traj_batch": 128,
+ "horizon_start_s": 1.0,
+ "horizon_max_s": 1.0,
+ "horizon_ramp": 0.5,
+ "traj_ramp": 0.025
+ },
+ "push_guard": {
+ "unit": "all_hit",
+ "bodies": "affected"
+ },
+ "history_noise": {
+ "floor_step_rms": 0.05,
+ "rate_kick": {
+ "size": 1.0,
+ "mix": [
+ 0.1,
+ 4.0
+ ]
+ }
+ },
+ "loss_scale": {
+ "rule": "step_type"
+ },
+ "contact_huber": 1.0,
+ "contact_sampling": "sqrt_groups",
+ "collision_cotrain": {
+ "weight": 1.0
+ },
+ "aux_geometry": {
+ "fk": "configs/contact_nrd/derived/so101_grasp_fk.json",
+ "body": "cube",
+ "frame": "arm",
+ "pairs": [
+ "fixed_jaw_cube",
+ "moving_jaw_cube"
+ ],
+ "weight": 1.0,
+ "generated": true
+ },
+ "collision_sampling": "sqrt_families",
+ "note": "Converged-state data round c1 of the SO101 policy study (2026-10-12): fine-tune of the sibling study's converged-state grasp NRD (state = joint/cube rates predicted, poses integrated; no derived or relative input channels; training-only geometry heads) full_ns_rk_cc_geo_cs_s62_plus/best.pt on production_plus + noisy_v1 + expert_v2 + policy_v3 x2.5 (the round-3 merge). Recipe = the source run's options; fine-tune schedule as rounds 2-3: 20,000 co-training updates at lr 1e-4, warmup 500, traj_ramp 0.025, horizon 1.0 s, a check every 2,500 updates. best.pt on the merged validation; last.pt = fixed budget.",
+ "init_from": {
+ "run": "artifacts/so101_pick_place/nrd/c0_s62",
+ "checkpoint": "original/best.pt",
+ "collision_updates": 0,
+ "collision_lr": 0.0001,
+ "collision_warmup": 0,
+ "check_first": true
+ }
+}
\ No newline at end of file
diff --git a/so101_pick_place/code/configs/so101_pick_place/parts_override_v2.json b/so101_pick_place/code/configs/so101_pick_place/parts_override_v2.json
new file mode 100644
index 0000000000000000000000000000000000000000..8fb47e3ce96da8d5bd842e15f61389d0414e4eb2
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_pick_place/parts_override_v2.json
@@ -0,0 +1,1667 @@
+[
+ {
+ "name": "camera_bracket_plate",
+ "body": "camera_mount",
+ "group": "board",
+ "polygon": [
+ [
+ 0.013159,
+ 0.029292,
+ -0.007253
+ ],
+ [
+ -0.006522,
+ 0.033162,
+ -0.006874
+ ],
+ [
+ -0.010424,
+ 0.026461,
+ -0.032272
+ ],
+ [
+ 0.012545,
+ 0.021276,
+ -0.034992
+ ]
+ ],
+ "offset": [
+ -0.000541,
+ -0.002832,
+ 0.00083
+ ],
+ "color": [
+ 0.0351,
+ 0.0333,
+ 0.0318
+ ]
+ },
+ {
+ "name": "bracket_ledge",
+ "body": "camera_mount",
+ "group": "printed",
+ "polygon": [
+ [
+ -0.011327,
+ 0.024812,
+ -0.037403
+ ],
+ [
+ 0.003322,
+ 0.021372,
+ -0.039591
+ ],
+ [
+ 0.005342,
+ 0.022598,
+ -0.034092
+ ],
+ [
+ 0.005291,
+ 0.023963,
+ -0.02947
+ ],
+ [
+ -0.008956,
+ 0.027183,
+ -0.027769
+ ]
+ ],
+ "offset": [
+ -5.4e-05,
+ -0.000283,
+ 8.3e-05
+ ],
+ "color": [
+ 0.2834,
+ 0.2723,
+ 0.2586
+ ]
+ },
+ {
+ "name": "plate_screw0_head_lo",
+ "body": "camera_mount",
+ "group": "board",
+ "polygon": [
+ [
+ -0.005842,
+ 0.02694,
+ -0.028015
+ ],
+ [
+ -0.005547,
+ 0.02713,
+ -0.027175
+ ],
+ [
+ -0.00495,
+ 0.027216,
+ -0.026494
+ ],
+ [
+ -0.004144,
+ 0.027185,
+ -0.026073
+ ],
+ [
+ -0.003251,
+ 0.027042,
+ -0.025978
+ ],
+ [
+ -0.002406,
+ 0.026809,
+ -0.026222
+ ],
+ [
+ -0.001738,
+ 0.026521,
+ -0.02677
+ ],
+ [
+ -0.00135,
+ 0.026222,
+ -0.027536
+ ],
+ [
+ -0.001299,
+ 0.025958,
+ -0.028405
+ ]
+ ],
+ "offset": [
+ 0.000108,
+ 0.000566,
+ -0.000166
+ ],
+ "color": [
+ 0.5459,
+ 0.4098,
+ 0.3793
+ ]
+ },
+ {
+ "name": "plate_screw0_head_hi",
+ "body": "camera_mount",
+ "group": "board",
+ "polygon": [
+ [
+ -0.001299,
+ 0.025958,
+ -0.028405
+ ],
+ [
+ -0.001595,
+ 0.025768,
+ -0.029245
+ ],
+ [
+ -0.002191,
+ 0.025682,
+ -0.029927
+ ],
+ [
+ -0.002997,
+ 0.025713,
+ -0.030347
+ ],
+ [
+ -0.003891,
+ 0.025856,
+ -0.030443
+ ],
+ [
+ -0.004736,
+ 0.026089,
+ -0.030198
+ ],
+ [
+ -0.005403,
+ 0.026377,
+ -0.029651
+ ],
+ [
+ -0.005792,
+ 0.026676,
+ -0.028884
+ ],
+ [
+ -0.005842,
+ 0.02694,
+ -0.028015
+ ]
+ ],
+ "offset": [
+ 0.000108,
+ 0.000566,
+ -0.000166
+ ],
+ "color": [
+ 0.1267,
+ 0.0951,
+ 0.088
+ ]
+ },
+ {
+ "name": "plate_screw0_recess",
+ "body": "camera_mount",
+ "group": "board",
+ "polygon": [
+ [
+ -0.003453,
+ 0.027358,
+ -0.027383
+ ],
+ [
+ -0.00397,
+ 0.027409,
+ -0.027544
+ ],
+ [
+ -0.004347,
+ 0.027368,
+ -0.027933
+ ],
+ [
+ -0.004486,
+ 0.027244,
+ -0.028443
+ ],
+ [
+ -0.004347,
+ 0.027072,
+ -0.02894
+ ],
+ [
+ -0.00397,
+ 0.026898,
+ -0.029289
+ ],
+ [
+ -0.003453,
+ 0.026767,
+ -0.029397
+ ],
+ [
+ -0.002937,
+ 0.026716,
+ -0.029235
+ ],
+ [
+ -0.00256,
+ 0.026758,
+ -0.028847
+ ],
+ [
+ -0.002421,
+ 0.026881,
+ -0.028337
+ ],
+ [
+ -0.00256,
+ 0.027053,
+ -0.02784
+ ],
+ [
+ -0.002937,
+ 0.027228,
+ -0.027491
+ ]
+ ],
+ "offset": [
+ 1.8e-05,
+ 9.4e-05,
+ -2.8e-05
+ ],
+ "color": [
+ 0.0915,
+ 0.0915,
+ 0.0915
+ ]
+ },
+ {
+ "name": "plate_screw1_head_lo",
+ "body": "camera_mount",
+ "group": "board",
+ "polygon": [
+ [
+ 0.002901,
+ 0.025022,
+ -0.028861
+ ],
+ [
+ 0.003073,
+ 0.025251,
+ -0.027969
+ ],
+ [
+ 0.003578,
+ 0.025382,
+ -0.027193
+ ],
+ [
+ 0.004339,
+ 0.025396,
+ -0.026648
+ ],
+ [
+ 0.005241,
+ 0.025291,
+ -0.026419
+ ],
+ [
+ 0.006145,
+ 0.025083,
+ -0.02654
+ ],
+ [
+ 0.006914,
+ 0.024803,
+ -0.026993
+ ],
+ [
+ 0.007432,
+ 0.024494,
+ -0.027709
+ ],
+ [
+ 0.007619,
+ 0.024204,
+ -0.028579
+ ]
+ ],
+ "offset": [
+ 0.000108,
+ 0.000566,
+ -0.000166
+ ],
+ "color": [
+ 0.5459,
+ 0.4098,
+ 0.3793
+ ]
+ },
+ {
+ "name": "plate_screw1_head_hi",
+ "body": "camera_mount",
+ "group": "board",
+ "polygon": [
+ [
+ 0.007619,
+ 0.024204,
+ -0.028579
+ ],
+ [
+ 0.007447,
+ 0.023975,
+ -0.02947
+ ],
+ [
+ 0.006942,
+ 0.023844,
+ -0.030247
+ ],
+ [
+ 0.006181,
+ 0.02383,
+ -0.030791
+ ],
+ [
+ 0.00528,
+ 0.023935,
+ -0.03102
+ ],
+ [
+ 0.004376,
+ 0.024143,
+ -0.030899
+ ],
+ [
+ 0.003606,
+ 0.024423,
+ -0.030446
+ ],
+ [
+ 0.003089,
+ 0.024731,
+ -0.02973
+ ],
+ [
+ 0.002901,
+ 0.025022,
+ -0.028861
+ ]
+ ],
+ "offset": [
+ 0.000108,
+ 0.000566,
+ -0.000166
+ ],
+ "color": [
+ 0.1267,
+ 0.0951,
+ 0.088
+ ]
+ },
+ {
+ "name": "plate_screw1_recess",
+ "body": "camera_mount",
+ "group": "board",
+ "polygon": [
+ [
+ 0.005378,
+ 0.02553,
+ -0.027864
+ ],
+ [
+ 0.004847,
+ 0.025583,
+ -0.02803
+ ],
+ [
+ 0.004458,
+ 0.02554,
+ -0.028429
+ ],
+ [
+ 0.004316,
+ 0.025413,
+ -0.028954
+ ],
+ [
+ 0.004458,
+ 0.025236,
+ -0.029465
+ ],
+ [
+ 0.004847,
+ 0.025057,
+ -0.029824
+ ],
+ [
+ 0.005378,
+ 0.024923,
+ -0.029935
+ ],
+ [
+ 0.005908,
+ 0.02487,
+ -0.029769
+ ],
+ [
+ 0.006297,
+ 0.024913,
+ -0.02937
+ ],
+ [
+ 0.006439,
+ 0.02504,
+ -0.028845
+ ],
+ [
+ 0.006297,
+ 0.025217,
+ -0.028334
+ ],
+ [
+ 0.005908,
+ 0.025396,
+ -0.027975
+ ]
+ ],
+ "offset": [
+ 1.8e-05,
+ 9.4e-05,
+ -2.8e-05
+ ],
+ "color": [
+ 0.0915,
+ 0.0915,
+ 0.0915
+ ]
+ },
+ {
+ "name": "jaw_face",
+ "body": "moving_jaw_so101_v1",
+ "group": "printed",
+ "polygon": [
+ [
+ 0.005621,
+ -0.015293,
+ -0.005075
+ ],
+ [
+ 0.008601,
+ -0.004752,
+ -0.005329
+ ],
+ [
+ 0.009052,
+ -0.00086,
+ -0.005422
+ ],
+ [
+ 0.007741,
+ 0.004273,
+ -0.005542
+ ],
+ [
+ 0.005927,
+ 0.006911,
+ -0.005603
+ ],
+ [
+ -0.003481,
+ 0.005917,
+ -0.00557
+ ],
+ [
+ -0.004889,
+ 0.004254,
+ -0.005529
+ ],
+ [
+ -0.008993,
+ -0.003032,
+ -0.005351
+ ],
+ [
+ -0.009368,
+ -0.012449,
+ -0.005127
+ ],
+ [
+ -0.008874,
+ -0.015844,
+ -0.005047
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -5e-06,
+ -0.0002
+ ],
+ "color": [
+ 0.3914,
+ 0.3812,
+ 0.3731
+ ]
+ },
+ {
+ "name": "jaw_screw0_rim",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ -0.003848,
+ -0.010599,
+ -0.005377
+ ],
+ [
+ -0.004753,
+ -0.010419,
+ -0.00538
+ ],
+ [
+ -0.00552,
+ -0.009907,
+ -0.005392
+ ],
+ [
+ -0.006033,
+ -0.00914,
+ -0.005409
+ ],
+ [
+ -0.006213,
+ -0.008235,
+ -0.005431
+ ],
+ [
+ -0.006033,
+ -0.00733,
+ -0.005452
+ ],
+ [
+ -0.00552,
+ -0.006563,
+ -0.005471
+ ],
+ [
+ -0.004753,
+ -0.00605,
+ -0.005484
+ ],
+ [
+ -0.003848,
+ -0.00587,
+ -0.005489
+ ],
+ [
+ -0.002943,
+ -0.00605,
+ -0.005486
+ ],
+ [
+ -0.002175,
+ -0.006563,
+ -0.005475
+ ],
+ [
+ -0.001663,
+ -0.00733,
+ -0.005457
+ ],
+ [
+ -0.001482,
+ -0.008235,
+ -0.005435
+ ],
+ [
+ -0.001663,
+ -0.00914,
+ -0.005414
+ ],
+ [
+ -0.002175,
+ -0.009907,
+ -0.005395
+ ],
+ [
+ -0.002943,
+ -0.010419,
+ -0.005382
+ ]
+ ],
+ "offset": [
+ -1e-06,
+ -1.4e-05,
+ -0.0006
+ ],
+ "color": [
+ 0.3224,
+ 0.2602,
+ 0.2444
+ ]
+ },
+ {
+ "name": "jaw_screw0_head",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ -0.003848,
+ -0.009669,
+ -0.006049
+ ],
+ [
+ -0.004558,
+ -0.009479,
+ -0.006053
+ ],
+ [
+ -0.005077,
+ -0.00896,
+ -0.006065
+ ],
+ [
+ -0.005267,
+ -0.00825,
+ -0.006081
+ ],
+ [
+ -0.005077,
+ -0.007541,
+ -0.006098
+ ],
+ [
+ -0.004558,
+ -0.007022,
+ -0.006111
+ ],
+ [
+ -0.003848,
+ -0.006832,
+ -0.006117
+ ],
+ [
+ -0.003139,
+ -0.007022,
+ -0.006113
+ ],
+ [
+ -0.002619,
+ -0.007541,
+ -0.006101
+ ],
+ [
+ -0.002429,
+ -0.00825,
+ -0.006084
+ ],
+ [
+ -0.002619,
+ -0.00896,
+ -0.006067
+ ],
+ [
+ -0.003139,
+ -0.009479,
+ -0.006054
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -5e-06,
+ -0.0002
+ ],
+ "color": [
+ 0.1218,
+ 0.0983,
+ 0.0923
+ ]
+ },
+ {
+ "name": "jaw_screw0_recess",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ -0.003849,
+ -0.008847,
+ -0.006319
+ ],
+ [
+ -0.004267,
+ -0.008674,
+ -0.006322
+ ],
+ [
+ -0.00444,
+ -0.008256,
+ -0.006332
+ ],
+ [
+ -0.004267,
+ -0.007838,
+ -0.006342
+ ],
+ [
+ -0.003849,
+ -0.007665,
+ -0.006347
+ ],
+ [
+ -0.00343,
+ -0.007838,
+ -0.006343
+ ],
+ [
+ -0.003257,
+ -0.008256,
+ -0.006333
+ ],
+ [
+ -0.00343,
+ -0.008674,
+ -0.006323
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -2e-06,
+ -0.0001
+ ],
+ "color": [
+ 0.0915,
+ 0.0915,
+ 0.0915
+ ]
+ },
+ {
+ "name": "jaw_screw1_rim",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ 0.00538,
+ -0.009933,
+ -0.005402
+ ],
+ [
+ 0.004475,
+ -0.009753,
+ -0.005406
+ ],
+ [
+ 0.003708,
+ -0.00924,
+ -0.005417
+ ],
+ [
+ 0.003195,
+ -0.008473,
+ -0.005435
+ ],
+ [
+ 0.003015,
+ -0.007568,
+ -0.005456
+ ],
+ [
+ 0.003195,
+ -0.006663,
+ -0.005478
+ ],
+ [
+ 0.003708,
+ -0.005896,
+ -0.005496
+ ],
+ [
+ 0.004475,
+ -0.005384,
+ -0.005509
+ ],
+ [
+ 0.00538,
+ -0.005204,
+ -0.005515
+ ],
+ [
+ 0.006286,
+ -0.005384,
+ -0.005511
+ ],
+ [
+ 0.007053,
+ -0.005896,
+ -0.0055
+ ],
+ [
+ 0.007566,
+ -0.006664,
+ -0.005482
+ ],
+ [
+ 0.007746,
+ -0.007568,
+ -0.005461
+ ],
+ [
+ 0.007566,
+ -0.008473,
+ -0.005439
+ ],
+ [
+ 0.007053,
+ -0.00924,
+ -0.00542
+ ],
+ [
+ 0.006286,
+ -0.009753,
+ -0.005407
+ ]
+ ],
+ "offset": [
+ -1e-06,
+ -1.4e-05,
+ -0.0006
+ ],
+ "color": [
+ 0.3224,
+ 0.2602,
+ 0.2444
+ ]
+ },
+ {
+ "name": "jaw_screw1_head",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ 0.00538,
+ -0.009002,
+ -0.006075
+ ],
+ [
+ 0.00467,
+ -0.008812,
+ -0.006078
+ ],
+ [
+ 0.004151,
+ -0.008293,
+ -0.00609
+ ],
+ [
+ 0.003961,
+ -0.007584,
+ -0.006107
+ ],
+ [
+ 0.004151,
+ -0.006874,
+ -0.006124
+ ],
+ [
+ 0.00467,
+ -0.006355,
+ -0.006137
+ ],
+ [
+ 0.00538,
+ -0.006165,
+ -0.006142
+ ],
+ [
+ 0.006089,
+ -0.006355,
+ -0.006138
+ ],
+ [
+ 0.006609,
+ -0.006874,
+ -0.006126
+ ],
+ [
+ 0.006799,
+ -0.007584,
+ -0.00611
+ ],
+ [
+ 0.006609,
+ -0.008293,
+ -0.006093
+ ],
+ [
+ 0.006089,
+ -0.008812,
+ -0.00608
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -5e-06,
+ -0.0002
+ ],
+ "color": [
+ 0.1218,
+ 0.0983,
+ 0.0923
+ ]
+ },
+ {
+ "name": "jaw_screw1_recess",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ 0.00538,
+ -0.008181,
+ -0.006344
+ ],
+ [
+ 0.004961,
+ -0.008008,
+ -0.006348
+ ],
+ [
+ 0.004788,
+ -0.00759,
+ -0.006358
+ ],
+ [
+ 0.004961,
+ -0.007172,
+ -0.006368
+ ],
+ [
+ 0.00538,
+ -0.006999,
+ -0.006372
+ ],
+ [
+ 0.005798,
+ -0.007172,
+ -0.006369
+ ],
+ [
+ 0.005971,
+ -0.00759,
+ -0.006359
+ ],
+ [
+ 0.005798,
+ -0.008008,
+ -0.006349
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -2e-06,
+ -0.0001
+ ],
+ "color": [
+ 0.0915,
+ 0.0915,
+ 0.0915
+ ]
+ },
+ {
+ "name": "jaw_screw2_rim",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ -0.003348,
+ -0.000881,
+ -0.005608
+ ],
+ [
+ -0.004253,
+ -0.000701,
+ -0.005612
+ ],
+ [
+ -0.00502,
+ -0.000188,
+ -0.005623
+ ],
+ [
+ -0.005533,
+ 0.000579,
+ -0.005641
+ ],
+ [
+ -0.005713,
+ 0.001484,
+ -0.005662
+ ],
+ [
+ -0.005533,
+ 0.002389,
+ -0.005684
+ ],
+ [
+ -0.00502,
+ 0.003156,
+ -0.005703
+ ],
+ [
+ -0.004253,
+ 0.003668,
+ -0.005716
+ ],
+ [
+ -0.003348,
+ 0.003848,
+ -0.005721
+ ],
+ [
+ -0.002443,
+ 0.003668,
+ -0.005717
+ ],
+ [
+ -0.001676,
+ 0.003156,
+ -0.005706
+ ],
+ [
+ -0.001163,
+ 0.002389,
+ -0.005688
+ ],
+ [
+ -0.000983,
+ 0.001484,
+ -0.005667
+ ],
+ [
+ -0.001163,
+ 0.000579,
+ -0.005645
+ ],
+ [
+ -0.001676,
+ -0.000188,
+ -0.005627
+ ],
+ [
+ -0.002443,
+ -0.000701,
+ -0.005614
+ ]
+ ],
+ "offset": [
+ -1e-06,
+ -1.4e-05,
+ -0.0006
+ ],
+ "color": [
+ 0.3224,
+ 0.2602,
+ 0.2444
+ ]
+ },
+ {
+ "name": "jaw_screw2_head",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ -0.003349,
+ 5e-05,
+ -0.006281
+ ],
+ [
+ -0.004058,
+ 0.00024,
+ -0.006284
+ ],
+ [
+ -0.004578,
+ 0.000759,
+ -0.006296
+ ],
+ [
+ -0.004768,
+ 0.001468,
+ -0.006313
+ ],
+ [
+ -0.004578,
+ 0.002178,
+ -0.00633
+ ],
+ [
+ -0.004058,
+ 0.002697,
+ -0.006343
+ ],
+ [
+ -0.003349,
+ 0.002887,
+ -0.006348
+ ],
+ [
+ -0.002639,
+ 0.002697,
+ -0.006344
+ ],
+ [
+ -0.00212,
+ 0.002178,
+ -0.006333
+ ],
+ [
+ -0.00193,
+ 0.001468,
+ -0.006316
+ ],
+ [
+ -0.00212,
+ 0.000759,
+ -0.006299
+ ],
+ [
+ -0.002639,
+ 0.00024,
+ -0.006286
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -5e-06,
+ -0.0002
+ ],
+ "color": [
+ 0.1218,
+ 0.0983,
+ 0.0923
+ ]
+ },
+ {
+ "name": "jaw_screw2_recess",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ -0.003349,
+ 0.000871,
+ -0.00655
+ ],
+ [
+ -0.003767,
+ 0.001044,
+ -0.006554
+ ],
+ [
+ -0.00394,
+ 0.001462,
+ -0.006564
+ ],
+ [
+ -0.003767,
+ 0.00188,
+ -0.006574
+ ],
+ [
+ -0.003349,
+ 0.002054,
+ -0.006578
+ ],
+ [
+ -0.002931,
+ 0.00188,
+ -0.006575
+ ],
+ [
+ -0.002758,
+ 0.001462,
+ -0.006565
+ ],
+ [
+ -0.002931,
+ 0.001044,
+ -0.006555
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -2e-06,
+ -0.0001
+ ],
+ "color": [
+ 0.0915,
+ 0.0915,
+ 0.0915
+ ]
+ },
+ {
+ "name": "jaw_screw3_rim",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ 0.005854,
+ -0.00057,
+ -0.005625
+ ],
+ [
+ 0.004949,
+ -0.00039,
+ -0.005629
+ ],
+ [
+ 0.004181,
+ 0.000123,
+ -0.00564
+ ],
+ [
+ 0.003669,
+ 0.00089,
+ -0.005658
+ ],
+ [
+ 0.003489,
+ 0.001795,
+ -0.005679
+ ],
+ [
+ 0.003669,
+ 0.0027,
+ -0.005701
+ ],
+ [
+ 0.004181,
+ 0.003467,
+ -0.00572
+ ],
+ [
+ 0.004949,
+ 0.003979,
+ -0.005733
+ ],
+ [
+ 0.005854,
+ 0.004159,
+ -0.005738
+ ],
+ [
+ 0.006759,
+ 0.003979,
+ -0.005734
+ ],
+ [
+ 0.007526,
+ 0.003467,
+ -0.005723
+ ],
+ [
+ 0.008039,
+ 0.0027,
+ -0.005705
+ ],
+ [
+ 0.008219,
+ 0.001795,
+ -0.005684
+ ],
+ [
+ 0.008039,
+ 0.00089,
+ -0.005662
+ ],
+ [
+ 0.007526,
+ 0.000123,
+ -0.005644
+ ],
+ [
+ 0.006759,
+ -0.00039,
+ -0.005631
+ ]
+ ],
+ "offset": [
+ -1e-06,
+ -1.4e-05,
+ -0.0006
+ ],
+ "color": [
+ 0.3224,
+ 0.2602,
+ 0.2444
+ ]
+ },
+ {
+ "name": "jaw_screw3_head",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ 0.005853,
+ 0.000361,
+ -0.006298
+ ],
+ [
+ 0.005144,
+ 0.000551,
+ -0.006301
+ ],
+ [
+ 0.004624,
+ 0.00107,
+ -0.006313
+ ],
+ [
+ 0.004434,
+ 0.001779,
+ -0.00633
+ ],
+ [
+ 0.004624,
+ 0.002489,
+ -0.006347
+ ],
+ [
+ 0.005144,
+ 0.003008,
+ -0.00636
+ ],
+ [
+ 0.005853,
+ 0.003198,
+ -0.006365
+ ],
+ [
+ 0.006563,
+ 0.003008,
+ -0.006361
+ ],
+ [
+ 0.007082,
+ 0.002489,
+ -0.00635
+ ],
+ [
+ 0.007272,
+ 0.001779,
+ -0.006333
+ ],
+ [
+ 0.007082,
+ 0.00107,
+ -0.006316
+ ],
+ [
+ 0.006563,
+ 0.000551,
+ -0.006303
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -5e-06,
+ -0.0002
+ ],
+ "color": [
+ 0.1218,
+ 0.0983,
+ 0.0923
+ ]
+ },
+ {
+ "name": "jaw_screw3_recess",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ 0.005853,
+ 0.001182,
+ -0.006567
+ ],
+ [
+ 0.005435,
+ 0.001355,
+ -0.006571
+ ],
+ [
+ 0.005262,
+ 0.001773,
+ -0.006581
+ ],
+ [
+ 0.005435,
+ 0.002191,
+ -0.006591
+ ],
+ [
+ 0.005853,
+ 0.002365,
+ -0.006595
+ ],
+ [
+ 0.006271,
+ 0.002191,
+ -0.006592
+ ],
+ [
+ 0.006444,
+ 0.001773,
+ -0.006582
+ ],
+ [
+ 0.006271,
+ 0.001355,
+ -0.006572
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -2e-06,
+ -0.0001
+ ],
+ "color": [
+ 0.0915,
+ 0.0915,
+ 0.0915
+ ]
+ },
+ {
+ "name": "jaw_hub",
+ "body": "moving_jaw_so101_v1",
+ "group": "servo",
+ "polygon": [
+ [
+ 0.001013,
+ -0.003026,
+ -0.005562
+ ],
+ [
+ 0.000422,
+ -0.002868,
+ -0.005565
+ ],
+ [
+ -1.1e-05,
+ -0.002435,
+ -0.005575
+ ],
+ [
+ -0.000169,
+ -0.001844,
+ -0.005589
+ ],
+ [
+ -1.1e-05,
+ -0.001253,
+ -0.005603
+ ],
+ [
+ 0.000422,
+ -0.00082,
+ -0.005614
+ ],
+ [
+ 0.001013,
+ -0.000662,
+ -0.005618
+ ],
+ [
+ 0.001605,
+ -0.00082,
+ -0.005615
+ ],
+ [
+ 0.002037,
+ -0.001253,
+ -0.005605
+ ],
+ [
+ 0.002196,
+ -0.001844,
+ -0.005591
+ ],
+ [
+ 0.002037,
+ -0.002435,
+ -0.005577
+ ],
+ [
+ 0.001605,
+ -0.002868,
+ -0.005566
+ ]
+ ],
+ "offset": [
+ -0.0,
+ -2e-06,
+ -0.0001
+ ],
+ "color": [
+ 0.2,
+ 0.2,
+ 0.2
+ ]
+ },
+ {
+ "name": "fixed_jaw_upper",
+ "body": "camera_mount",
+ "group": "printed",
+ "polygon": [
+ [
+ -0.02361,
+ 0.004371,
+ -0.085465
+ ],
+ [
+ -0.011907,
+ 0.01023,
+ -0.077948
+ ],
+ [
+ -0.004197,
+ 0.026704,
+ -0.035982
+ ],
+ [
+ -0.030809,
+ 0.017707,
+ -0.040375
+ ]
+ ],
+ "offset": [
+ -5.2e-05,
+ 0.000183,
+ -6.2e-05
+ ],
+ "color": [
+ 0.361,
+ 0.3367,
+ 0.3077
+ ]
+ },
+ {
+ "name": "fixed_jaw_lower",
+ "body": "camera_mount",
+ "group": "printed",
+ "polygon": [
+ [
+ -0.030809,
+ 0.017707,
+ -0.040375
+ ],
+ [
+ -0.011578,
+ 0.024061,
+ -0.037634
+ ],
+ [
+ -0.006998,
+ 0.032751,
+ -0.015921
+ ],
+ [
+ -0.024394,
+ 0.028871,
+ -0.012921
+ ],
+ [
+ -0.032714,
+ 0.019284,
+ -0.034174
+ ]
+ ],
+ "offset": [
+ -5.2e-05,
+ 0.000183,
+ -6.2e-05
+ ],
+ "color": [
+ 0.3109,
+ 0.2981,
+ 0.2695
+ ]
+ },
+ {
+ "name": "jaw_upper",
+ "body": "moving_jaw_so101_v1",
+ "group": "printed",
+ "polygon": [
+ [
+ -0.006786,
+ -0.052277,
+ 0.010364
+ ],
+ [
+ 0.001207,
+ -0.052485,
+ 0.010668
+ ],
+ [
+ 0.005265,
+ -0.0145,
+ -0.006154
+ ],
+ [
+ -0.008904,
+ -0.014856,
+ -0.006371
+ ]
+ ],
+ "offset": [
+ 5e-06,
+ -8.1e-05,
+ -0.000183
+ ],
+ "color": [
+ 0.4154,
+ 0.3873,
+ 0.3587
+ ]
+ }
+]
\ No newline at end of file
diff --git a/so101_pick_place/code/configs/so101_pick_place/real_scene_v2.json b/so101_pick_place/code/configs/so101_pick_place/real_scene_v2.json
new file mode 100644
index 0000000000000000000000000000000000000000..875d850d719f7e0c3c4e29f6a0470bc84a5f42d7
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_pick_place/real_scene_v2.json
@@ -0,0 +1,627 @@
+{
+ "version": "real_scene_v2",
+ "calib": "/home/harry/so101_r2s_claude/calib/calib_v1.json",
+ "student_view": {
+ "external": {
+ "crop": [
+ 52,
+ 103,
+ 288,
+ 288
+ ],
+ "out": [
+ 224,
+ 224
+ ],
+ "interp": "area"
+ },
+ "wrist": {
+ "crop": [
+ 0,
+ 0,
+ 640,
+ 480
+ ],
+ "out": [
+ 224,
+ 224
+ ],
+ "interp": "area"
+ }
+ },
+ "geometry": {
+ "floor_xy": [
+ -0.045,
+ 0.59,
+ -0.456,
+ 0.457
+ ],
+ "walls": [
+ [
+ [
+ -0.045,
+ 0.457
+ ],
+ [
+ 0.59,
+ 0.457
+ ],
+ 0.53
+ ],
+ [
+ [
+ 0.59,
+ 0.457
+ ],
+ [
+ 0.59,
+ -0.456
+ ],
+ 0.38
+ ]
+ ],
+ "wall_thickness": 0.005,
+ "strip": {
+ "from": [
+ 0.585,
+ -0.42,
+ 0.33
+ ],
+ "to": [
+ 0.585,
+ 0.42,
+ 0.43
+ ],
+ "size": [
+ 0.03,
+ 0.01
+ ]
+ },
+ "room": {
+ "center": [
+ 0.3,
+ 0.0,
+ 0.6
+ ],
+ "half": [
+ 2.5,
+ 2.5,
+ 1.8
+ ],
+ "floor_z": -0.75
+ },
+ "ceiling": null,
+ "table_plane": null,
+ "mat_thickness": 0.001,
+ "plate_thickness": 0.001,
+ "parts": [
+ {
+ "name": "camera_bracket_plate",
+ "body": "camera_mount",
+ "group": "board",
+ "polygon": [
+ [
+ 0.013618,
+ 0.025993,
+ -0.007363
+ ],
+ [
+ -0.007618,
+ 0.030169,
+ -0.006955
+ ],
+ [
+ -0.011829,
+ 0.022939,
+ -0.03436
+ ],
+ [
+ 0.012955,
+ 0.017344,
+ -0.037294
+ ]
+ ],
+ "offset": [
+ 0.000541,
+ 0.002832,
+ -0.00083
+ ]
+ }
+ ]
+ },
+ "colors": {
+ "printed": [
+ 0.713,
+ 0.6798,
+ 0.6153
+ ],
+ "servo": [
+ 0.1196,
+ 0.1331,
+ 0.1162
+ ],
+ "cube": [
+ 0.06,
+ 0.361,
+ 0.1295
+ ],
+ "plate": [
+ 0.6544,
+ 0.0844,
+ 0.0855
+ ],
+ "floor": [
+ 0.85,
+ 0.85,
+ 0.85
+ ],
+ "mat": [
+ 0.0796,
+ 0.0837,
+ 0.0814
+ ],
+ "walls": [
+ 0.6021,
+ 0.5967,
+ 0.5836
+ ],
+ "board": [
+ 0.1038,
+ 0.0912,
+ 0.0908
+ ],
+ "room": [
+ 0.1637,
+ 0.1546,
+ 0.0971
+ ],
+ "room_floor": [
+ 0.1356,
+ 0.131,
+ 0.0932
+ ],
+ "strip": [
+ 0.2689,
+ 0.2689,
+ 0.2689
+ ]
+ },
+ "light": {
+ "lights": [
+ {
+ "type": "point",
+ "position": [
+ 0.55,
+ 0.0,
+ 0.39
+ ],
+ "shadow": false
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 0.0,
+ 0.0,
+ -1.0
+ ],
+ "shadow": false,
+ "intensity": 0.2331,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ -1.0,
+ 0.0,
+ -0.35
+ ],
+ "shadow": false,
+ "intensity": 0.2322,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 1.0,
+ 0.0,
+ -0.35
+ ],
+ "shadow": false,
+ "intensity": 0.152,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 0.0,
+ -1.0,
+ -0.35
+ ],
+ "shadow": false,
+ "intensity": 0.6659,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 0.0,
+ 1.0,
+ -0.35
+ ],
+ "shadow": false,
+ "intensity": 0.4755,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 0.0,
+ 0.0,
+ 1.0
+ ],
+ "shadow": false,
+ "intensity": 0.6029,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ -1.0,
+ -1.0,
+ -1.0
+ ],
+ "shadow": false,
+ "intensity": 0.2813,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ -1.0,
+ 1.0,
+ -1.0
+ ],
+ "shadow": false,
+ "intensity": 0.2956,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 1.0,
+ -1.0,
+ -1.0
+ ],
+ "shadow": false,
+ "intensity": 0.2438,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 1.0,
+ 1.0,
+ -1.0
+ ],
+ "shadow": false,
+ "intensity": 0.2614,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ -1.0,
+ -1.0,
+ 1.0
+ ],
+ "shadow": false,
+ "intensity": 0.9642,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ -1.0,
+ 1.0,
+ 1.0
+ ],
+ "shadow": false,
+ "intensity": 0.5733,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 1.0,
+ -1.0,
+ 1.0
+ ],
+ "shadow": false
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 1.0,
+ -1.0,
+ 1.0
+ ],
+ "shadow": false
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 1.0,
+ -1.0,
+ 1.0
+ ],
+ "shadow": false,
+ "intensity": 0.2441,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ },
+ {
+ "type": "directional",
+ "direction": [
+ 1.0,
+ 1.0,
+ 1.0
+ ],
+ "shadow": false,
+ "intensity": 0.5668,
+ "center": [
+ 0.25,
+ 0.0,
+ 0.0
+ ]
+ }
+ ],
+ "ambient": true,
+ "shadows": false,
+ "sky": [
+ 20,
+ 20,
+ 20
+ ]
+ },
+ "tone": {
+ "external": {
+ "exposure": 0.39731,
+ "wb": [
+ 0.90161,
+ 1.0,
+ 0.92806
+ ],
+ "black": [
+ -0.02908,
+ -0.04135,
+ -0.04141
+ ],
+ "gamma": 1.35405,
+ "vignette": 2.1107
+ },
+ "wrist": {
+ "exposure": 0.48968,
+ "wb": [
+ 0.98961,
+ 1.0,
+ 0.96236
+ ],
+ "black": [
+ -0.04404,
+ -0.0359,
+ -0.04162
+ ],
+ "gamma": 1.05565,
+ "vignette": 0.18174
+ }
+ },
+ "fit": {
+ "source": "/home/harry/so101_r2s_claude/scene/out/fit_B5.json",
+ "config": "B",
+ "rms_nominal_fit": 26.994945526123047,
+ "rms_nominal_heldout": 27.508882522583008,
+ "frame_exposure_log_std": [
+ 0.03232957050204277,
+ 0.0951780155301094
+ ]
+ },
+ "dr": {
+ "bright": {
+ "printed": [
+ 0.85,
+ 1.15
+ ],
+ "servo": [
+ 0.7,
+ 1.5
+ ],
+ "cube": [
+ 0.8,
+ 1.2
+ ],
+ "plate": [
+ 0.8,
+ 1.2
+ ],
+ "floor": [
+ 0.9,
+ 1.08
+ ],
+ "mat": [
+ 0.7,
+ 1.5
+ ],
+ "walls": [
+ 0.8,
+ 1.12
+ ],
+ "board": [
+ 0.7,
+ 1.5
+ ],
+ "room": [
+ 0.2,
+ 2.5
+ ],
+ "room_floor": [
+ 0.2,
+ 2.5
+ ],
+ "strip": [
+ 1.0,
+ 1.0
+ ]
+ },
+ "tint": {
+ "printed": 0.04,
+ "servo": 0.08,
+ "cube": 0.08,
+ "plate": 0.08,
+ "floor": 0.03,
+ "mat": 0.1,
+ "walls": 0.04,
+ "board": 0.08,
+ "room": 0.45,
+ "room_floor": 0.45,
+ "strip": 0.0
+ },
+ "cam_pos": {
+ "external": 0.008,
+ "wrist": 0.003
+ },
+ "cam_rot": {
+ "external": 0.026,
+ "wrist": 0.035
+ },
+ "mat_xy": 0.01,
+ "mat_yaw": 0.052,
+ "wall_xy": 0.02,
+ "light_deg": 15.0,
+ "light_pos": 0.05,
+ "exposure": {
+ "external": [
+ 0.8,
+ 1.35
+ ],
+ "wrist": [
+ 0.7,
+ 1.7
+ ]
+ },
+ "wb": {
+ "external": 0.06,
+ "wrist": 0.06
+ },
+ "black": [
+ -0.01,
+ 0.01
+ ],
+ "gamma": [
+ 0.85,
+ 1.25
+ ],
+ "vignette": {
+ "external": [
+ -0.8,
+ 0.8
+ ],
+ "wrist": [
+ -0.2,
+ 0.8
+ ]
+ },
+ "focal": 0.03,
+ "pp_px": 3.0,
+ "focal_levels": 7
+ },
+ "image_fx": {
+ "nominal_blur_px": 0.55,
+ "nominal_chroma_px": {
+ "external": 2.0,
+ "wrist": 0.0
+ },
+ "p_noise": 0.8,
+ "noise": [
+ 0.002,
+ 0.012
+ ],
+ "p_blur": 0.3,
+ "blur_px": [
+ 0.2,
+ 0.8
+ ],
+ "p_motion": 0.2,
+ "motion_px": [
+ 1.0,
+ 3.0
+ ],
+ "p_jpeg": 0.8,
+ "jpeg_quality": [
+ 50,
+ 95
+ ]
+ },
+ "render": {
+ "supersample": 1
+ },
+ "notes": [
+ {
+ "doc": "/home/harry/so101_r2s_claude/docs/scene_match.md",
+ "geometry": "training geometry: table / mat top at z = 0 (sim physics), plate 1 mm. The paired real-state check used the measured table plane (geometry.table_plane = 'calib') and the plate thickness of calib_v1 (3.9 mm).",
+ "load": "RealScene.from_path(this file); RealDR.from_scene(real); camera_fx.ImageFX.from_dict(real.image_fx) (random effects only: the renderer applies the nominal blur / chroma itself)",
+ "student_view": "the real-robot code must use this student_view (hw_lib.view_specs reads the dict it is given)"
+ },
+ "v2 (2026-10-22, main session, after ~/so101_r2s_claude/scene/REVIEW.md sec. 3): v1 + room / room_floor nominal colour darker and more yellow (x 0.8, 0.75, 0.55 per channel; review: real room darker and more yellow than 81 % of the draws), room brightness 0.2-2.5 and tint +-0.45, wider tone-map exposure (external 0.8-1.35, wrist 0.7-1.7: clipped highlights, real wrist frames have 9.4 % pixels >= 245) and gamma 0.85-1.25 (real contrast at rank 0.81 / 0.93 of the v1 draws). Geometry, lights, nominal tone map and image_fx unchanged."
+ ]
+}
\ No newline at end of file
diff --git a/so101_pick_place/code/configs/so101_pick_place/so101_follower_lerobot_calib.json b/so101_pick_place/code/configs/so101_pick_place/so101_follower_lerobot_calib.json
new file mode 100644
index 0000000000000000000000000000000000000000..ea2d771bcb6f25c2a288602c107721e150b123e3
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_pick_place/so101_follower_lerobot_calib.json
@@ -0,0 +1,44 @@
+{
+ "shoulder_pan": {
+ "id": 1,
+ "drive_mode": 0,
+ "homing_offset": 1252,
+ "range_min": 999,
+ "range_max": 2937
+ },
+ "shoulder_lift": {
+ "id": 2,
+ "drive_mode": 0,
+ "homing_offset": -1476,
+ "range_min": 811,
+ "range_max": 3194
+ },
+ "elbow_flex": {
+ "id": 3,
+ "drive_mode": 0,
+ "homing_offset": 1483,
+ "range_min": 840,
+ "range_max": 3030
+ },
+ "wrist_flex": {
+ "id": 4,
+ "drive_mode": 0,
+ "homing_offset": -673,
+ "range_min": 914,
+ "range_max": 3263
+ },
+ "wrist_roll": {
+ "id": 5,
+ "drive_mode": 0,
+ "homing_offset": -182,
+ "range_min": 0,
+ "range_max": 4095
+ },
+ "gripper": {
+ "id": 6,
+ "drive_mode": 0,
+ "homing_offset": 758,
+ "range_min": 2033,
+ "range_max": 3551
+ }
+}
\ No newline at end of file
diff --git a/so101_pick_place/code/configs/so101_pick_place/teacher/env_jt_b140.json b/so101_pick_place/code/configs/so101_pick_place/teacher/env_jt_b140.json
new file mode 100644
index 0000000000000000000000000000000000000000..51a0139bc4793b4a8c5666ba6f78228880c1a26b
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_pick_place/teacher/env_jt_b140.json
@@ -0,0 +1 @@
+{"starts": "artifacts/so101_pick_place/rl_inputs/banks/bank_pp_split0.npz"}
diff --git a/so101_pick_place/code/configs/so101_pick_place/teacher/env_jt_h110.json b/so101_pick_place/code/configs/so101_pick_place/teacher/env_jt_h110.json
new file mode 100644
index 0000000000000000000000000000000000000000..d77af9bb32b9915f5b192460bda902e4e6a4c090
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_pick_place/teacher/env_jt_h110.json
@@ -0,0 +1 @@
+{"starts": "artifacts/so101_pick_place/rl_inputs/banks/bank_pp_split0.npz", "task": {"hold_cap_s": 2.5}, "note": "training-only: at most 2.5 s held in the air (evaluation rule 3.5 s)"}
diff --git a/so101_pick_place/code/configs/so101_policy/ppo/curriculum_tol_v3.json b/so101_pick_place/code/configs/so101_policy/ppo/curriculum_tol_v3.json
new file mode 100644
index 0000000000000000000000000000000000000000..8a1bbd5c8e451b253c8d9c66f3325757731a4884
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/ppo/curriculum_tol_v3.json
@@ -0,0 +1,8 @@
+{
+ "note": "Tolerance ladder v3 (build4_ppo2.md, 2026-10-12 00:10): curriculum_tol_v2 with std_reset false at every promotion. In the kinematic-world sweep both CARRY-macro runs (kE, kF) collapsed right after the promotion to 15 mm (validation 67 / 71 % at 30 mm -> 7 / 11 % at 15 mm, 10 iterations later): the promotion raised the move std from 0.18 back to 0.3 (train_cfg std_reset), and with the CARRY macro a[0:2] x 0.32 m turns that into about 10 cm of carry-target noise. The default-carry run kC did not collapse (89.6 -> 95.1 %).",
+ "stages": [
+ {"name": "tol30", "task": {"tol_xy": 0.030, "tol_yaw": 0.5235987755982988}, "promote": 0.6, "min_iters": 20},
+ {"name": "tol15", "task": {"tol_xy": 0.015, "tol_yaw": 0.2617993877991494}, "promote": 0.75, "min_iters": 20, "std_reset": false},
+ {"name": "tol10", "task": {"tol_xy": 0.010, "tol_yaw": 0.17453292519943295}, "std_reset": false}
+ ]
+}
diff --git a/so101_pick_place/code/configs/so101_policy/ppo/env_v2.json b/so101_pick_place/code/configs/so101_policy/ppo/env_v2.json
new file mode 100644
index 0000000000000000000000000000000000000000..2b1649aee5059f3d6aa3a13e34ea9c0a923701ff
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/ppo/env_v2.json
@@ -0,0 +1,11 @@
+{
+ "note": "env_v2 (2026-10-11 23:10, build4_ppo2.md): env_v1 + the decoder PPO options that apply in EVERY world (decoder module docstring, 'PPO options'): grasp_gate (a GRASP trigger whose descent end puts the cube outside 4.5 mm / 10 mm / 2.5 deg is ignored at no cost: the permanent rule instead of the grasp assist), grasp_latch (a started GRASP is not aborted by a[4]) and abort_action (a 7th action a[6] = the explicit abort; review_code_v2 R3). Task rules pinned (review R6): self_rule and ghost_rule on (the TaskConfig defaults since 21:24). Default free-motion carry (decoder cosine blend). Starts: production_plus split 0 task-family first states (25,197).",
+ "starts": "artifacts/so101_pick_place/nrd_data/production_plus",
+ "start_split": 0,
+ "pool_size": 65536,
+ "nrd_cuda_graph": true,
+ "task": {"self_rule": true, "ghost_rule": true},
+ "decoder": {"grasp_gate": true, "grasp_latch": true, "abort_action": true},
+ "grasp_shaping": {},
+ "obs_rate_noise": [0.0, 0.0]
+}
diff --git a/so101_pick_place/code/configs/so101_policy/ppo/joint_ppo_v3.json b/so101_pick_place/code/configs/so101_policy/ppo/joint_ppo_v3.json
new file mode 100644
index 0000000000000000000000000000000000000000..6c225b7954322420ac7d0e4c082501c48d3bc223
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/ppo/joint_ppo_v3.json
@@ -0,0 +1,35 @@
+{
+ "note": "build9 joint teacher PPO v3 (2026-10-14 16:20): joint_ppo_v2 with std 0.05 normalised (arm offset about 1.5 mrad), floor 0.02, cap 0.2.",
+ "algorithm": {
+ "clip_param": 0.2,
+ "desired_kl": 0.005,
+ "entropy_coef": 0.0,
+ "gamma": 0.99,
+ "lam": 0.95,
+ "learning_rate": 3e-05,
+ "max_grad_norm": 1.0,
+ "num_learning_epochs": 5,
+ "num_mini_batches": 8,
+ "schedule": "adaptive",
+ "use_clipped_value_loss": true,
+ "value_loss_coef": 1.0
+ },
+ "num_steps_per_env": 32,
+ "critic_lr": 0.0003,
+ "init_std": [
+ 0.05,
+ 0.05
+ ],
+ "std_floor": [
+ 0.02,
+ 0.02
+ ],
+ "std_cap": [
+ 0.2,
+ 0.2
+ ],
+ "std_reset": [
+ 0.05,
+ 0.05
+ ]
+}
\ No newline at end of file
diff --git a/so101_pick_place/code/configs/so101_policy/ppo/r2s/joint_ppo_v3_kl02.json b/so101_pick_place/code/configs/so101_policy/ppo/r2s/joint_ppo_v3_kl02.json
new file mode 100644
index 0000000000000000000000000000000000000000..d12acba8b6fa211ba9999382b97bbad2d3f50ad3
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/ppo/r2s/joint_ppo_v3_kl02.json
@@ -0,0 +1,35 @@
+{
+ "note": "real2sim teacher fine-tune 2026-10-22: joint_ppo_v3 with desired_kl 0.02 (v3: 0.005; in the fine-tunes under the robot dynamics stage the adaptive lr fell to 2.25e-6 at kl 0.007 and success stayed flat).",
+ "algorithm": {
+ "clip_param": 0.2,
+ "desired_kl": 0.02,
+ "entropy_coef": 0.0,
+ "gamma": 0.99,
+ "lam": 0.95,
+ "learning_rate": 0.0001,
+ "max_grad_norm": 1.0,
+ "num_learning_epochs": 5,
+ "num_mini_batches": 8,
+ "schedule": "adaptive",
+ "use_clipped_value_loss": true,
+ "value_loss_coef": 1.0
+ },
+ "num_steps_per_env": 32,
+ "critic_lr": 0.0003,
+ "init_std": [
+ 0.05,
+ 0.05
+ ],
+ "std_floor": [
+ 0.02,
+ 0.02
+ ],
+ "std_cap": [
+ 0.2,
+ 0.2
+ ],
+ "std_reset": [
+ 0.05,
+ 0.05
+ ]
+}
diff --git a/so101_pick_place/code/configs/so101_policy/ppo/r2s/teacher_roll_v12_fr10.json b/so101_pick_place/code/configs/so101_policy/ppo/r2s/teacher_roll_v12_fr10.json
new file mode 100644
index 0000000000000000000000000000000000000000..469e94198c2df89ebca0e0e46b2efe8c70da9563
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/ppo/r2s/teacher_roll_v12_fr10.json
@@ -0,0 +1,15 @@
+{
+ "starts": "artifacts/so101_pick_place/rl_inputs/banks/bank_pp_h45mix.npz",
+ "horizon": 1500,
+ "task": {
+ "hold_cap_s": 20.0
+ },
+ "hold_obs_s": 3.5,
+ "roll_hi_deg": 98.0,
+ "floor_raise": [
+ 0.01,
+ 0.0,
+ 0.0
+ ],
+ "note": "real2sim round v12 (2026-10-26), table-drop track, teacher env for a flat 10 mm raise (table plane (-0.010, 0, 0)): teacher_roll_v8.json (D's teacher env, everything else unchanged: start bank bank_pp_h45mix, 30 s episodes, hold cap 20 s, held-time scale 3.5 s, roll cap 98, nominal NRD worlds) + floor_raise (JointEnvConfig.floor_raise): the action-layer floor 1.5 mm above z = c0 + c1 x + c2 y at the grasp point instead of z = 0; the table, cube, task rules and observation stay at the sim table. This is the robot's flat arm-frame floor seen in the true frame by a student distilled with the same fixed table plane (online config table_bias {\"plane\": -floor_raise}, student_floor \"observed\"; vision_viral.py online refuses a labelling teacher with another floor raise). No grasp_shift. arm_table OFF (v9c rule), with evidence (~/so101_r2s_claude/v12/table/baseline_summary.json, D's teacher, 100 tasks per set): under any raise (5 / 10 / 15 mm, plane) the rule (margin 0, tau 20 ms, grasp only) would fire in 0 of 1,200 NRD and 0 of 1,200 MuJoCo episodes (raise 0: 13 / 300 and 9 / 300), MuJoCo arm-table ends 0 of 1,500 and the true lowest gripper point before the lift >= 1.8 mm: the rule would not change the reward. D's teacher at this raise, lenient % home_dev100 / dev100 / home45_dev100: NRD 94/89/91, CPU MuJoCo 93/90/90 (raise 0: NRD 99/100/99, MuJoCo 95/90/91). The floor is not a hard stop: the guard lets a target go as low as the measured pose, and the arm sags below the floor before the lift; D's teacher, lowest true gripper point before the lift minus the raised floor (1.5 mm above the raise; corrected 2026-10-26, review finding 7): NRD p50 -3.8 / p10 -5.1 / min -6.8 mm, CPU MuJoCo p50 -3.6 / min -6.1 mm (raise 0: NRD p50 +0.3 mm, the table holds it). The real robot (eval episodes 10-24..10-26, n 68 holds, flat floor): p50 -4.4, p10 -11.6, min -14.0 mm (D: p50 -3.8 mm, n 18). The dev evaluations log this gap (floor gap p50 / p10; teacher gate: p10 not below the robot's -11.6 mm). Failures of D's teacher at this raise (NRD, 300 tasks): 16 'unsupported' ends (raise 0: 1). Launch (2026-10-26, seed 122, ~/so101_r2s_claude/v12/launch/submit_v12_teacher.py, repo_v12): r2s_teacher_ppo.sbatch ENVCFG= INIT= TRAINCFG=configs/so101_policy/ppo/r2s/joint_ppo_v3_kl02.json, 8,192 worlds, 200 iterations, DEV_TASKS=home45_dev100 DEV_EXTRA='dev100 home_dev100' EXTRA=--dev-match-env (the dev evaluations take the floor raise)."
+}
diff --git a/so101_pick_place/code/configs/so101_policy/ppo/r2s/teacher_roll_v8.json b/so101_pick_place/code/configs/so101_policy/ppo/r2s/teacher_roll_v8.json
new file mode 100644
index 0000000000000000000000000000000000000000..67f9984710efe3f28039c6fda091a830b2bbbf65
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/ppo/r2s/teacher_roll_v8.json
@@ -0,0 +1,10 @@
+{
+ "starts": "artifacts/so101_pick_place/rl_inputs/banks/bank_pp_h45mix.npz",
+ "horizon": 1500,
+ "task": {
+ "hold_cap_s": 20.0
+ },
+ "hold_obs_s": 3.5,
+ "roll_hi_deg": 98.0,
+ "note": "real2sim round v8 (2026-10-23), wrist-roll cap. Robot: the guard clamps the roll command at +101.2 sim deg (the motor's calibrated range ends at +-180 real deg, minus the guard's 3 deg margin; real = sim + 75.8 deg); the sim target range goes to 159.9 deg; 9 of 115 robot student episodes stopped there (4 of 11 carries across the base). Why 98 and not 100: at the clamp the servo reaches only 100.69 deg (0.52 deg short: dead band / breakaway). A steady command above ~100.7 lets the guard's integral correction wind up to its 3 deg limit against the clamp, Guard.prev = 101.21 - 3.00 = 98.21, |q - prev| = 2.48 deg >= 0.9 x LEAD = 2.455 deg, and after 25 steps 'stall: wrist_roll blocked' (both robot stalls: ~/so101_r2s_claude/robot_logs/eval_20261023_141614/ep_06 and eval_20261023_144431/ep_01; student targets 100.7-101.8 deg). The sim cannot show this (RobotDyn clamps at the cap, no stall rule). 98 leaves 2.7 deg below the reachable 100.7 for the student's output error. roll_hi_deg caps every wrist-roll target of the env (JointEnvConfig.roll_hi_deg: action layer, world target, start-bank rows above it dropped); the teacher's observation is unchanged. Start bank bank_pp_h45mix.npz (vision_viral_teacher.py starts): bank_pp_split0 once (25,197 rows) + the HOME45 training starts (train_H45_8k = the HOME45 half of train_mix45_16k) 3 times = 49,773 rows, 49 % HOME45 (the robot starts at HOME45, where the cap costs most). PPO fine-tune from jt_h110 in NOMINAL NRD worlds (no robot dynamics stage) with v7's 30 s episodes (hold cap 20 s, observation scale 3.5 s = the online env); joint_ppo_v3_kl02.json, 200 iterations; r2s_teacher_ppo.sbatch with DEV_TASKS=home45_dev100 DEV_EXTRA=dev100 EXTRA=--dev-match-env (RUN/dev_evals.jsonl). jt_h110 with the cap 98 (NRD nominal, 30 s, ~/so101_r2s_claude/roll_v8/jt_roll_count_98.json): lenient HOME45 train 97.6 -> 88.8 % (25 % of the episodes command above 98), home45_dev100 95 -> 84 %, home45_fresh100 96 -> 93 %, start bank 98.4 -> 96.7 % (11.5 %), dev100 99 -> 96 %; the failures are time-outs (cap 100: 140 of 241 HOME45 over-cap episodes go above it first at the grasp alignment, 101 in the carry). The cap is a clamp, no penalty: PPO gets no gradient on the raw command above it, so the log's 'roll over cap' need not fall. Gate (vision_viral_teacher.py eval --roll-hi-deg 98 --horizon 1500 --hold-cap-s 20 --hold-obs-s 3.5; NRD and MuJoCo; home45_dev100, home45_fresh100, dev100): lenient back near the uncapped jt_h110 (NRD 95 / 96 / 99 %) and roll_q_at_cap (episodes whose measured roll comes within 0.5 deg of the cap) well below jt_h110's 44 / 34 / 13 %."
+}
diff --git a/so101_pick_place/code/configs/so101_policy/ppo/train_v2.json b/so101_pick_place/code/configs/so101_policy/ppo/train_v2.json
new file mode 100644
index 0000000000000000000000000000000000000000..f6345465466ad7ae4e5268c9335126fa5cbad0ce
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/ppo/train_v2.json
@@ -0,0 +1,14 @@
+{
+ "note": "train_v2 (2026-10-11 23:10, build4_ppo2.md): train_v1 with the trigger bias -1 (P(a[4] > 0) = 16 % per decision at std 1: with the decoder's grasp gate an out-of-box trigger costs nothing, so the trigger may explore more than at bias -2 = 2.3 %), the abort group (a[6], decoder abort_action: init std 0.5, floor 0.2, cap 1.0, bias -3) and 8 minibatches of 32 decisions x num_envs.",
+ "algorithm": {"clip_param": 0.2, "desired_kl": 0.01, "entropy_coef": 0.002, "gamma": 0.99, "lam": 0.95,
+ "learning_rate": 0.0003, "max_grad_norm": 1.0, "num_learning_epochs": 5, "num_mini_batches": 8,
+ "schedule": "adaptive", "use_clipped_value_loss": true, "value_loss_coef": 1.0},
+ "policy": {"actor_hidden_dims": [512, 256, 128], "critic_hidden_dims": [512, 256, 128], "activation": "elu",
+ "actor_out_gain": 0.01, "action_bias": [0.0, 0.0, 0.0, 0.0, -1.0, 0.0, -3.0], "norm_clip": 10.0},
+ "num_steps_per_env": 32,
+ "critic_lr": 0.0003,
+ "init_std": [0.3, 1.0, 0.5, 0.5],
+ "std_floor": [0.15, 0.3, 0.2, 0.2],
+ "std_cap": [0.3, 2.0, 1.0, 1.0],
+ "std_reset": [0.3, 1.0, 0.5, 0.5]
+}
diff --git a/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_home.json b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_home.json
new file mode 100644
index 0000000000000000000000000000000000000000..03dd5d157ca6a3f7771cc403e76256bf1c10cabc
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_home.json
@@ -0,0 +1,20 @@
+{
+ "note": "real2sim HOME task starts v2 (2026-10-22, tray.make_tasks stage H): the arm at rest at the real robot's HOME pose (scripts/so101_policy/real2sim/hw/hw_lib.HOME_SIM_DEG = 0, -5, -15, 92, 45, 30 sim deg: pan, lift, elbow, wrist_flex, wrist_roll, jaw) + U(-3, 3) deg per joint, U(-15, 15) deg on the wrist roll (the roll calibration is uncertain by about 15 deg; jt_h110 >= 97 % at roll 30-60), the cube resting at the xy / yaw of a random row of jt_h110's PPO start bank, the goal by stage C's rule. v1 (roll 0) gave jt_h110 93-95 % lenient CPU MuJoCo, roll 45 98.1 % (~/so101_r2s_claude/teacher_check/logs/report_final.log).",
+ "home_deg": [
+ 0.0,
+ -5.0,
+ -15.0,
+ 92.0,
+ 45.0,
+ 30.0
+ ],
+ "noise_deg": [
+ 3.0,
+ 3.0,
+ 3.0,
+ 3.0,
+ 15.0,
+ 3.0
+ ],
+ "bank": "artifacts/so101_pick_place/rl_inputs/banks/bank_pp_split0.npz"
+}
diff --git a/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_relabel_roll_v8.json b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_relabel_roll_v8.json
new file mode 100644
index 0000000000000000000000000000000000000000..0e01dfaba953eca92c9bac8202fe1ecaeda166cd
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_relabel_roll_v8.json
@@ -0,0 +1,45 @@
+{
+ "note": "viral_r2s_online_relabel_v4.json + the wrist-roll cap (real2sim round v8, 2026-10-23): roll_hi_deg 98 (sim deg; the robot guard clamps at 101.2, where the servo reaches only 100.69 deg: a command above ~100.7 winds the guard's integral correction up and the stall rule stops the robot; 98 leaves 2.7 deg for the student's output error; configs/so101_policy/ppo/r2s/teacher_roll_v8.json note) caps every wrist-roll target of the online env, the JT's labels get the same cap (the student never learns a roll command above it), task rows that start above it leave the pool (train_mix45_16k: 1 of 16,384, seed 687570 at 119.9 deg) and the in-run evaluations use it. Teacher: the roll-capped fine-tune (teacher_roll_v8.json) via r2s_online.sbatch TEACHER_JT=; the run refuses a JT trained without the cap (vision_viral.py online --allow-uncapped-jt overrides): jt_h110's plans go above 98 in 25 % of the HOME45 episodes, and capped labels alone do not teach another grasp roll (HOME45 lenient 97.6 -> 88.8 %). Log columns roll_over_student / roll_over_teacher = share of the finished episodes whose command went above the cap. | v4 note: Root cause (2026-10-22): the student's step size follows the MEASURED qdot; the real arm is ~5x slower, so the steps shrink and the arm holds still above the plate (robot-like sim: today's student 50 %, 88-94 % with its qdot input x2-3). Track C1: robot dynamics in the student slots (no command delay: it dropped commands and broke the grasp in dyn v2; gain 0.3-1, lag 20-150 ms, sag 0-1.5 deg + the guard's integral correction), the JT labels those worlds with the COMMANDED speed in its qdot observation (relabel_cmd_speed) so its labels keep the nominal pace; robot-like qdot input in half of the worlds, image lag 1-4, 30 s episodes.",
+ "envs": 1024,
+ "teacher_share": 0.5,
+ "noise_share": 0.5,
+ "noise": 1.0,
+ "nominal_share": 0.2,
+ "default_light_p": 0.25,
+ "buffer": 100000,
+ "steps_per_iter": 8,
+ "lr": 0.0001,
+ "lr_backbone": 5e-05,
+ "iterations": 3000,
+ "eval_every": 1000,
+ "save_every": 250,
+ "log_every": 25,
+ "dyn": {
+ "p": 0.8,
+ "d_lo": 0,
+ "d_hi": 0,
+ "jitter": 0.0,
+ "s_lo": 0.3,
+ "s_hi": 1.0,
+ "tau_lo": 0.02,
+ "tau_hi": 0.15,
+ "sag_max_deg": 1.5,
+ "noise_max": 0.0,
+ "i_time_s": 0.2,
+ "i_max_deg": 3.0,
+ "i_e_max_deg": 1.0,
+ "i_v_min": 0.02
+ },
+ "dyn_student_only": true,
+ "qd_robot_p": 0.5,
+ "qd_window": 3,
+ "horizon": 1500,
+ "hold_cap_s": 20.0,
+ "hold_obs_s": 3.5,
+ "lag_range": [
+ 1,
+ 4
+ ],
+ "relabel_cmd_speed": true,
+ "roll_hi_deg": 98.0
+}
diff --git a/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_relabel_v4.json b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_relabel_v4.json
new file mode 100644
index 0000000000000000000000000000000000000000..3f80bab4d1eb504fb4145e811d590239c6b99072
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_relabel_v4.json
@@ -0,0 +1,44 @@
+{
+ "note": "Root cause (2026-10-22): the student's step size follows the MEASURED qdot; the real arm is ~5x slower, so the steps shrink and the arm holds still above the plate (robot-like sim: today's student 50 %, 88-94 % with its qdot input x2-3). Track C1: robot dynamics in the student slots (no command delay: it dropped commands and broke the grasp in dyn v2; gain 0.3-1, lag 20-150 ms, sag 0-1.5 deg + the guard's integral correction), the JT labels those worlds with the COMMANDED speed in its qdot observation (relabel_cmd_speed) so its labels keep the nominal pace; robot-like qdot input in half of the worlds, image lag 1-4, 30 s episodes.",
+ "envs": 1024,
+ "teacher_share": 0.5,
+ "noise_share": 0.5,
+ "noise": 1.0,
+ "nominal_share": 0.2,
+ "default_light_p": 0.25,
+ "buffer": 100000,
+ "steps_per_iter": 8,
+ "lr": 0.0001,
+ "lr_backbone": 5e-05,
+ "iterations": 3000,
+ "eval_every": 1000,
+ "save_every": 250,
+ "log_every": 25,
+ "dyn": {
+ "p": 0.8,
+ "d_lo": 0,
+ "d_hi": 0,
+ "jitter": 0.0,
+ "s_lo": 0.3,
+ "s_hi": 1.0,
+ "tau_lo": 0.02,
+ "tau_hi": 0.15,
+ "sag_max_deg": 1.5,
+ "noise_max": 0.0,
+ "i_time_s": 0.2,
+ "i_max_deg": 3.0,
+ "i_e_max_deg": 1.0,
+ "i_v_min": 0.02
+ },
+ "dyn_student_only": true,
+ "qd_robot_p": 0.5,
+ "qd_window": 3,
+ "horizon": 1500,
+ "hold_cap_s": 20.0,
+ "hold_obs_s": 3.5,
+ "lag_range": [
+ 1,
+ 4
+ ],
+ "relabel_cmd_speed": true
+}
diff --git a/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_v1.json b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_v1.json
new file mode 100644
index 0000000000000000000000000000000000000000..a9f56949812b3c852501ac8d260be26eb7125d6e
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_v1.json
@@ -0,0 +1,17 @@
+{
+ "note": "real2sim online loop v1 (2026-10-21): build9's viral_online_v1 (the o16 / o17 loop: 1,024 NRD worlds, slots 0-511 JT-driven, half of them with 1 x std noise, 20 % nominal-visual slots, the scene light in 25 % of the decisions, 100,000-sample GPU buffer, 8 steps of 128 per decision, constant lr 1e-4 / 5e-5) for 3,000 decisions (o16 was cancelled after 3,000 of 6,000; constant lr, so the same schedule). Use with --config viral_r2s_v1.json (jaw lead 0).",
+ "envs": 1024,
+ "teacher_share": 0.5,
+ "noise_share": 0.5,
+ "noise": 1.0,
+ "nominal_share": 0.2,
+ "default_light_p": 0.25,
+ "buffer": 100000,
+ "steps_per_iter": 8,
+ "lr": 0.0001,
+ "lr_backbone": 0.00005,
+ "iterations": 3000,
+ "eval_every": 1000,
+ "save_every": 250,
+ "log_every": 25
+}
diff --git a/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_v12_tb10.json b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_v12_tb10.json
new file mode 100644
index 0000000000000000000000000000000000000000..bd6e12cd11b695741824968b22ae26f39b0934f4
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_online_v12_tb10.json
@@ -0,0 +1,55 @@
+{
+ "note": "real2sim round v12 table-drop student tb10 (2026-10-26): D's online config viral_r2s_online_relabel_roll_v8.json + ONE fixed table plane under every world, a flat table 10 mm below the sim table (table_bias plane c = [-0.01, 0.0, 0.0], p 1, no random draw), table_render on (the images show the lower table), student_floor observed (the online env's floor is flat in the student's observed frame = the robot's flat arm-frame floor; true-frame floor raised by -plane). Nothing else changed (plate, scene, tasks, commanded-speed relabel, robot dynamics, roll cap 98 as D). Labelling teacher: the v12 fine-tune teacher_roll_v12_fr10.json (floor raise 10 mm); the run refuses a teacher with another floor raise. The in-run evaluations run on this plane with 1,500 steps and the 20 s hold cap by default (vision_viral.inrun_eval_setup) | D's note: viral_r2s_online_relabel_v4.json + the wrist-roll cap (real2sim round v8, 2026-10-23): roll_hi_deg 98 (sim deg; the robot guard clamps at 101.2, where the servo reaches only 100.69 deg: a command above ~100.7 winds the guard's integral correction up and the stall rule stops the robot; 98 leaves 2.7 deg for the student's output error; configs/so101_policy/ppo/r2s/teacher_roll_v8.json note) caps every wrist-roll target of the online env, the JT's labels get the same cap (the student never learns a roll command above it), task rows that start above it leave the pool (train_mix45_16k: 1 of 16,384, seed 687570 at 119.9 deg) and the in-run evaluations use it. Teacher: the roll-capped fine-tune (teacher_roll_v8.json) via r2s_online.sbatch TEACHER_JT=; the run refuses a JT trained without the cap (vision_viral.py online --allow-uncapped-jt overrides): jt_h110's plans go above 98 in 25 % of the HOME45 episodes, and capped labels alone do not teach another grasp roll (HOME45 lenient 97.6 -> 88.8 %). Log columns roll_over_student / roll_over_teacher = share of the finished episodes whose command went above the cap. | v4 note: Root cause (2026-10-22): the student's step size follows the MEASURED qdot; the real arm is ~5x slower, so the steps shrink and the arm holds still above the plate (robot-like sim: today's student 50 %, 88-94 % with its qdot input x2-3). Track C1: robot dynamics in the student slots (no command delay: it dropped commands and broke the grasp in dyn v2; gain 0.3-1, lag 20-150 ms, sag 0-1.5 deg + the guard's integral correction), the JT labels those worlds with the COMMANDED speed in its qdot observation (relabel_cmd_speed) so its labels keep the nominal pace; robot-like qdot input in half of the worlds, image lag 1-4, 30 s episodes.",
+ "envs": 1024,
+ "teacher_share": 0.5,
+ "noise_share": 0.5,
+ "noise": 1.0,
+ "nominal_share": 0.2,
+ "default_light_p": 0.25,
+ "buffer": 100000,
+ "steps_per_iter": 8,
+ "lr": 0.0001,
+ "lr_backbone": 5e-05,
+ "iterations": 3000,
+ "eval_every": 1000,
+ "save_every": 250,
+ "log_every": 25,
+ "dyn": {
+ "p": 0.8,
+ "d_lo": 0,
+ "d_hi": 0,
+ "jitter": 0.0,
+ "s_lo": 0.3,
+ "s_hi": 1.0,
+ "tau_lo": 0.02,
+ "tau_hi": 0.15,
+ "sag_max_deg": 1.5,
+ "noise_max": 0.0,
+ "i_time_s": 0.2,
+ "i_max_deg": 3.0,
+ "i_e_max_deg": 1.0,
+ "i_v_min": 0.02
+ },
+ "dyn_student_only": true,
+ "qd_robot_p": 0.5,
+ "qd_window": 3,
+ "horizon": 1500,
+ "hold_cap_s": 20.0,
+ "hold_obs_s": 3.5,
+ "lag_range": [
+ 1,
+ 4
+ ],
+ "relabel_cmd_speed": true,
+ "roll_hi_deg": 98.0,
+ "table_bias": {
+ "plane": [
+ -0.01,
+ 0.0,
+ 0.0
+ ],
+ "p": 1.0
+ },
+ "table_render": true,
+ "student_floor": "observed"
+}
diff --git a/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_v1.json b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_v1.json
new file mode 100644
index 0000000000000000000000000000000000000000..218752ae3b08c105d5af8f87d61c247105a412ab
--- /dev/null
+++ b/so101_pick_place/code/configs/so101_policy/vision/viral_r2s_v1.json
@@ -0,0 +1,64 @@
+{
+ "note": "real2sim student v1 (2026-10-21, ~/so101_r2s_claude/docs/integrate.md): build9's network and round-based recipe (viral_v2 + qd_noise 0.3 = d2, jaw lead 0) with the REAL cameras and scene: external + wrist calibrated fisheye cameras (crop of the 640 x 480 frame -> 224 px, the deployment's student_view rule), the light-box scene of the scene file (body groups, RealDR randomisation, its lights, optional tone map, its image_fx camera effects), image lag 2 control steps (40 ms; real 42-48 ms) at evaluation, drawn 1-3 per world per episode in training; extra student-side effects (vignetting, white balance, gamma); DRConfig colour augmentation kept, its noise / blur off (image_fx has them). scene: the final file of the render agent; calib: '' = the scene file's own calib entry (override on AMD with --set calib=...). 2026-10-22: scene -> real_scene_v2.json (v1 + wider room colour, exposure and gamma randomisation after the scene review). DRConfig contrast p 0.5, 0.75-1.6 (was p 0.4, 0.6-1.4): real contrast was at rank 0.81 (external) / 0.93 (wrist) of the draws.",
+ "chunk": 10,
+ "n_exec": 5,
+ "res": 224,
+ "cameras": [
+ "external",
+ "wrist"
+ ],
+ "qd_noise": 0.3,
+ "encoder": "resnet18",
+ "stages": 3,
+ "keypoints": 32,
+ "pool_dim": 64,
+ "hidden": [
+ 512,
+ 512
+ ],
+ "aux_weight": 1.0,
+ "aux_hidden": 256,
+ "jaw_lead": 0,
+ "batch": 128,
+ "render_batch": 256,
+ "lr": 0.0003,
+ "lr_backbone": 0.0001,
+ "weight_decay": 0.0001,
+ "warmup": 300,
+ "grad_clip": 10.0,
+ "amp": true,
+ "dr": {
+ "p_noise": 0.0,
+ "p_blur": 0.0,
+ "p_contrast": 0.5,
+ "contrast": [
+ 0.75,
+ 1.6
+ ]
+ },
+ "dr_frac": 1.0,
+ "reuse": 2,
+ "scene": "configs/so101_pick_place/real_scene_v2.json",
+ "calib": "",
+ "crops": {},
+ "real_dr": {},
+ "cam_fx": {
+ "p_vignette": 0.3,
+ "vignette": [
+ 0.0,
+ 0.3
+ ],
+ "p_wb": 0.3,
+ "wb": 0.08,
+ "p_gamma": 0.3,
+ "gamma": [
+ 0.85,
+ 1.2
+ ]
+ },
+ "lag": 2,
+ "lag_range": [
+ 1,
+ 3
+ ]
+}
diff --git a/so101_pick_place/code/contact_nrd/so101_grasp/.gitignore b/so101_pick_place/code/contact_nrd/so101_grasp/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..64d817af7d2786290dd63cf9e2f62432ec9a9889
--- /dev/null
+++ b/so101_pick_place/code/contact_nrd/so101_grasp/.gitignore
@@ -0,0 +1,2 @@
+vendor/
+__pycache__/
diff --git a/so101_pick_place/code/contact_nrd/so101_grasp/fetch_sources.py b/so101_pick_place/code/contact_nrd/so101_grasp/fetch_sources.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2ad070f92e88e315322226f4412805c3477d643
--- /dev/null
+++ b/so101_pick_place/code/contact_nrd/so101_grasp/fetch_sources.py
@@ -0,0 +1,61 @@
+"""Fetch the pinned MuJoCo Menagerie SO101 model (sparse, shallow) and verify every file against the manifest.
+
+ python -I contact_nrd/so101_grasp/fetch_sources.py
+
+The checkout goes to vendor/ (gitignored) and is never edited: the collector builds its scene around the
+unchanged so101.xml. The fetched folder holds only data (MJCF, STL meshes, text); nothing in it is executed.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+
+
+ROOT = Path(__file__).resolve().parent
+
+
+def git(*args: str, cwd: Path | None = None) -> str:
+ return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip()
+
+
+def main() -> None:
+ manifest = json.loads((ROOT / "source_manifest.json").read_text())
+ source = manifest["source"]
+ target = ROOT / source["local_path"]
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if not target.exists():
+ with tempfile.TemporaryDirectory(prefix="menagerie-fetch-", dir=target.parent) as tmp:
+ stage = Path(tmp) / "mujoco_menagerie"
+ stage.mkdir()
+ git("init", "--quiet", cwd=stage)
+ git("remote", "add", "origin", source["url"], cwd=stage)
+ git("sparse-checkout", "set", "--no-cone", *source["sparse_paths"], cwd=stage)
+ git("fetch", "--quiet", "--depth", "1", "--filter=blob:none", "origin", source["revision"], cwd=stage)
+ git("checkout", "--quiet", "--detach", "FETCH_HEAD", cwd=stage)
+ stage.rename(target)
+ if Path(git("rev-parse", "--show-toplevel", cwd=target)).resolve() != target.resolve():
+ raise SystemExit(f"Expected a standalone upstream checkout: {target}")
+ if git("rev-parse", "HEAD", cwd=target) != source["revision"]:
+ raise SystemExit("Existing checkout has another revision; leave it intact and use a separate folder.")
+ if git("status", "--porcelain", cwd=target):
+ raise SystemExit("Existing upstream checkout has changes; leave it intact and use a separate folder.")
+ present = sorted(str(p.relative_to(target)) for p in target.rglob("*") if p.is_file() and ".git" not in p.parts)
+ expected = sorted(item["path"] for item in manifest["files"])
+ if present != expected:
+ raise SystemExit(f"Checkout files differ from the manifest: {sorted(set(present) ^ set(expected))}")
+ for item in manifest["files"]:
+ path = target / item["path"]
+ digest = hashlib.sha256(path.read_bytes()).hexdigest()
+ if digest != item["sha256"] or path.stat().st_size != item["bytes"]:
+ raise SystemExit(f"Source verification failed: {path}")
+ if any(p.endswith(".py") for p in present):
+ raise SystemExit("The fetched model holds Python files; it should hold data only.")
+ print(f"Verified mujoco_menagerie {source['revision']} and {len(manifest['files'])} pinned files.")
+ print(f"Model: {target / manifest['model']['path']}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/contact_nrd/so101_grasp/source_manifest.json b/so101_pick_place/code/contact_nrd/so101_grasp/source_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..ca0d2711e559253573209da790706c55c04a6eaf
--- /dev/null
+++ b/so101_pick_place/code/contact_nrd/so101_grasp/source_manifest.json
@@ -0,0 +1,159 @@
+{
+ "schema_version": 1,
+ "fetched_and_audited_utc": "2026-10-09T00:07:22.978008+00:00",
+ "nedm_baseline_revision": "41be3efccb7eb2f74e6741610853557b288a86bc",
+ "source": {
+ "name": "mujoco_menagerie (robotstudio_so101)",
+ "url": "https://github.com/google-deepmind/mujoco_menagerie.git",
+ "revision": "0059d4335f8156206f63a35662313385f7ad6d74",
+ "revision_date": "2026-10-07T13:07:25-07:00",
+ "local_path": "vendor/mujoco_menagerie",
+ "sparse_paths": [
+ "/robotstudio_so101/",
+ "/LICENSE"
+ ]
+ },
+ "files": [
+ {
+ "path": "LICENSE",
+ "bytes": 434514,
+ "sha256": "b1334631b1d7bd73394f95d3241d5110f98f7310ad08b17d3b113518dd967a5b"
+ },
+ {
+ "path": "robotstudio_so101/CHANGELOG.md",
+ "bytes": 391,
+ "sha256": "ac7f6205e40f0fb2bc08ff3ff4c5e5092dacf8d78cb03f024ae9aae33738acc4"
+ },
+ {
+ "path": "robotstudio_so101/LICENSE",
+ "bytes": 11357,
+ "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4"
+ },
+ {
+ "path": "robotstudio_so101/README.md",
+ "bytes": 1142,
+ "sha256": "e2344e7c14290bed85c7907247aecb8bf6cb4392e3de0d7c45680efe9bb9b5a9"
+ },
+ {
+ "path": "robotstudio_so101/assets/base_motor_holder_so101_v1.stl",
+ "bytes": 1877084,
+ "sha256": "8cd2f241037ea377af1191fffe0dd9d9006beea6dcc48543660ed41647072424"
+ },
+ {
+ "path": "robotstudio_so101/assets/base_so101_v2.stl",
+ "bytes": 471584,
+ "sha256": "bb12b7026575e1f70ccc7240051f9d943553bf34e5128537de6cd86fae33924d"
+ },
+ {
+ "path": "robotstudio_so101/assets/motor_holder_so101_base_v1.stl",
+ "bytes": 1129384,
+ "sha256": "31242ae6fb59d8b15c66617b88ad8e9bded62d57c35d11c0c43a70d2f4caa95b"
+ },
+ {
+ "path": "robotstudio_so101/assets/motor_holder_so101_wrist_v1.stl",
+ "bytes": 1052184,
+ "sha256": "887f92e6013cb64ea3a1ab8675e92da1e0beacfd5e001f972523540545e08011"
+ },
+ {
+ "path": "robotstudio_so101/assets/moving_jaw_so101_gripper_part0_v1.stl",
+ "bytes": 50684,
+ "sha256": "3a92e115d1934d4c45cff808c4eff2ea10361a137a7f89940033a1f8a821b88c"
+ },
+ {
+ "path": "robotstudio_so101/assets/moving_jaw_so101_gripper_part1_v1.stl",
+ "bytes": 342684,
+ "sha256": "d10f6c671d26f62988ec95efee9370a0657b5833b3c5f8aad59fd69a87ef2aee"
+ },
+ {
+ "path": "robotstudio_so101/assets/moving_jaw_so101_gripper_v1.stl",
+ "bytes": 690384,
+ "sha256": "e8a5dc040b98e27453a5b74f9087d1dbca14589cf9a17c4de7868d5ab98413cd"
+ },
+ {
+ "path": "robotstudio_so101/assets/moving_jaw_so101_v1.stl",
+ "bytes": 1413584,
+ "sha256": "785a9dded2f474bc1d869e0d3dae398a3dcd9c0c345640040472210d2861fa9d"
+ },
+ {
+ "path": "robotstudio_so101/assets/rotation_pitch_so101_v1.stl",
+ "bytes": 883684,
+ "sha256": "9be900cc2a2bf718102841ef82ef8d2873842427648092c8ed2ca1e2ef4ffa34"
+ },
+ {
+ "path": "robotstudio_so101/assets/sts3215_03a_no_horn_v1.stl",
+ "bytes": 865884,
+ "sha256": "75ef3781b752e4065891aea855e34dc161a38a549549cd0970cedd07eae6f887"
+ },
+ {
+ "path": "robotstudio_so101/assets/sts3215_03a_v1.stl",
+ "bytes": 954084,
+ "sha256": "a37c871fb502483ab96c256baf457d36f2e97afc9205313d9c5ab275ef941cd0"
+ },
+ {
+ "path": "robotstudio_so101/assets/under_arm_so101_v1.stl",
+ "bytes": 1975884,
+ "sha256": "d01d1f2de365651dcad9d6669e94ff87ff7652b5bb2d10752a66a456a86dbc71"
+ },
+ {
+ "path": "robotstudio_so101/assets/upper_arm_so101_v1.stl",
+ "bytes": 1303484,
+ "sha256": "475056e03a17e71919b82fd88ab9a0b898ab50164f2a7943652a6b2941bb2d4f"
+ },
+ {
+ "path": "robotstudio_so101/assets/waveshare_mounting_plate_so101_v2.stl",
+ "bytes": 62784,
+ "sha256": "e197e24005a07d01bbc06a8c42311664eaeda415bf859f68fa247884d0f1a6e9"
+ },
+ {
+ "path": "robotstudio_so101/assets/wrist_roll_follower_so101_camera_mount.stl",
+ "bytes": 122884,
+ "sha256": "58c457b33a26d9c9bb337aa351173e7123f84719a93f486541adef6eba57ae21"
+ },
+ {
+ "path": "robotstudio_so101/assets/wrist_roll_follower_so101_gripper_part0_v1.stl",
+ "bytes": 73784,
+ "sha256": "370eb470a6ab48b08febcaeb5274d2bcc91246692532ce12c795fb82977def72"
+ },
+ {
+ "path": "robotstudio_so101/assets/wrist_roll_follower_so101_gripper_v1.stl",
+ "bytes": 741684,
+ "sha256": "65f32debcf265420c0160afe004f8befc5df4b3e578fd59ebaa62eade0371224"
+ },
+ {
+ "path": "robotstudio_so101/assets/wrist_roll_follower_so101_v1.stl",
+ "bytes": 1439884,
+ "sha256": "4b17b410a12d64ec39554abc3e8054d8a97384b2dc4a8d95a5ecb2a93670f5f4"
+ },
+ {
+ "path": "robotstudio_so101/assets/wrist_roll_pitch_so101_v2.stl",
+ "bytes": 2699784,
+ "sha256": "6c7ec5525b4d8b9e397a30ab4bb0037156a5d5f38a4adf2c7d943d6c56eda5ae"
+ },
+ {
+ "path": "robotstudio_so101/scene.xml",
+ "bytes": 825,
+ "sha256": "d3037f0fd36b61a9b6805b2c79831e7a392276d0f490145d01f718542eee9150"
+ },
+ {
+ "path": "robotstudio_so101/scene_box.xml",
+ "bytes": 1469,
+ "sha256": "14c3826f23889587e63b88ef9a0e7d72318ffe13078fad8287c56dbdb9ba9ad8"
+ },
+ {
+ "path": "robotstudio_so101/so101.png",
+ "bytes": 1010575,
+ "sha256": "fca552381f318dab5b1f9a69007e79d905d91c9d1bebbfdf267b78d924a9c46d"
+ },
+ {
+ "path": "robotstudio_so101/so101.xml",
+ "bytes": 17206,
+ "sha256": "982c02c027ec0c62d3459d0a6eb00dfb7dc13a451992e72ce99addc71f209805"
+ }
+ ],
+ "model": {
+ "path": "robotstudio_so101/so101.xml",
+ "license": "Apache-2.0 (robotstudio_so101/LICENSE)",
+ "used_unchanged": true,
+ "note": "The collector loads so101.xml with mujoco.MjSpec and adds the table, the cube, the options and the contact exclusions in code; the vendor files are not edited."
+ }
+}
diff --git a/so101_pick_place/code/docs/hf_dataset_card.md b/so101_pick_place/code/docs/hf_dataset_card.md
new file mode 100644
index 0000000000000000000000000000000000000000..e4f88e22f099275429e1d607908c65c31407d879
--- /dev/null
+++ b/so101_pick_place/code/docs/hf_dataset_card.md
@@ -0,0 +1,866 @@
+---
+license: bsd-3-clause
+pretty_name: NeDM Neural Reduced Dynamics Datasets
+tags:
+ - robotics
+ - vehicle-dynamics
+ - project-chrono
+ - simulation
+ - time-series
+ - reduced-order-model
+ - reinforcement-learning
+ - terramechanics
+task_categories:
+ - time-series-forecasting
+ - robotics
+size_categories:
+ - 100M **Learning the Right Abstraction: Neural Reduced Dynamics for Complex Robot Control**
+> Harry Zhang and Dan Negrut, 2026 (preprint).
+> Project page: · Code:
+
+Every dataset here is exactly what the paper's models were trained and validated on. Two tiers
+are published (70 GB in total):
+
+* **`raw/`** — every recorded channel of every episode (Parquet, float32), plus a per-episode
+ index and the byte-exact collection metadata (driver profiles, seeds, terrain, termination
+ causes). This is the reusable resource: build your own reduced states from it.
+* **`processed/`** — the four training caches the deployed models read (`.npy`), so the
+ paper's training configs run without touching the raw data.
+
+### Datasets
+
+| Config | System | Terrain / task | Rate | Episodes (train / val) | Rows | Raw Parquet | Columns |
+|---|---|---|---|---|---|---|---|
+| `hmmwv_flat` | HMMWV (`HMMWV_Full`, TMEASY tires, SMC contact) | flat rigid, μ = 0.9, 900 × 900 m | 100 Hz | 32,768 (26,124 / 6,644) | 160,551,861 | 44.0 GB, 128 shards | 105 |
+| `hmmwv_bumpy` | HMMWV (same vehicle) | rigid heightmap, 100 random 500 × 500 m fields, ±0.6 m | 100 Hz | 1,360 (1,104 / 256) | 4,511,778 | 1.3 GB, 4 shards | 105 |
+| `hmmwv_crm` | HMMWV (rigid-mesh tires) | CRM deformable soil (SPH), 150 × 150 × 0.25 m | 100 Hz | 2,000 (1,582 / 418) | 2,884,961 | 0.8 GB, 4 parts | 105 |
+| `arm` | 4-DOF LRV arm mounted on an M113 (base held) | free-space joint motion, PD torque control | 50 Hz | 15,000 (12,716 / 2,284) | 920,640 | 0.09 GB, 15 shards | 47 |
+| `tracked` | M113 tracked vehicle, arm welded at home | flat rigid drive, 10 manoeuvre families | 50 Hz | 2,160 (1,808 / 352) | 1,683,484 | 0.2 GB, 60 shards | 42 |
+
+Roles in the paper: `hmmwv_flat` + `hmmwv_crm` train the terrain-conditioned HMMWV NN-ROM
+(Study Case I); `hmmwv_bumpy` is the zero-shot out-of-distribution test regime and never enters
+training, model selection, normalisation or reward tuning; `tracked` and `arm` train the two
+Study Case II NN-ROMs. All five were collected with PyChrono 10.0.0 (conda `projectchrono`
+channel) using the collectors in the code repository (`src/nedm/hmmwv_data.py`,
+`scripts/collection/collect_hmmwv_crm_dataset.py`, `src/nedm/arm_data.py`,
+`src/nedm/tracked_vehicle_data.py`).
+
+#### Splits
+
+Train/val is decided **per episode at collection time** and stored in the `split` column:
+`sha1(episode_id)[:8] / 0xFFFFFFFF < validation_ratio → val` (ratio 0.20 for the HMMWV sets,
+0.15 for `arm` and `tracked`). Whole episodes stay together; the assignment depends only on the
+episode id, so it is stable under re-sharding. `train` and `val` files never share an episode.
+
+### Layout
+
+```
+raw//train/.parquet transitions, one file per raw collection shard
+raw//val/.parquet
+raw//episodes.parquet one row per episode: index entry + JSON sidecar (see below)
+raw//metadata.tar.gz byte-exact originals: dataset_index.json, collector_config.resolved.json,
+ episodes/.json sidecars, shard-plan manifests
+processed// .npy training caches + metadata.json (state layout, normalisation)
+assets/bumpy_terrain/bumpy_field_NNN.bmp the 100 heightmaps behind hmmwv_bumpy (256×256, 8-bit, gray 128 = 0 m)
+release_manifest.json sha256 / size / row count of every file, tool versions, source commit
+```
+
+Rows are ordered by episode (collection order) then `sample_index`; each episode is contiguous
+inside exactly one file. Column names and order are the collector's CSV columns, unchanged. All
+physical channels are `float32` (`time_s` is `float64`; `sample_index`, `collision` are `int32`;
+identifiers are dictionary-encoded strings). Files are zstd-compressed with BYTE_STREAM_SPLIT
+float encoding and ≤ 262,144-row row groups.
+
+#### Column groups
+
+**HMMWV (`hmmwv_flat`, `hmmwv_bumpy`, `hmmwv_crm` — identical 105 columns).** Units are in the
+names (`_m`, `_mps`, `_mps2`, `_rad`, `_radps`, `_n`, `_nm`); world frame is Chrono's ISO
+(x forward, z up), body frame is the chassis frame.
+
+| Group | Columns |
+|---|---|
+| identifiers | `episode_id`, `scenario_name`, `scenario_family`, `split`, `sample_index`, `time_s` |
+| driver command (the action) | `driver_steering` ∈ [−1, 1], `driver_throttle` ∈ [0, 1], `driver_braking` ∈ [0, 1] |
+| chassis pose | `pos_{x,y,z}_m`, `quat_e0..e3`, `roll_rad`, `pitch_rad`, `yaw_rad` |
+| chassis motion | `vel_world_{x,y,z}_mps`, `vel_body_{x,y,z}_mps`, `acc_world_*`, `acc_body_*`, `ang_vel_world_{x,y,z}_radps`, `ang_vel_body_{x,y,z}_radps`, `speed_mps`, `body_slip_rad`, `roll_rate_radps`, `yaw_rate_radps` |
+| per-tire block, prefix `tire_{fl,fr,rl,rr}_` (16 × 4) | `longitudinal_slip`, `slip_angle_rad`, `camber_angle_rad`, `force_world_{x,y,z}_n`, `moment_world_{x,y,z}_nm`, `force_wheel_{fx,fy,fz}_n`, `spindle_omega_radps`, `wheel_vx_mps`, `slip_ratio`, `deflection_m` |
+
+`force_wheel_*` and `slip_ratio` are derived from spindle state and the world-frame force so they
+are computed identically on rigid and CRM terrain (on CRM the tire force comes from the FSI
+solver, `tire_force_source: crm_fsi`). The paper's 15-D HMMWV state is
+`vel_body_x_mps, vel_body_y_mps, roll_rad, pitch_rad, roll_rate_radps, ang_vel_body_y_radps, yaw_rate_radps`
++ `tire_*_force_wheel_fz_n` (4) + `tire_*_spindle_omega_radps` (4); action is the driver triple;
+pose for open-loop rollout scoring is `pos_x_m, pos_y_m, yaw_rad`. Recording starts after a
+settle/warm-up window (`warmup_s` 2.5 s rigid, 0.2 s CRM), so `time_s` does not start at 0.
+
+**Arm (`arm`, 47 columns).** Each row is one 50 Hz control step written as a transition
+`(s, a, s')`: `q_0..3`, `qd_0..3` (joint angle rad / rate rad/s), `qcmd_0..3` (current joint
+command), `act_0..3` (Δq_cmd), `qcmd_next_0..3` (command applied over this step — the paper's
+action), `q_next_0..3`, `qd_next_0..3`, end-effector position in world (`ee_{x,y,z}`,
+`ee_next_*`) and in the vehicle base frame (`ee_base_{x,y,z}`, `ee_next_base_*`), plus
+`collision` (0/1), `collision_kind` (`ground` / `track` / `joint_limit` / empty), `contact_force_n`.
+Episodes start from the home pose with random command increments and terminate on the first
+contact or joint-limit hit, so lengths are 9–500 steps (mean ≈ 58). The paper's 8-D state is
+`[q, qd]` with the end effector recovered by forward kinematics.
+
+**Tracked (`tracked`, 42 columns).** The HMMWV chassis block without `body_slip_rad` and without
+tire channels, plus `left_sprocket_speed_radps`, `right_sprocket_speed_radps`. The paper's 3-D
+state is `vel_body_x_mps, vel_body_y_mps, yaw_rate_radps`; action is the driver triple.
+
+#### `episodes.parquet` and the metadata bundle
+
+`episodes.parquet` flattens each episode's `dataset_index.json` entry and its JSON sidecar
+(nested values are JSON strings): `episode_id`, `split`, `scenario_family`, `rows`,
+`duration_s`, `warmup_s`, `source_shard`, `parquet_file`, and per dataset e.g.
+`height_map_index` / `height_map` / `terminated_out_of_bounds` (bumpy), `terminated_near_boundary`,
+`crm_particles`, `crm_force_summary`, full `driver` profile (CRM), `collision_kind`,
+`collision_links`, `start_q` (arm), `diverged` (tracked), `tire_nominal_radius_m`.
+
+`metadata.tar.gz` is the untouched original metadata: per shard `dataset_index.json` and
+`collector_config.resolved.json` (every materialised scenario: driver profile, seed, family,
+terrain and solver settings), every per-episode sidecar, and the shard-plan manifests. It is what
+lets the release be turned back into the collectors' original directory tree (below).
+
+### Loading
+
+**Streaming with 🤗 `datasets`** (no download of the 44 GB flat set required):
+
+```python
+from datasets import load_dataset
+ds = load_dataset("harryzhang1018/NeDM", "hmmwv_crm", split="val", streaming=True)
+for row in ds.take(3):
+ print(row["episode_id"], row["time_s"], row["vel_body_x_mps"], row["tire_fl_force_wheel_fz_n"])
+episodes = load_dataset("harryzhang1018/NeDM", "hmmwv_bumpy_episodes", split="train")
+```
+
+**Arrow / DuckDB** — one shard at a time, with row-group statistics for pushdown:
+
+```python
+import pyarrow.parquet as pq
+t = pq.read_table("raw/hmmwv_flat/train/shard_017.parquet",
+ columns=["episode_id", "time_s", "vel_body_x_mps", "yaw_rate_radps"],
+ filters=[("scenario_family", "==", "chirp_steer")])
+```
+
+**Reproducing the paper** with the code repository (`conda env create -f environment.nedm.yml`):
+
+```bash
+# training caches -> artifacts/training_datasets/, then any config in configs/ runs verbatim
+PYTHONPATH=src python scripts/release/download_nedm_datasets.py --dataset all --no-raw --processed
+PYTHONPATH=src python scripts/training/train_hmmwv_dynamics.py --config configs/tracked_transformer_v1.json
+
+# raw Parquet -> the collectors' original per-episode CSV tree under artifacts/datasets/,
+# so scripts/preprocess/* and the RL reference builders run unchanged
+PYTHONPATH=src python scripts/release/download_nedm_datasets.py --dataset arm --rehydrate
+```
+
+The rehydrated CSVs carry the float32 values the trainer uses; caches rebuilt from them are
+bit-identical to the ones in `processed/` (this is checked in the release validation).
+
+### Processed caches
+
+| Cache | Trained model | State | Action | Transitions (train / val) | Size |
+|---|---|---|---|---|---|
+| `hmmwv_tire_rigid_300g_normal_force_omega_seq_v1` | terrain-conditioned HMMWV NN-ROM (flat share) | 15-D | 3-D | 128,043,338 / 32,475,755 | 23.1 GB |
+| `hmmwv_crm_2000_normal_force_omega_seq_v1` | terrain-conditioned HMMWV NN-ROM (CRM share) | 15-D | 3-D | 2,280,431 / 602,530 | 0.4 GB |
+| `arm_dyn_v3_8d_seq16_v1` | arm NN-ROM | 8-D `[q, q̇]` | 4-D `q_cmd` | 763,886 / 141,754 | 87 MB |
+| `tracked_drive_v2_seq16_v1` | tracked-base NN-ROM | 3-D `[vx, vy, r]` | 3-D | 1,407,465 / 273,859 | 81 MB |
+
+Each cache holds contiguous `float32` arrays `{train,val}_{states,actions,targets,rollout}.npy`
+(`targets = states[t+1] − states[t]`, `rollout` = pose per recorded row), `episode_starts` /
+`episode_lengths`, `{train,val}_episodes.json` (episode ids and provenance) and `metadata.json`
+(`state_fields`, `action_fields`, `dt_s`, train-split mean/std used for normalisation). Values are
+raw physical units; the model applies the statistics.
+
+### Known limitations
+
+* `hmmwv_bumpy` episodes are short (mean 3.3 k rows) because 78 % end on the 0.9 × 500 m
+ keep-in guard; the regime is meant as a test set.
+* The arm collection is restricted to free-space motion (episodes end at first contact) and
+ under-samples the lower/rear workspace.
+* CRM episodes are 12–18 s long (SPH cost) and use rigid-mesh tires; the CRM tire "force" is the
+ fluid–solid interaction force.
+* Simulation is deterministic and noise-free; there is no sensor model.
+
+### Citation
+
+```bibtex
+@article{zhang2026abstraction,
+ title = {Learning the Right Abstraction: Neural Reduced Dynamics for Complex Robot Control},
+ author = {Zhang, Harry and Negrut, Dan},
+ journal = {Preprint},
+ year = {2026}
+}
+```
+
+License: BSD-3-Clause (same as the code). Simulation assets are Project Chrono's HMMWV and M113
+models; the LRV arm geometry is in the code repository (`src/arm_model/`).
+
+## Part B: traversing study
+
+### What the study is
+
+Follow-on work to the paper, not part of it. A vehicle in [Project Chrono](https://projectchrono.org) has to reach a
+goal across generated hill-and-crater terrain, on rigid ground and on CRM deformable soil. A neural network trained on
+thousands of recorded Chrono drives predicts, for a candidate route and speed profile, where along the route the
+vehicle is likely to fail: roll back on a climb, stall, dig into the soil or tip over. A route search picks the route
+with the lowest predicted risk, and Chrono's stock PID path follower drives it. Separately, a route tracker is trained
+with PPO inside a learned neural reduced dynamics model (NRD) and compared with that PID follower. The milestones, how
+they were measured and what they do not show are documented in
+[`traversing/` of the code repository](https://github.com/uwsbel/NeDM/tree/main/traversing). This part holds what
+reproduces those results: the recorded drives, the exact training files built from them, every trained model behind a
+result-table column, and the evaluation inputs and per-drive records. Every file is a byte-exact copy of the study's
+record, or a deterministic archive of such copies; nothing was re-encoded.
+
+Terms used below:
+
+- **Milestones** (the `milestone` labels of each item):
+ - `m1`: a Chrono depth camera in the planning loop (live multi-waypoint missions, rigid ground);
+ - `m2`: one risk model for rigid ground and soil, not told which one it is on (HMMWV on f104);
+ - `m3`: a learned route tracker against Chrono's PID follower;
+ - `m4a`: the HMMWV planner on arenas it never trained on;
+ - `m4b`: the pipeline on other vehicles (Gator, Polaris; the M113 only in a smoke test).
+- **Arenas.** f104 is the 80 m x 80 m hill-and-crater arena where most training drives were recorded. g203, g217 and
+ g228 are sibling arenas from the same terrain generator: the depth-camera model of m1 trained on all three (g216 and
+ g231 were its held-out arenas), the m4a planners on g203 and g228 (g217 was their development arena). The unseen
+ arenas are eight more made with new seeds and never used in training.
+- **Ground.** Rigid means a rigid heightmap. Soil means Chrono's CRM particle soil: a 0.24 m layer over a rigid floor,
+ one setting throughout.
+- **Groups and route ids.** A start/goal pair is a group. Each group has several routes: designed routes (sideways
+ offsets x speed profiles, ids ending `_route_NN`) and planner-style routes (`_op_NN`), for example
+ `f104_v2_group_0000_route_03`. The soil collections and the other vehicles reuse these ids; the Gator and Polaris
+ drive folders carry a `gator__` or `polaris__` prefix.
+- **Drive.** One Chrono run of one route with the stock PID path follower, after a 0.8 s braked settle, recorded every
+ 50 ms. It stops at the goal (2.5 m radius), on rollover, on leaving the terrain, on prolonged blockage, on soil when a
+ wheel digs through the whole layer, or at the 120 s horizon.
+
+### Layout
+
+```
+traversing/README.md short index: every item with bundle, milestone, packing, files, bytes, restore path
+traversing/release_manifest.json every file (bytes, sha256, item, kind) and every item (bundle, milestone, ...)
+traversing/models/- /... trained networks with their training records
+traversing/evaluation/
- /... evaluation suites, locked route picks, task lists, per-drive records and results
+traversing/processed/
- /... the exact training files the models were fitted on
+traversing/raw/
- /... the recorded Chrono drives the training files were built from
+traversing/assets/
- /... arena heightmaps, the f104 terrain grid, the soil setting and vehicle variants
+```
+
+Each item is packed in one of two ways:
+
+- **`files`.** Every file is uploaded as is, at `traversing/
/- /
`, where `` is its path under
+ the item's source folder. Used for models, single large training files and small sets of evaluation files.
+- **`tar`.** Folders of many small files (mostly drive folders) go into `part-00000.tar.gz`, `part-00001.tar.gz`, ...
+ of about 1 GiB of uncompressed files each; a drive folder never spans two shards. Each member is stored under its
+ restore path relative to the code repository's root, so extracting a shard at the root of a checkout puts it in
+ place. The archives are deterministic (members sorted by path, time stamps 0, owner 0, mode 0644, regular files
+ only, PAX format, gzip level 6 without name or time). Next to the shards:
+ - `index.csv.gz`: one row per member, with columns `path, bytes, sha256, shard`;
+ - `ids.txt.gz`: the list of drive folders, for items selected by such a list;
+ - `episodes.csv.gz`: raw collections only, one row per drive (see below).
+
+`release_manifest.json` is the reference for everything under `traversing/`:
+
+- `source_commit`: the experiment commit the files come from,
+ [`901d6c9`](https://github.com/uwsbel/NeDM/tree/901d6c9423a16c0fafc3d60056065415d5a725f2);
+- `items`: per item its bundle, milestones, description, `needed_for` (`rerun`, `recount` or `retrain`), packing,
+ `restore_root`, member count and bytes, Hub files, parameter counts of its checkpoints (`known_params`), and the other
+ items it needs (`requires`);
+- `files`: per Hub file its bytes, SHA256, item and kind (`file`, `tar_shard`, `index` or `episodes`). Shards also
+ record `tar_bytes` and `tar_sha256` of the uncompressed stream, since the compressed bytes depend on the zlib
+ version;
+- `path_remap`: how paths written inside released task files map to restore paths, and the symbolic links the
+ planners expect (the release holds no links; `ln -s` recreates them from this list).
+
+The code repository keeps a copy pinned to a Hub commit, `traversing/manifests/hf_release_manifest.json`, whose
+`hf_revision` is `6620faead5225ac9aa5ae8ab19bc2ef2db38a863`.
+
+### Items
+
+
+
+**119 items, 732 files, 56.6 GB** (models 30 items, 206 MB; evaluation 33 items, 5.8 GB; processed 28 items, 33.9 GB; raw 25 items, 16.8 GB; assets 3 items, 8.1 MB). The raw collections with an episodes table hold 189,335 drives. Sizes are Hub bytes (compressed for tar shards); `release_manifest.json` has every file's exact size and SHA256. The descriptions are the manifest's: they name the column of the result tables in `traversing/results/` that each model or record stands behind, and the study's own file and model names.
+
+#### Models
+
+| Item | Milestone | What it is | Files | Size |
+|---|---|---|---|---|
+| `m1_nav_direct_depth_risk_ensemble` | m1 | Navigation risk ensemble: 3 seeds (s0-s2) of the direct-depth corridor model (channels range_abs, sec1, speed, valid) that scored every candidate route in all 120 navigation missions (all 4 decision-timing arms). | 4 | 3.1 MB |
+| `m2_joint_station_history_transformer` | m2 | Joint station+history transformer trained on the same rows (deploy_a3_haux_txjoint, 5 seeds s0-s4) behind transformer_1s, transformer_0p5s and transformer_0p5s_grad (soil). | 6 | 8.4 MB |
+| `m2_oracle_world_label_model` | m2 | Shared model given the true world label (T, 5 seeds s0-s4) behind oracle_tag_standing, oracle_tag_3s, oracle_tag_1s, oracle_tag_0p5s. | 6 | 5.3 MB |
+| `m2_pooled_no_label_no_history_model` | m2 | Shared model with neither history nor label (P, 5 seeds s0-s4) behind pooled_3s, pooled_1s, pooled_0p5s. | 6 | 5.3 MB |
+| `m2_rigid_only_planner_standing_start` | m2 | Earlier deployed rigid-only planner (night-2 N2, 5 seeds s0-s4) behind column specialist_rigid_standing (study arm Srigid, sampling arm B) in both m2 tables. | 6 | 5.2 MB |
+| `m2_rigid_specialist_same_rows` | m2 | Single-world rigid model trained on the same re-anchored rows (Sp_rigid, 5 seeds s0-s4) behind specialist_rigid_3s. | 6 | 5.3 MB |
+| `m2_shared_history_early_rows_final_model` | m2 | Model of the FINAL label-free configuration: the history design retrained with extra early-decision and moving-branch rows (deploy_a1_haux_gru, 5 seeds s0-s4). Behind shared_hist_early_rows_1s, shared_hist_early_rows_0p5s (soil and rigid) and shared_hist_early_rows_0p5s_grad (the 780/800 soil and 800/800 rigid headline). | 6 | 6.2 MB |
+| `m2_shared_history_model` | m2 | Shared rigid/soil history model H (CNN-GRU + 2 s history encoder, 5 seeds s0-s4) behind shared_hist_standing, shared_hist_3s, shared_masked_3s (history masked at decision), shared_hist_1s and shared_hist_0p5s. | 6 | 5.5 MB |
+| `m2_soil_only_planner_standing_start` | m2 | Earlier deployed soil-only planner (CRM_N2, 5 seeds s0-s4) behind column specialist_soil_standing (study arm Scrm, sampling arm B) in both m2 tables. | 6 | 5.2 MB |
+| `m2_soil_specialist_same_rows` | m2 | Single-world soil model trained on the same re-anchored rows (Sp_crm, 5 seeds s0-s4) behind specialist_soil_3s and specialist_soil_1s. | 6 | 5.3 MB |
+| `m3_tracker_learned_dynamics_model` | m3 | Tag-conditioned NRD vehicle-dynamics model (causal transformer, 17-D state, 50 ms steps, 8x8 terrain crop) inside which the round-2 PPO policy was trained; not used when driving. | 2 | 19.7 MB |
+| `m3_tracker_round2_numpy_actor` | m3 | Deployed round-2 learned tracker: the PPO actor exported to NumPy (158-D observation, 3 actions), run without torch or the NRD model; behind column nrd_policy_v2 of m3_tracker_routes.csv. | 2 | 2.0 MB |
+| `m3_tracker_round2_ppo_checkpoint` | m3 | Final PPO torch checkpoint (iteration 999) of the round-2 tracker, the source of the NumPy actor. Not needed to re-drive (the actor is enough) and not a training input, but it is the only artefact with which the actor export and parity check can be repeated. | 3 | 5.9 MB |
+| `m4a_rigid_f104_only_ens1` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s0-s4), M1a_rigid_deploy, behind columns f104_only_ens1_fixed2mps and _speedfree (rigid, M1a). The same bytes are aliased as H, the HMMWV-trained rigid model of the Gator study. | 8 | 7.8 MB |
+| `m4a_rigid_f104_only_ens2` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s5-s9), M1b_rigid_deploy, behind columns f104_only_ens2_fixed2mps and _speedfree (rigid, M1b). | 8 | 7.8 MB |
+| `m4a_rigid_three_arenas_all_data` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s0-s4), A3_rigid_deploy, behind columns three_arenas_all_data_fixed2mps and _speedfree (rigid, A3). | 8 | 12.5 MB |
+| `m4a_rigid_three_arenas_same_total_ens1` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s0-s4), M3a_rigid_deploy, behind columns three_arenas_same_total_ens1_fixed2mps and _speedfree (rigid, M3a). | 8 | 8.0 MB |
+| `m4a_rigid_three_arenas_same_total_ens2` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s5-s9), M3b_rigid_deploy, behind columns three_arenas_same_total_ens2_fixed2mps and _speedfree (rigid, M3b). | 8 | 8.0 MB |
+| `m4a_rigid_two_arenas_same_total` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s0-s4), M2_rigid_deploy, behind columns two_arenas_same_total_fixed2mps and _speedfree (rigid, M2). | 8 | 7.9 MB |
+| `m4a_soil_f104_only_ens1` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s0-s4), M1a_soil_deploy, behind column f104_only_ens1 (soil table, study M1a). The same bytes are aliased as H_soil, the Gator study's stage-1 HMMWV soil model. | 8 | 6.3 MB |
+| `m4a_soil_f104_only_ens2` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s5-s9), M1b_soil_deploy, behind column f104_only_ens2 (soil table, study M1b). | 8 | 6.3 MB |
+| `m4a_soil_three_arenas_all_data` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s0-s4), A3_soil_deploy, behind column three_arenas_all_data (soil, A3). | 8 | 7.1 MB |
+| `m4a_soil_three_arenas_same_total_ens1` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s0-s4), M3a_soil_deploy, behind column three_arenas_same_total_ens1 (soil, M3a). | 8 | 6.3 MB |
+| `m4a_soil_three_arenas_same_total_ens2` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s5-s9), M3b_soil_deploy, behind column three_arenas_same_total_ens2 (soil, M3b). | 8 | 6.3 MB |
+| `m4a_soil_two_arenas_same_total` | m4a | CNN-GRU route-risk ensemble, 5 seeds (s0-s4), M2_soil_deploy, behind column two_arenas_same_total (soil, M2). | 8 | 6.3 MB |
+| `m4b_gator_rigid_own_model` | m4b | Gator-trained rigid ensemble on the Gator's 24,000 f104 rigid drives (CNN-GRU, 5 seeds s0-s4, G_rigid_deploy). Behind the README bar-table Gator rigid row (800/800 on f104; arms G_free at free speed and the G_fixed2 addendum); not a compact-table column. | 8 | 7.6 MB |
+| `m4b_gator_soil_own_model_full_data` | m4b | Gator-trained soil ensemble on all 15,235 Gator f104 soil drives (CNN-GRU, 5 seeds s0-s4, G_full_soil_deploy), behind gator_own_model_sampling (Gfull_free_gator) and gator_own_model_sampling_grad (Gfull_grad_gator). | 8 | 6.8 MB |
+| `m4b_gator_soil_own_model_tiers0to6` | m4b | Gator-trained soil ensemble on only the first 7 routes of each group (8,399 drives; CNN-GRU, 5 seeds s0-s4, G_soil_deploy), behind gator_own_model_tiers0to6_sampling (G_free_gator). | 8 | 6.2 MB |
+| `m4b_hmmwv_soil_model_full_data` | m4b | HMMWV-trained soil ensemble on the full HMMWV f104 soil file, the same ids as the Gator (CNN-GRU, 5 seeds s0-s4, H_full_soil_deploy). Behind gator_hmmwv_model_sampling (Hfull_free_gator), hmmwv_own_model_sampling (Hfull_free) and hmmwv_own_model_sampling_grad (Hfull_grad_hmmwv). | 8 | 6.9 MB |
+| `m4b_polaris_soil_own_model_full_data` | m4b | Final Polaris soil ensemble on all 15,229 valid Polaris f104 soil drives (CNN-GRU, 5 seeds s0-s4, polaris_full_soil_deploy). Behind polaris_own_model_sampling_grad and polaris_own_model_sampling on f104 and on the 8 unseen arenas; polaris_corrected_driveline_grad_routes re-drives the polaris_grad routes. | 7 | 5.4 MB |
+
+#### Evaluation
+
+| Item | Milestone | What it is | Files | Size |
+|---|---|---|---|---|
+| `nav_corrected_mission_outcomes` | m1 | Corrected navigation read-out after the rescue-route fix: summary.json and the 120 per-mission outcome files (30 missions x 4 decision-timing arms) behind m1_navigation_missions.csv. | 121 | 377 kB |
+| `nav_corrected_run_folders` | m1 | Per-mission decisions, candidate routes and trajectory of the 120 corrected navigation drives. | 3 | 33.8 MB |
+| `nav_missions_and_task_list` | m1 | The 30 frozen waypoint missions and the 120-row task list (mission x decision-timing arm). | 31 | 67.1 kB |
+| `f104_eval_suite_800` | m2, m4a, m4b | The frozen 800-pair f104 start/goal suite: suite definition, lock file, 800 case files, the designed route of each group and the locked standing-start task lists. | 2 | 5.7 MB |
+| `planner_map_f104` | m2, m4a, m4b | Whole-arena overhead depth map of f104 on which every f104 planner scores its candidate routes. | 2 | 4.1 MB |
+| `shared_model_decision_states` | m2 | Inputs of the moving-start decisions: straight approach routes, the approach drives, and the recorded decision poses and 2 s history arrays at 3 s, 1 s and 0.5 s, with the approach task files. | 2 | 53.5 MB |
+| `shared_model_drive_folders_rigid` | m2 | Per-drive folders behind every cell of m2_shared_risk_rigid.csv (9,469 distinct drives for 9,600 cells). | 3 | 435 MB |
+| `shared_model_drive_folders_soil` | m2 | Per-drive folders behind every cell of m2_shared_risk_soil.csv (18,027 distinct drives for 18,400 cells). | 4 | 903 MB |
+| `shared_model_drive_task_lists` | m2 | Task lists that drove the milestone-2 table arms (standing start, 3 s, 1 s, 0.5 s and final), with the two standing-start lock files; those two locks cover unreleased route copies and cannot be checked from the release. | 14 | 25.8 MB |
+| `shared_model_results_early_and_final` | m2 | Per-pair results of the 1 s and 0.5 s early-decision arms and of the final gradient-refined configuration on soil and rigid ground. | 4 | 16.7 MB |
+| `shared_model_results_standing_and_3s` | m2 | Per-pair results of the standing-start arms and the 3 s-approach arms, soil and rigid. | 4 | 10.6 MB |
+| `shared_model_route_picks_3s` | m2 | Locked planner output of the 3 s-approach arms. | 2 | 45.8 MB |
+| `shared_model_route_picks_early` | m2 | Locked planner output of the 1 s and 0.5 s early-decision arms (sampling search only), including the rigid 0.5 s arm. | 2 | 52.7 MB |
+| `shared_model_route_picks_final` | m2 | Locked planner output of the final gradient-refined arms after the 0.5 s approach (soil and rigid). | 2 | 38.3 MB |
+| `shared_model_route_picks_standing` | m2 | Locked planner output of the standing-start arms: per-pair pick records with candidate scores, route files, task list, run summary and lock file. | 2 | 47.6 MB |
+| `f104_reference_routes_and_cases` | m3, m4b | f104 start/goal case files and reference routes that released drive tasks point at: the 423 routes and 55 cases the tracker drives follow, and the 147 routes (88 designed, 59 on-policy) and 27 cases of the vehicle smoke test: the 144 sample-A routes (86 designed, 58 planner proposals) plus the 3 routes of the bit-identity check. | 2 | 1.4 MB |
+| `tracker_drive_folders` | m3 | Drive folders of the 2,538 tracker table rows (native PID, held PID and learned tracker on 423 routes, both grounds). | 3 | 141 MB |
+| `tracker_results_suite_tasks` | m3 | Per-route tracker results (both grounds), the 423-route tracking suite with strata, and the task lists that drove the PID and learned-tracker arms. | 7 | 6.2 MB |
+| `planner_maps_new_arenas` | m4a, m4b | Overhead depth maps of the 11 other planner arenas (g203, g217, g228 and the 8 unseen test arenas) and the map checks. | 23 | 45.2 MB |
+| `unseen_and_vehicle_picks_lock_files` | m4a, m4b | Top-level pick lock files and job lists of the unseen-arena, Gator and Polaris evaluations. | 23 | 567 kB |
+| `unseen_arena_drive_folders_rigid` | m4a | Drive folders behind the 37,100 cells of m4_unseen_arenas_hmmwv_rigid.csv (36,653 distinct drives). | 5 | 1.9 GB |
+| `unseen_arena_drive_folders_soil` | m4a, m4b | Drive folders behind the 9,000 non-empty cells of m4_unseen_arenas_hmmwv_soil.csv (8,746 distinct drives). | 3 | 411 MB |
+| `unseen_arena_drive_task_lists` | m4a, m4b | Task lists that drove the HMMWV soil and rigid unseen-arena evaluations (including the Gator rigid f104 drives). | 18 | 31.4 MB |
+| `unseen_arena_eval_indexes` | m4a, m4b | Per-drive evaluation indexes of the unseen-arena study (soil and rigid; the rigid index also holds the Gator rigid f104 rows) and the task-to-arm mapping files. | 11 | 80.5 MB |
+| `unseen_arena_route_picks` | m4a, m4b | Locked planner picks of every HMMWV arm of the two unseen-arena tables, on the 8 unseen arenas, f104, the held-out and dev arenas (236 arm x arena folders). | 3 | 228 MB |
+| `unseen_arena_suites` | m4a, m4b | Frozen start/goal suites of the 8 unseen test arenas, held-out g203/g228 and dev g217: case files, designed routes, per-suite lock files, manifests, the f104 in-distribution list, the declared soil subset and the spread-headroom group list. | 2 | 43.7 MB |
+| `gator_rigid_f104_drive_folders` | m4b | Drive folders of the Gator rigid f104 read-out in the README bar table: the Gator-trained planner (800/800) and the straight route at 6 m/s. | 3 | 68.7 MB |
+| `polaris_unseen_drive_folders` | m4b | Drive folders behind the 3,000 cells of m4_polaris_unseen_soil.csv (2,618 distinct drives). | 3 | 183 MB |
+| `vehicle_drive_task_lists` | m4b | Task lists of the Gator/HMMWV all-data drives, Polaris on f104, the gradient-refined Gator/HMMWV drives, Polaris on the unseen arenas and the smoke test. | 16 | 6.6 MB |
+| `vehicle_eval_indexes_and_smoke_extract` | m4b | Per-drive indexes of the Gator all-data comparison, Polaris on f104 and Polaris on the unseen arenas, their task-mapping files, the per-route smoke and collection extract, and the definition of smoke sample A. | 11 | 54.0 MB |
+| `vehicle_f104_drive_folders` | m4b | Drive folders behind the 9,600 cells of m4_vehicles_f104_soil.csv (9,243 distinct drives; Gator, HMMWV and Polaris variants). | 3 | 702 MB |
+| `vehicle_route_picks` | m4b | Locked picks of the vehicle arms: Gator own models, HMMWV-trained model, gradient refinements, Polaris on f104 and on the 8 unseen arenas, and the Gator rigid planner. | 3 | 86.2 MB |
+| `vehicle_smoke_test_drives` | m4b | Complete drive folders of the vehicle smoke test on sample A (144 f104 soil routes) for the 7 variants with their own folders (three Polaris driveline/wheel variants, stock and re-geared M113, Gator at 1 ms and 0.5 ms steps), plus the failure record of the one crashed drive. The polaris_stock and hmmwv_stored columns of m4_vehicle_smoke.csv come from drives released in the raw collections polaris_f104_soil_collection_runs and hmmwv_soil_f104_collection (not required: about 3.7 GB). | 3 | 148 MB |
+
+#### Processed training files
+
+| Item | Milestone | What it is | Files | Size |
+|---|---|---|---|---|
+| `nav_depth_corridors_arena_g203` | m1 | Navigation corridors on sibling training arena g203. 4,925 rows. | 1 | 366 MB |
+| `nav_depth_corridors_arena_g216_heldout` | m1 | Navigation corridors on held-out arena g216 (read by the trainer for its held-out route-choice score, not fitted). 4,956 rows. | 1 | 368 MB |
+| `nav_depth_corridors_arena_g217` | m1 | Navigation corridors on sibling training arena g217. 5,008 rows. | 1 | 372 MB |
+| `nav_depth_corridors_arena_g228` | m1 | Navigation corridors on sibling training arena g228. 4,937 rows. | 1 | 367 MB |
+| `nav_depth_corridors_arena_g231_heldout` | m1 | Navigation corridors on held-out arena g231 (read by the trainer for its held-out score, not fitted). 4,889 rows. | 1 | 363 MB |
+| `nav_depth_corridors_f104_extra_drives` | m1 | Navigation corridors from f104 gen_v1 / sensor_v1 test drives (fitted; f104 is a training arena). 3,111 rows. | 1 | 231 MB |
+| `nav_depth_corridors_f104_training_routes` | m1 | Direct-depth route-corridor tensors for the navigation risk ensemble (matched_Dabs, 3 seeds): all 36,199 f104 rigid training routes (labels reused from the merged station set via R/sensor_v1/labels_station_ds_all.npz, corridors re-sampled from the back-projected depth grid). 36,199 rows. | 1 | 2.7 GB |
+| `rigid_specialist_training_rows` | m2 | Training rows of the earlier rigid-only f104 planner N2 (column specialist_rigid_standing, arm Srigid): merged night-1 + night-2 rigid route set, 36,199 routes / 2,700 groups (train 33,840, val 764, test 1,595; 31,851 fitted per N2_meta.json). | 1 | 1.1 GB |
+| `shared_model_baseline_reanchored_rows` | m2 | Re-anchored rigid + soil rows with a 2 s history on the f104 route ids: 115,868 rows (105,193 fitted). Training file of the generalist ensembles H, P, T, Sp_crm, Sp_rigid (columns oracle_tag_*, shared_hist_standing/3s/1s/0p5s, pooled_*, shared_masked_3s, specialist_soil_3s/1s, specialist_rigid_3s). | 1 | 2.1 GB |
+| `shared_model_final_anchor_k60_rows` | m2 | Final shared-model training file 3 of 3: decision rows at frame 60 (3 s), the k=60 slice of anchor_k40_60_80.npz (14,972 rigid + 14,727 soil). 29,699 rows, 26,936 fitted. | 1 | 541 MB |
+| `shared_model_final_reanchored_plus_branch_rows` | m2 | Final shared-model training file 1 of 3: mixed_reanchor rows plus 4,614 moving-prefix branch rows of both worlds. 120,482 rows, 109,244 fitted. | 1 | 2.2 GB |
+| `shared_model_final_short_anchor_rows` | m2 | Final shared-model training file 2 of 3: early decision rows at frames 10/20/30 of every rigid and soil f104 episode. 89,998 rows, 81,634 fitted. | 1 | 1.6 GB |
+| `soil_specialist_training_rows` | m2 | Training rows of the earlier soil-only f104 planner CRM_N2 (column specialist_soil_standing, arm Scrm): one row per validated HMMWV soil route (15,235); 13,821 fitted per CRM_N2_deploy.json. | 1 | 471 MB |
+| `tracker_dynamics_training_cache` | m3 | Per-episode 50 ms state/action/pose/power cache of 43,235 f104 episodes (rigid 26,500 = 24,000 production + 1,500 perturbed + 1,000 round-1 policy harvest; soil 16,735 = 15,235 collection + 1,500 perturbed) plus cache_manifest.json and build_report.json. | 3 | 2.0 GB |
+| `tracker_group_split_file` | m3 | Night-2 soil twin dataset whose group/split arrays define the 1,200-group split (1,089/56/55) used by the cache builder and cross-checked by the NRD trainer. | 1 | 169 MB |
+| `terrain_rigid_subset_f104_only` | m4a | HMMWV rigid, f104 only, 1,089 groups. 93,397 rows, 84,787 fitted. Trained M1a and M1b (columns f104_only_ens1/ens2 _fixed2mps/_speedfree); byte-identical to H_f104_hmmwv_rigid.npz (Gator-study H). | 1 | 1.7 GB |
+| `terrain_rigid_subset_three_arenas_all` | m4a | HMMWV rigid, all data: f104 1,089 + g203 1,083 + g228 1,063 groups. 278,735 rows, 250,490 fitted. Trained A3 (column three_arenas_all_data). | 1 | 5.0 GB |
+| `terrain_rigid_subset_three_arenas_same_total` | m4a | HMMWV rigid, f104 + g203 + g228, same total. 112,726 rows, 84,481 fitted. Trained M3a and M3b (columns three_arenas_same_total_ens1/ens2). | 1 | 2.0 GB |
+| `terrain_rigid_subset_two_arenas` | m4a | HMMWV rigid, f104 + g203, same total. 101,916 rows, 84,310 fitted. Trained M2 (column two_arenas_same_total). | 1 | 1.8 GB |
+| `terrain_soil_subset_f104_only` | m4a | HMMWV soil, f104 only, 1,089 training groups, tiers 0-6. 32,152 rows, 29,210 fitted. Trained M1a_soil and M1b_soil (columns f104_only_ens1/ens2, soil) and is byte-identical to H_f104_hmmwv_soil.npz (Gator-study H_soil). | 1 | 583 MB |
+| `terrain_soil_subset_three_arenas_all` | m4a | HMMWV soil, all data: f104 1,089 + g203 559 + g228 520 groups. 64,400 rows, 57,898 fitted. Trained A3_soil (column three_arenas_all_data). | 1 | 1.2 GB |
+| `terrain_soil_subset_three_arenas_same_total` | m4a | HMMWV soil, f104 + g203 + g228, 363 groups each. 35,573 rows, 29,071 fitted. Trained M3a_soil and M3b_soil (columns three_arenas_same_total_ens1/ens2). | 1 | 644 MB |
+| `terrain_soil_subset_two_arenas` | m4a | HMMWV soil, f104 + g203, 545 groups each. 33,227 rows, 29,048 fitted. Trained M2_soil (column two_arenas_same_total). | 1 | 603 MB |
+| `gator_rigid_subset_all` | m4b | Gator rigid on f104, all 24,000 route ids. 93,551 rows, 84,922 fitted. Trained G, the Gator rigid planner cited in the README bar table (800/800). | 1 | 1.7 GB |
+| `gator_soil_subset_all` | m4b | Gator soil on f104, all 15,235 validated ids (tiers 0-12). 55,826 rows, 50,822 fitted. Trained G_full_soil (columns gator_own_model_sampling, gator_own_model_sampling_grad). | 1 | 1.0 GB |
+| `gator_soil_subset_tiers0to6` | m4b | Gator soil on f104, tiers 0-6 (8,399 drives). 30,827 rows, 28,057 fitted. Trained G_soil (column gator_own_model_tiers0to6_sampling). | 1 | 557 MB |
+| `hmmwv_soil_subset_gator_matched_all` | m4b | HMMWV soil on f104, exactly the route ids the Gator validated (all tiers). 58,268 rows, 52,923 fitted. Trained H_full_soil (columns gator_hmmwv_model_sampling, hmmwv_own_model_sampling, hmmwv_own_model_sampling_grad). | 1 | 1.1 GB |
+| `polaris_soil_subset_all` | m4b | Polaris soil on f104, all 15,229 valid ids (tiers 0-12). 57,228 rows, 52,021 fitted. Trained polaris_full_soil (all Polaris planner columns on f104 and the unseen arenas). | 2 | 1.0 GB |
+
+#### Raw collections
+
+| Item | Milestone | What it is | Files | Size |
+|---|---|---|---|---|
+| `hmmwv_rigid_f104_early_waves` | m1, m2 | Seven small early HMMWV rigid f104 waves whose drives are in the navigation model's 36,199-route f104 label file: prospective_v1 309, fixed_speed_v1 292, speed_c4 206, wide_v1 146, speed_c6 90, band_v1 73, showcase_v1 14. The last six make up the 821 rows the label file tags as MPPI arms. | 4 | 84.9 MB |
+| `hmmwv_rigid_f104_first_overnight_collection` | m1, m2 | Earlier HMMWV rigid f104 production collection (1,500 groups, the first overnight wave). It is not part of the 24,000-route pool. It supplies 11,412 of the navigation model's 36,199 f104 routes and part of the rigid N2 specialist's training rows. | 4 | 681 MB |
+| `hmmwv_rigid_f104_pool_designed` | m1, m2, m3, m4a | HMMWV rigid-ground pool on f104, designed routes: 1,200 start/goal groups x 12 routes. This is the first half of the 24,000-route rigid pool. Every later rigid f104 model and the tracker cache were built from this pool, and the Gator and Polaris re-drove its route ids. | 4 | 853 MB |
+| `hmmwv_rigid_f104_pool_onpolicy` | m1, m2, m3, m4a | HMMWV rigid-ground pool on f104, planner-style (on-policy) routes: 1,200 groups x 8 routes. This is the second half of the 24,000-route rigid pool. | 5 | 1.1 GB |
+| `hmmwv_rigid_multi_arena_test_drives` | m1 | HMMWV rigid test drives on f104, g203, g217 and g228 from the multi-arena study (planner, rule-based, fixed-speed and straight-route arms; 1,103 / 1,098 / 1,132 / 1,111). The navigation trainer (sensor_train_v2.py) fits every row from a training arena whatever its source, so these are training rows. | 4 | 250 MB |
+| `hmmwv_rigid_sensor_study_test_drives` | m1 | HMMWV rigid drives from the sensor study's two test campaigns (sensor_v1/test 3,614 and test2 4,523) on the training arenas f104, g203, g217 and g228. They enter the navigation training rows through ds_v2_gen_<arena>.npz. | 4 | 408 MB |
+| `hmmwv_rigid_sibling_arenas_designed_routes` | m1 | HMMWV rigid designed-route drives on the navigation model's three sibling training arenas g203, g217 and g228 (1,800 each, 5,400 total). The g216 and g231 drives in the same folder are held-out evaluation only and are excluded. | 4 | 330 MB |
+| `hmmwv_rigid_f104_branch_anchor_records` | m2 | Per-anchor records of the HMMWV rigid f104 branch drives (<episode>\_\_a4, 800 anchor states): the automatic branch choice (branch_auto.json, 789) or the skip record (skipped.json, 11) and the completion marker. The drives themselves are hmmwv_rigid_f104_branch_continuations. | 3 | 519 kB |
+| `hmmwv_rigid_f104_branch_continuations` | m2 | HMMWV rigid drives that branch from a moving state on f104: 2,367 continuation drives (<anchor>\_\_a4\_\_c<j>; 2,358 produce rows, 9 were skipped) from 800 anchor states. The per-anchor records are hmmwv_rigid_f104_branch_anchor_records. | 4 | 251 MB |
+| `hmmwv_soil_f104_branch_continuations` | m2 | HMMWV soil drives that branch from a moving state on f104: 752 anchor states x 3 = 2,256 continuation drives (<episode>\_\_c<j>). | 4 | 246 MB |
+| `hmmwv_soil_f104_collection` | m2, m3, m4a, m4b | HMMWV soil collection on f104 (Chrono's particle-based deformable soil, 0.24 m deep over a rigid floor): 15,235 validated route ids in 1,200 groups, tiers 0-12 (9,168 designed + 6,067 planner-style). The Gator and Polaris later re-drove the same ids. | 5 | 1.4 GB |
+| `hmmwv_rigid_tracker_held_control_drives` | m3 | HMMWV rigid drives with perturbed controls on f104 training routes: controls held for a true 50 ms with brake taps added (1,500 drives, <route>\_\_b3). | 4 | 100 MB |
+| `hmmwv_rigid_tracker_policy_harvest` | m3 | HMMWV rigid drives by the round-1 learned tracker on 1,000 training routes (<route>\_\_harvest). They were added to the dynamics cache. | 4 | 68.9 MB |
+| `hmmwv_soil_tracker_held_control_drives` | m3 | HMMWV soil drives with the same held-control perturbations on f104 training routes (1,500 drives, <route>\_\_b3). | 4 | 130 MB |
+| `arena_gator_collection_task_files` | m4a, m4b | Task files passed to the collection builds of the arena and vehicle studies: the Gator rigid pool (rigid_v2), the Gator soil builds (soil_v3 for tiers 0-12, soil_v2 for tiers 0-6, which also defines the HMMWV g203/g228 soil tiers) and the HMMWV g203/g228 rigid pools (rigid_hmmwv_v1). | 4 | 103 MB |
+| `hmmwv_rigid_g203_pool` | m4a | HMMWV rigid 24,000-route pool on the extra training arena g203 (1,200 groups x 20 routes; 14,400 route_ ids + 9,600 op_ ids). ag_build_ds.py selected all 24,000 (92,225 rows). | 6 | 2.0 GB |
+| `hmmwv_rigid_g228_pool` | m4a | HMMWV rigid 24,000-route pool on the extra training arena g228 (93,113 rows). | 6 | 2.0 GB |
+| `hmmwv_soil_g203_tiers0to6` | m4a | HMMWV soil drives on g203, tiers 0-6 (the first 7 routes of each of 606 start/goal groups): 4,242 driven, of which 4,240 pass QA (2 rejected as crm_qa:unstalled_break). | 4 | 385 MB |
+| `hmmwv_soil_g228_tiers0to6` | m4a | HMMWV soil drives on g228, tiers 0-6: 4,242 driven, all validated. | 4 | 377 MB |
+| `gator_collection_qa_records` | m4b | Recorded QA of the Gator collections and the validated-id lists passed to the subset builder: soil all tiers, soil tiers 0-6 and rigid. | 8 | 9.1 MB |
+| `gator_f104_rigid_collection_runs` | m4b | The Gator driving the 24,000-route rigid f104 pool (1,200 groups x 20: 14,400 designed routes and 9,600 planner-style routes), 165.7 simulated hours. Chain: ci_f104_gator_rigid.npz (93,551 rows), then subset G_f104_gator_rigid.npz, then the G_rigid ensemble (e5/deploy/G). | 6 | 2.0 GB |
+| `gator_f104_soil_collection_runs` | m4b | The Gator driving the 15,235 HMMWV f104 soil route ids (tiers 0-12: 9,168 designed routes and 6,067 planner proposals), 141.1 simulated hours. These are the source of ci_f104_gator_crm.npz (tiers 0-12, 55,826 rows), which feeds the G_full_soil ensemble. They are also the source of the stage-1 file (tiers 0-6, 8,399 runs, 30,827 rows), which feeds the G_soil ensemble. | 6 | 2.3 GB |
+| `polaris_collection_build_record` | m4b | The Polaris stage-2 build record (15,235 candidates, 6 rejected, 15,229 selected) and the validated id list passed to the subset builder. | 2 | 552 kB |
+| `polaris_collection_task_file` | m4b | soil_v5_polaris.json: the task file passed as --tasks-crm to the Polaris stage-2 build. Its tier 0-12 rows are the 15,235 collection ids. | 1 | 15.9 MB |
+| `polaris_f104_soil_collection_runs` | m4b | The Polaris (stock driveline) driving the same 15,235 f104 soil ids: 15,229 valid, 93.0 simulated hours. Chain: stage-2 ci_f104_polaris_crm.npz (tiers 0-12, 57,228 rows), then polaris_full_f104_soil.npz, then the polaris_full_soil ensemble. The 144 sample-A rows of the smoke arm 'polaris' are part of this collection. | 5 | 1.7 GB |
+
+#### Assets
+
+| Item | Milestone | What it is | Files | Size |
+|---|---|---|---|---|
+| `arena_heightmaps` | m1, m2, m3, m4a, m4b | Heightmap and metadata of every arena driven in a milestone: f104 and 17 generated arenas, plus the arena family description. | 37 | 4.8 MB |
+| `crm_soil_config_and_vehicle_variants` | m2, m3, m4a, m4b | The single deformable-soil setting (crm_main.json), the M113 smoke-test soil setting (crm_m113.json) and the Polaris and M113 vehicle definition variants. | 14 | 42.0 kB |
+| `f104_terrain_grid` | m3 | Metric terrain grid of f104 used for the terrain crops of the vehicle-dynamics model and the tracker training environment. | 1 | 3.3 MB |
+
+
+
+### What one drive folder contains
+
+Raw collections and evaluation drives share one folder layout: one folder per drive, named by its route id, with a
+suffix for drive variants (`__b3` drives with perturbed held controls, `__a4__cN` on rigid ground and `__cN` on soil for
+continuations branching from a moving state, `__harvest` drives by the first learned tracker). Raw collections release only the files the dataset builders
+read:
+
+| File | Present in | Contents |
+|---|---|---|
+| `trajectory.npz` | every drive | the drive, one row per 50 ms interval (below) |
+| `command_reference.npz` | every drive | the route the follower was given and the speed it was asked for (below) |
+| `anchor_state.npz` | every drive | the vehicle at the start of recording, with a short history array (below) |
+| `outcome.json` | every drive | how the drive ended: `status` (for example `goal_reached`, `timeout`, `rollover`, `prolonged_blockage_terminated`, `soil_breakthrough_terminated`), `goal_reached`, `elapsed_s`, goal distances and progress (m), path length (m), positive engine work (kJ), frame count, the follower's settings; on soil a `crm` block (particle counts, sinkage and slip summaries); for the Gator and Polaris a `vehicle` block |
+| `case.json` | every drive | the start/goal task: `id`, `arena` (the arena's asset path), start pose (in `layout`), `goal_xy`, `goal_radius_m`, `horizon_s`, the route parameters of its group (sideways offsets, speeds, speed profiles), and the train/val/test `split` of its group |
+| `episode_complete.json` | every drive | completion marker: elapsed time and the SHA256 of every file the collector wrote, including files not released |
+| `initial_state_validation.json` | when recorded | check of the settled start: horizontal speed, roll, pitch, heading and position error against their limits |
+| `crm_extra.npz` | soil drives | per 50 ms: chassis height `pos_z_m` and heightmap ground under it `bmp_ground_z_m` (m), chassis quaternion `quat` (e0..e3), wheel-centre heights `spindle_z_m` (m), `slip_ratio` and longitudinal soil force `fsi_force_wheel_fx_n` (N) per wheel (`wheel_order` fl, fr, rl, rr), and `tire_radius_m` |
+| `collection_request.json` | soil drives | the collector's inputs: case and route paths with their SHA256, soil settings, seed, stop rules, and the vehicle setup for the Gator and Polaris |
+| `vehicle_extra.npz` | Gator and Polaris | per 50 ms (`frame`): `belly_clearance_min_m`, the lowest of the points sampled on the chassis underside minus the undisturbed ground below it (m, negative = inside the soil or ground), `belly_points_below_surface`, `belly_argmin_point`, chassis vertical speed `chassis_vz_mps`; and those points in the chassis frame, `belly_points_chassis_m` |
+| `native_height_check.json` | Gator rigid drives | Chrono's terrain height against the heightmap at 50 points (m) |
+| `branch_route.json`, `branch_reference.json` | branch continuations | the continuation route from the moving state (waypoints, speeds, stations, headings) |
+| `branch_auto.json`, `skipped.json` | rigid branch anchor records | the automatic branch choice at each anchor state, or why the anchor was skipped |
+
+Evaluation drive folders are released with every recorded file except logs, and hold at least `trajectory.npz`, `outcome.json` and
+`episode_complete.json`, usually `case.json`; navigation missions instead hold `decisions.json`, `routes.json` and
+`trajectory.npz`.
+
+`outcome.json` also has a `safe_goal_reached` flag. It is the collector's own flag (no obstacle contact, no 2 s
+effortful stop, no rollover), not the study's label. The study's label counts rolling back on a climb and is
+recomputed from `trajectory.npz`: see the outcome codes in
+[`traversing/results/README.md`](https://github.com/uwsbel/NeDM/blob/main/traversing/results/README.md).
+
+**`trajectory.npz`.** `T` rows, one per 50 ms interval; row `i` is measured at the start of interval `i` and the
+action is the one applied over it.
+
+| Key | Shape, type | Contents |
+|---|---|---|
+| `state` | (T, 17) float32 | the 17-number vehicle state below |
+| `action` | (T, 3) float32 | applied steering in [-1, 1], throttle in [0, 1], braking in [0, 1] |
+| `pose` | (T, 3) float64 | world x (m), y (m), yaw (rad) |
+| `power_kw` | (T,) float64 | engine output torque times transmission shaft speed (kW) |
+| `positive_work_kj_per_interval` | (T,) float64 | positive engine work in the interval (kJ) |
+| `contact_n` | (T,) float64 | largest contact force with placed obstacles (N); the arenas have none, so it is 0 |
+| `parked` | (T,) bool | the vehicle is at the end of the route and asked to stop |
+| `terminal_state`, `terminal_pose`, `terminal_parked` | (17,), (3,), () | the same quantities after the last interval |
+| `state_fields` | (17,) str | the names of the state columns |
+| `dt_s` | () float32 | 0.05 |
+
+The 17-number state, in this order (`STATE_FIELDS` in `src/nedm/traverse/fdm_data.py`, the preset
+`tire_normal_force_omega_pt` of `src/nedm/training/constants.py`, at the experiment commit
+[`901d6c9`](https://github.com/uwsbel/NeDM/blob/901d6c9423a16c0fafc3d60056065415d5a725f2/src/nedm/training/constants.py)):
+
+| # | Field | Unit |
+|---|---|---|
+| 0-1 | `vel_body_x_mps`, `vel_body_y_mps`: chassis velocity in the body frame (x forward) | m/s |
+| 2-3 | `roll_rad`, `pitch_rad` | rad |
+| 4-6 | `roll_rate_radps`, `ang_vel_body_y_radps` (pitch rate), `yaw_rate_radps` | rad/s |
+| 7-10 | `tire_{fl,fr,rl,rr}_force_wheel_fz_n`: normal force on each wheel | N |
+| 11-14 | `tire_{fl,fr,rl,rr}_spindle_omega_radps`: wheel spin rate | rad/s |
+| 15 | `engine_motor_speed_radps` | rad/s |
+| 16 | `engine_motorshaft_torque_nm` | N m |
+
+**`command_reference.npz`.** `interval_start_s` and `desired_speed_mps` (T,): the time of each interval (s) and the
+speed the follower was asked for (m/s). `reference_waypoints` (N, 2, m), `reference_stations` (N, m along the route),
+`reference_speeds` (N, m/s) and `reference_headings` (N, rad): the route. Rigid branch continuations add `branch_frame` and
+`branch_waypoints`, `branch_stations`, `branch_speeds`, `branch_headings`.
+
+**`anchor_state.npz`.** `state` (17,) and `pose` (3,) at the start of recording, `goal_xy` (2, m), `goal_radius_m`,
+and `history` (16, 24): 16 steps of 50 ms (0.8 s), each with the 17 state numbers, the 3 previously applied
+controls, the position relative to the current pose in its heading frame (x, y in m) and the sine and cosine of the
+relative heading (`HISTORY_FIELDS` in `src/nedm/traverse/fdm_data.py`). At a standing start the history repeats the
+first state with a braking command.
+
+### `episodes.csv.gz`
+
+One row per drive of a raw collection, next to its tar shards at `traversing/raw/- /episodes.csv.gz`:
+
+| Column | Meaning |
+|---|---|
+| `run_id` | drive folder name |
+| `collection` | the collection folder: the folder holding the drive's `runs/` folder, else the drive's parent folder |
+| `vehicle`, `world` | `hmmwv`, `gator` or `polaris`; `rigid` or `soil` (from `outcome.json`, else the item's defaults) |
+| `arena` | the arena asset path from `case.json`, for example `assets/traverse/arena_f104_50h_v1`; the item `arena_heightmaps` restores that folder (heightmap `arena_000.bmp` and `arena_meta.json`) |
+| `status`, `elapsed_s` | end status and recorded time (s) from `outcome.json` |
+| `n_files`, `bytes` | released files of the drive and their total size |
+| `trajectory_sha256`, `outcome_sha256` | SHA256 of the drive's `trajectory.npz` and `outcome.json` |
+| `shard` | the tar shard holding the drive |
+
+These tables have no `load_dataset` configs of their own: the `datasets` library reads every config of a repository
+with one file format, here the paper's Parquet. Load a table with the CSV reader and its Hub path instead:
+
+```python
+from datasets import load_dataset
+eps = load_dataset("csv", split="train", data_files="hf://datasets/harryzhang1018/NeDM@6620faead5225ac9aa5ae8ab19bc2ef2db38a863/"
+ "traversing/raw/hmmwv_soil_f104_collection/episodes.csv.gz")
+```
+
+### Download and restore
+
+The helper in the code repository downloads items at the pinned revision, checks every file against the manifest's
+SHA256, and restores each item to its path in a checkout (for example `artifacts/traverse/crm_f104_v1/collect_v1/runs/`
+for the HMMWV soil collection), which is where the study's scripts expect it. It needs `huggingface_hub`:
+
+```bash
+python traversing/scripts/release/download_traversing_data.py --list --all # items, sizes, restore paths
+python traversing/scripts/release/download_traversing_data.py --milestone m2 --bundle models
+python traversing/scripts/release/download_traversing_data.py --items hmmwv_soil_f104_collection --verify-members
+python traversing/scripts/release/verify_release.py --local artifacts/hf_release/download # re-check downloaded files
+```
+
+The default revision is `6620faead5225ac9aa5ae8ab19bc2ef2db38a863`, the Hub commit pinned in
+`traversing/manifests/hf_release_manifest.json`; `--revision` selects another one (with a warning). Items named in an
+item's `requires` are added to the selection. Existing files with other content are kept unless `--overwrite` is
+given. Without the helper, fetch a folder with
+`huggingface_hub.snapshot_download("harryzhang1018/NeDM", repo_type="dataset", revision="6620faead5225ac9aa5ae8ab19bc2ef2db38a863", allow_patterns="traversing/models/m2_shared_history_model/*")`
+and extract tar shards with `tar -xzf part-00000.tar.gz` at the root of a checkout.
+
+### Loading notes
+
+- **`.npz` files** contain object arrays in places: load them with `numpy.load(path, allow_pickle=True)`.
+- **Models** are PyTorch checkpoints: a dict holding a state dict (under `state` for the risk networks, `model` for the
+ NRD, `model_state_dict` for the PPO checkpoint) plus the architecture settings. Load with
+ `torch.load(path, map_location="cpu", weights_only=True)`, allowing the NumPy arrays and paths some of them store
+ (`load_checkpoint` in `traversing/scripts/release/verify_release.py` shows how). The JSON next to each ensemble is
+ its training record. The network classes are in the experiment code at commit
+ [`901d6c9`](https://github.com/uwsbel/NeDM/tree/901d6c9423a16c0fafc3d60056065415d5a725f2) and are not on main yet.
+- **The tracker actor** (`m3_tracker_round2_numpy_actor/actor.npz`) is plain NumPy: observation normalisation
+ (`obs_mean`, `obs_var`, `obs_eps`), the layer weights `W0..W3`, `b0..b3` of a 158 -> 512 -> 256 -> 128 -> 3
+ network, and the action scaling (`action_center`, `action_scale`, `action_low`, `action_high`). It runs without
+ torch.
+- **Units** are in the key names (`_m`, `_mps`, `_rad`, `_radps`, `_n`, `_nm`, `_kw`, `_kj`, `_s`).
+
+### Known limitations
+
+- **Simulation only.** Every drive is a Chrono simulation; there is no real-vehicle data.
+- **Whole-arena overhead camera.** Every planner map comes from a fixed overhead camera that sees the whole arena,
+ with ideal depth, and the planners use the simulator's exact vehicle pose.
+- **One soil setting and one terrain generator.** All soil drives use the same 0.24 m particle layer, and only the
+ wheels touch the soil: the HMMWV's rigid tyre mesh, and plain cylinders for the Gator and Polaris calibrated to the
+ HMMWV's sinkage. All arenas come from one hill-and-crater generator.
+- **The Polaris's engine values are not physical.** Chrono's stock Polaris driveline gives the wheels about 16 times
+ the engine's power, so in Polaris drives the engine speed and torque (state numbers 15 and 16), `power_kw` and the
+ work values do not describe a real engine.
+- **Vehicle-specific models.** Each risk model was trained on one vehicle's drives and is meant for that vehicle; the
+ labels describe drives by Chrono's stock PID follower. The predicted failure probabilities rank routes but are not
+ calibrated.
+- **Re-drives are not always bit-identical.** Chrono runs on the cluster repeat exactly on one node but not across
+ nodes. Re-driving the PID follower on soil reproduced 369 of 423 trajectories exactly and 419 of 423 end states.
+
+### License and citation
+
+BSD-3-Clause, the same as Part A and the code. The traversing study has no publication yet: please cite the NeDM paper
+(Part A) and name the dataset revision you used (`6620faead5225ac9aa5ae8ab19bc2ef2db38a863`).
+
+## Part C: contact NRD
+
+### What it is
+
+Follow-on work to the paper, not part of it. A neural reduced dynamics model (NRD) for systems whose contacts start
+and stop: a bouncing ball, two pool balls, an SO101 arm that pushes a T-shaped block, and a Unitree G1 humanoid that a
+frozen walking policy (HOMIE) drives. A core network, a collision network and a contact network predict each 20 ms
+step, with one design for all four cases; the first three cases share one training config, and G1 has its own. The
+design, the results and the commands are in
+[`contact_nrd/` of the code repository](https://github.com/uwsbel/NeDM/tree/main/contact_nrd). The training files,
+the SO101 and G1 test files and the models are byte-exact copies of the study's files. The ball and pool test files are
+new conversions of the study's raw test recordings, made with the same converter as the training files. The ball, pool
+and SO101 data come from [Project Chrono](https://projectchrono.org) simulations, the G1 data from MuJoCo 3.15.0.
+
+### Layout
+
+| Path | Contents |
+|---|---|
+| `contact_nrd/
/train/` | `system.json` and `unified_data.npz`: training (split 0) and validation (split 1) episodes, plus the source campaign's own test episodes (split 2, not used) |
+| `contact_nrd//test/` | The same two files for test episodes (split 2) from a separate collection with a new seed. No test episode was used for training or checkpoint selection |
+| `contact_nrd//models/seed61.pt`, `seed62.pt` | The trained models (PyTorch checkpoints) |
+| `contact_nrd/g1_locomotion/{train,test}/manifest.json` | G1 only: the collection record (settings, seeds, package versions, model-file hashes) |
+| `contact_nrd/g1_locomotion/models/seed61_training/`, `seed62_training/` | G1 only: the training record of each model (`run_config.json` with the SHA-256 of the code and the data, `complete.json`, `train_log.jsonl`, `validation.json`) |
+| `contact_nrd/g1_locomotion/results/` | G1 only: the test output of both models (`sealed_test_seed61_seed62.json`, `.out`) |
+| `contact_nrd/release_manifest.json` | Size and SHA-256 of every file; source folders, campaigns, seeds and episode counts |
+
+`` is `bouncing_ball` (5,400 / 900 training / validation episodes, 1,800 test), `pool` (19,200 / 2,400,
+4,800 test), `so101_push_t` (51,200 / 6,400, 1,000 test) or `g1_locomotion` (30,685 / 3,413, 3,608 test). The first
+three cases total 9.8 GB, G1 21.4 GB.
+
+### What the files contain
+
+- `system.json`: the bodies (kind, size, fixed planes or table), the contact pairs, the record step, the target
+ body and time; for the arm and the T, the channel names and types.
+- `unified_data.npz` (uncompressed NumPy): `contacts` [N, T-1, P] (pair p touches during record interval k),
+ `lengths` [N], `splits` [N], and the states. Ball and pool: `states` [N, T, D, 9] = position, velocity, angular
+ velocity of each ball. SO101 push-T: `arm` [N, T, 10] (joint angles, joint speeds), `tshape` [N, T, 13]
+ (position, quaternion wxyz, velocity, angular velocity) and `action` [N, T, 5] (joint position command). Other
+ arrays (`launches`; for the SO101 `contacts_link`, `t_table`, `scenario`) give more detail on each shot or push;
+ the models do not use them. Units are SI. Ball and pool records are 1 ms apart, the SO101 records 10 ms. In the
+ ball and pool `system.json`, `model_step_s` is 0.01 s; the released models use 0.02 s (from the training config).
+- G1 `unified_data.npz`: `robot` [N, T, 67] (pelvis position, quaternion wxyz, 27 joint angles, pelvis velocity,
+ pelvis angular velocity, 27 joint rates), `action` [N, T, 27] (joint position targets), `contacts` [N, T-1, 2]
+ (left foot and right foot on the ground), `family` [N] (index into the `families` of `system.json`), `episode_id`,
+ `lengths`, `splits`. Other arrays (per record: `command`, `policy_output`, `contact_force`, `contact_steps`,
+ `torque`, `limit_steps`, `limit_joints`; per episode: `seed`, `group_id`, `terminal_reason` and the settings of the
+ difficult and probe families) give more detail; the models do not use them. Records are 10 ms apart. The G1
+ `system.json` also gives the families and the `evaluation` block of checkpoint selection. The G1 data come from
+ running the HOMIE walking policy (OpenHomie, commit `33071f79`) in MuJoCo. HOMIE itself is not in this dataset: it is
+ fetched from its pinned upstream commit, under its own license.
+
+### Download and use
+
+```bash
+PYTHONPATH=src python -m nedm.contact_nrd.download --case pool # in the code repository; checks every SHA-256
+PYTHONPATH=src python -m nedm.contact_nrd.download --case g1_locomotion --part models results # G1 without the data
+```
+
+The code repository's `contact_nrd/release_manifest.json` pins the Hub revision (the G1 case has its own revision in
+`case_revisions`). The files cannot be loaded with `datasets.load_dataset`; read them with NumPy or with
+`nedm.contact_nrd.data.load_data`.
+
+### Known limitations
+
+- **Simulation only.** There is no real-robot or real-table data.
+- **One scene per case.** One ball, wall and floor; one pool table with fixed ball start positions; one arm, T and
+ table; one G1 robot with one walking policy on a flat floor. The test episodes are new shots, pushes and walks from
+ the same ranges as the training data.
+- **Open-loop scores.** The published errors are model rollouts against recorded episodes, with the recorded arm
+ commands (G1: rollouts from recorded 4-state histories with the recorded joint targets).
+- **Test sets seen during design.** The study also scored earlier design versions on these test episodes.
+
+### License and citation
+
+BSD-3-Clause, the same as Part A and the code. The contact NRD has no publication yet: please cite the NeDM paper
+(Part A) and name the dataset revision you used (`d68fa3c4d91539bc6a079f4b2f3ff5c27d825101`; the G1 case:
+`cba82611210e401dc0155cb78fcf456a385ecef4`).
+
+## Part D: G1 footstep policy
+
+### What it is
+
+Follow-on work to the paper, not part of it. A footstep policy for the Unitree G1 humanoid. Every 20 ms it sets the
+velocity command (forward speed, sideways speed, turn rate) of a frozen walking policy (HOMIE), so that the feet land
+on given footprints, on a flat floor and on planks with gaps. PPO trained it only inside the G1 contact NRD of Part C
+(`contact_nrd/g1_locomotion/models/seed61.pt`, `seed62.pt`); MuJoCo 3.15.0 checked it on new courses. The training,
+the results and the commands are in
+[`g1_footstep_rl/` of the code repository](https://github.com/uwsbel/NeDM/tree/main/g1_footstep_rl). The policies,
+their run files and the RL inputs are byte-exact copies of the study's files.
+
+### Layout
+
+| Path | Contents |
+|---|---|
+| `g1_footstep_rl/policy/fs_cmd_s1/`, `fs_cmd_s2/` | Two PPO policies (`policy.pt`) and their run files: configs, curriculum, input hashes, stage ends, validation history, learning curve |
+| `g1_footstep_rl/rl_inputs/start_bank/` | 200,000 start states from the G1 training data (`bank_v1.npz`), its summary and the joint ranges of the training data |
+| `g1_footstep_rl/rl_inputs/courses/` | 200,000 training and 1,280 validation footstep courses, and their report |
+| `g1_footstep_rl/results/dev/` | MuJoCo evaluations on the development courses (5 course types, 64 courses each): both policies, with the same episodes also inside the NRD, and the baseline H-FS (HOMIE with a hand-written footstep controller); the NRD-against-MuJoCo summary; package versions |
+| `g1_footstep_rl/results/hfs_tuning/` | The parameter search of the baseline |
+| `g1_footstep_rl/videos/` | Three side-by-side MuJoCo videos (policy above, baseline below) and their record (command, policy SHA-256, outcomes) |
+| `g1_footstep_rl/release_manifest.json` | Size and SHA-256 of every file; provenance |
+
+Total 975 MB.
+
+### What the files contain
+
+- `policy.pt`: an RSL-RL 2.2.4 checkpoint (`model_state_dict`: actor and critic MLPs 512-256-128 on 163 inputs, 3
+ outputs, and the action std). The run files next to it give the environment and PPO settings.
+- `course_bank_v4_{train,val}.npz` (float32, course frame): `targets` [M, 40, 5] (x, y, yaw, foot side, stop flag),
+ `centre` [M, 40, 3] (course line), `n` (footprints in use), `level`, `seed`, plank `intervals` [M, 16, 2] and
+ `half_width`, the stop and cliff flags.
+- `bank_v1.npz`: `hist` [N, 4, 67] (the NRD's state history), `teacher_history` [N, 6, 76] (HOMIE's input history),
+ `family`, `kind` (stand, walk, turn, ...) and the source episode and step of each start.
+- Each evaluation folder: `rows.json` (one row per course: outcome, completion, falls, drift), `steps.json` (one row
+ per footprint: error, along and across), `summary.json` and `SUMMARY.md` (cell rates with 95 % intervals, paired
+ McNemar tests against the baseline); the policy folders also `nrd_rows.json`, `nrd_steps.json` (the same courses
+ inside the NRD) and `snapshots.npz` (the MuJoCo states that start them).
+
+### Download and use
+
+```bash
+scripts/g1_footstep_rl/reproduce.sh full --steps download --with-results # in the code repository; checks every SHA-256
+```
+
+The code repository's `g1_footstep_rl/release_manifest.json` pins the Hub revision. `reproduce.sh` also trains the
+policies again and runs the MuJoCo evaluation. HOMIE is not in this dataset: the code repository fetches it from its
+pinned upstream commit (OpenHomie, commit `33071f79`), which has its own license.
+
+### Known limitations
+
+- **Simulation only.** There is no real-robot data.
+- **One robot and one walking policy.** Flat floor and flat plank tops at the floor height, straight plank courses,
+ standing starts.
+- **Development results only.** The results are on development courses, which also guided choices during the study.
+ The study's final-test courses were not run.
+- **Machine-dependent episodes.** MuJoCo episodes repeat bitwise only with the same CPU type and package versions
+ (`results/dev/environment.json`).
+
+### License and citation
+
+BSD-3-Clause, the same as Part A and the code. HOMIE is not hosted here; it is fetched from its pinned upstream commit,
+under its own license. The G1 footstep policy has no publication yet: please cite the NeDM paper (Part A) and name the
+dataset revision you used (`cba82611210e401dc0155cb78fcf456a385ecef4`).
+
+## Part E: SO101 pick and place
+
+### What it is
+
+Follow-on work to the paper, not part of it. A camera policy (the "student") for a real SO101 arm picks a 30 mm cube
+and places it on a plate. Every training step ran inside a contact NRD of the arm and the cube (the design of Part C,
+trained on CPU MuJoCo 3.15.0 episodes): a state teacher trained with PPO in the NRD, then the student trained in the
+NRD with ray-traced images of a calibrated copy of the real scene (online DAgger). No real image was a training
+sample. On the real arm the student placed the cube in 36 of 50 stress-test episodes (72 %; 95 % interval 58–83 %).
+The training, the results and the commands are in
+[`so101_pick_place/` of the code repository](https://github.com/uwsbel/NeDM/tree/main/so101_pick_place).
+
+### Layout
+
+| Path | Contents |
+|---|---|
+| `so101_pick_place/nrd/c1_s62/`, `nrd/c0_s62/` | The policy NRD (every teacher and student stage ran in it) and its base: `best.pt` loads with `nedm.contact_nrd.model.load_model`; `original/best.pt` is the file as trained (two training-only heads more); the training records |
+| `so101_pick_place/nrd_data/` | The 4 NRD training data parts (93,494 episodes; `unified_data.npz`, `system.json`, `manifest.json`), and the 7 PPO policies behind `policy_v3` |
+| `so101_pick_place/nrd_test/` | The sealed scripted test set (3,050 episodes) |
+| `so101_pick_place/teacher/`, `student/` | Every teacher (T0-T6) and student (S0-S5) checkpoint of the chain with its run record; the teacher's expert data |
+| `so101_pick_place/rl_inputs/` | Task sets, start banks, geometry, the task sets of the sim checks |
+| `so101_pick_place/results/` | The sealed NRD test, the sim-check results and selection rules, the per-episode robot results |
+| `so101_pick_place/robot/` | Raw logs of 19 robot sessions (102 policy episodes), 52 videos of the student's input images, 2 LeRobot teleop recordings |
+| `so101_pick_place/bundle/` | The folder installed on the robot computer, and its tarball |
+| `so101_pick_place/scene_calib/`, `provenance/` | Camera calibration, scene and servo fit (also in the code repository); code snapshots that are in no commit |
+| `so101_pick_place/release_manifest.json` | Size and SHA-256 of every file; provenance (commits, runs, sources) |
+
+Total 13.3 GB (NRD data 10.6 GB).
+
+### What the files contain
+
+- NRD data (`unified_data.npz`, uncompressed): `arm` [N, 601, 12] (6 joint angles, 6 joint rates), `cube` [N, 601,
+ 13] (position, quaternion wxyz, velocity, angular velocity), `action` [N, 601, 6] (joint position targets),
+ `contacts` [N, 600, 3] (fixed jaw - cube, moving jaw - cube, cube - table), `lengths`, `splits` (0 train,
+ 1 validation, 2 test), `family`, `phase`, contact force, impulse and depth, ids, seeds and outcome fields. Records
+ are 10 ms apart, episodes 4 s.
+- Checkpoints: PyTorch files. Teachers: MLP state policies with privileged inputs. Students: two ResNet18 image
+ encoders (external camera crop and wrist camera, 224 x 224 RGB), joint angles and rates, a chunk of 10 joint
+ targets as output.
+- Robot logs: per session `session.json` (command line, typed outcome per episode) and `first_frames.npz`; per
+ episode `episode_live.json` (setup, guard, latency, outcome) and `episode_live.npz` (50 Hz joints and commands,
+ each policy query with its action chunk and the two input images at 112 px).
+
+### Download and use
+
+```bash
+scripts/so101_pick_place/reproduce.sh full --steps download # in the code repository; checks every SHA-256
+```
+
+The code repository's `so101_pick_place/release_manifest.json` pins the Hub revision; `--with-nrd-data` and
+`--with-robot` add the large folders. The MuJoCo Menagerie SO101 model is not in this dataset: the code repository
+fetches it at a pinned revision.
+
+### Known limitations
+
+- **One robot, one lab, one cube and plate.** The outcome is typed by the operator; the stress protocol was not fixed
+ in advance, and the student was chosen with robot results.
+- **The NRD test set has only scripted families** and is not fully blind (run once before on an older NRD design).
+- **Lab content.** The robot logs hold lab background images, the robot computer's user path and the USB adapter
+ serial. The videos show the student's input images as logged on the robot (112 px; the student sees 224 px);
+ there is no full-resolution video.
+
+### License and citation
+
+BSD-3-Clause, the same as Part A and the code. The MuJoCo Menagerie model is not hosted here. The SO101 pick and place
+has no publication yet: please cite the NeDM paper (Part A) and name the dataset revision you used (the
+`hf_revision` of `so101_pick_place/release_manifest.json` in the code repository).
diff --git a/so101_pick_place/code/requirements-so101-pick-place.txt b/so101_pick_place/code/requirements-so101-pick-place.txt
new file mode 100644
index 0000000000000000000000000000000000000000..09d4acac56323d48e57a616bb63625e370494efd
--- /dev/null
+++ b/so101_pick_place/code/requirements-so101-pick-place.txt
@@ -0,0 +1,33 @@
+# Extra Python packages of the SO101 pick-and-place release (so101_pick_place/README.md). Not part of the paper's
+# environment: requirements.txt and environment*.yml are unchanged, and this study does not use them.
+#
+# 1. Workstation: training, sim checks, bundle build, fake-robot replay (one GPU; scripts/so101_pick_place/reproduce.sh)
+# install the torch / torchvision build for your GPU first (https://pytorch.org), then
+# pip install -r requirements-so101-pick-place.txt
+# Do not add requirements.txt: it pins torch 2.8.0 / torchvision 0.23.0, which this study never ran on. Tested:
+# torch 2.12.0+cu130, torchvision 0.27.1+cu130, Python 3.12.15 (RTX 5090; local runs, smoke runs, the sealed
+# NRD test), torch 2.10.0+rocm7.1, torchvision 0.25.0+rocm (AMD MI350X / MI300X; every training job).
+# AMD GPUs: do NOT install warp-lang from PyPI (that wheel is CUDA only). The renderer ran on AMD's ROCm port of
+# Warp 1.13.0, built from source (scripts/render/hpcfund/build_warp_rocm.sbatch on the branch
+# so101-pick-place-study), with newton installed with --no-deps.
+mujoco==3.15.0 # CPU MuJoCo: the NRD data collector, the scene, the evaluations and sim checks
+scipy==1.18.1 # MuJoCo worlds (rotations), the collector
+warp-lang==1.13.0 # ray-traced camera images of the student (with newton; pinned as a pair)
+newton==1.2.0
+trimesh==5.1.1 # mesh files of the renderer
+huggingface_hub==1.33.0 # download.py (the Hub files)
+pyarrow==26.0.0 # LeRobot recordings (replay), robot logs
+pillow==12.3.0 # images
+opencv-python-headless==4.13.0.92 # the replay of the LeRobot recordings (fake step) and the robot videos
+imageio==2.38.1 # videos (optional)
+imageio-ffmpeg==0.6.0
+# numpy came with torch: 2.5.4 (RTX 5090), 2.4.3 / 2.5.4 (AMD). The robot videos (robot/render_videos.py) also need
+# an ffmpeg with libx264 on the PATH.
+#
+# 2. Robot computer only (Jetson AGX Orin, conda env "lerobot"; README "Deploy"). The steps of section 1 need none of
+# these except opencv; the bundle carries the kin points, so the robot computer needs no mujoco, warp or newton:
+# pip install lerobot==0.6.1 opencv-python pyarrow (with the torch / torchvision of the Jetson)
+# The study's notes record LeRobot 0.6.2 on the Orin: the version string of LeRobot's GitHub main branch after v0.6.1,
+# not a PyPI release (PyPI's latest is 0.6.1, checked 2026-10-27), so the Orin had a source install of LeRobot
+# whose commit was not recorded. PyPI lerobot 0.6.1 ran the replay and the fake robot on the workstation; it was
+# not run on the real arm. A source install of LeRobot's main branch also reports 0.6.2, but its commit will differ.
diff --git a/so101_pick_place/code/scripts/so101_pick_place/check/check_analyze.py b/so101_pick_place/code/scripts/so101_pick_place/check/check_analyze.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4583d95239761c957cf952c2d4d7b02b050ed90
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/check/check_analyze.py
@@ -0,0 +1,231 @@
+"""Release sim check, v12 (CHECK_SPEC.md section 3): per-episode and per-start metrics of check_eval.py runs.
+
+ python -B check_analyze.py TAG=runs/x.npz[:kind] ... --out out/analysis_.json
+kind: H (hold starts, tasks/h68.npz; rows % 68 = start, rows // 68 = draw) or J (jit224; the cube side of each row
+from the task metadata, Addendum B6: the file changes side in blocks of 8, 112 rows cube left L->R, 112 cube right
+R->L). The J task metrics (grasp / lift / place / near place / carry stop) are those of sim_eps.py (this folder;
+the plane = the run's own plane). Ported from the study's ~/so101_r2s_claude/v12/check/lib/check_analyze.py: file
+paths from this repository and its download folder; --h68 names the H68 metadata (was /tasks/h68.json).
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+import numpy as np
+
+HERE = Path(__file__).resolve().parent
+DATA = HERE.parents[2] / "artifacts" / "so101_pick_place"
+DT = 0.02
+LOOSE, LOOSE6 = 10.0, 6.0
+OPEN_CMD = 20.0
+FAR_MM = 40.0
+LIFT_MM = 25.0
+WIN_S = 6.0
+_K = {}
+
+
+def kin():
+ if "k" not in _K:
+ import torch
+ from nedm.so101_policy.kin import SO101Kin
+ k = SO101Kin()
+ _K["k"] = lambda q: tuple(x.numpy() for x in k.fk(torch.as_tensor(q)))
+ return _K["k"]
+
+
+def hold_start(jaw_deg, n=15):
+ ok = (jaw_deg >= 6) & (jaw_deg <= 13)
+ run = np.convolve(ok.astype(int), np.ones(n, int), "valid") >= n
+ h = np.flatnonzero(run)
+ return int(h[0]) if len(h) else None
+
+
+def planned_jaw(chunk, k, n_dec, lo=0.0, hi=1.5):
+ dstep = np.arange(n_dec) * 5 - 1
+ m = (dstep >= k + lo / DT) & (dstep < k + hi / DT)
+ if not m.any():
+ return float("nan")
+ return float(np.degrees(chunk[:n_dec][m, :5, 5].mean(1)).mean())
+
+
+def ep_metrics(q, cube, ex, chunk, n, goal_xy):
+ q, cube = q[:n].astype(np.float64), cube[:n].astype(np.float64)
+ cmd = np.degrees(ex[:, :, 5].reshape(-1)[:n].astype(np.float64))
+ jaw = np.degrees(q[:, 5])
+ P, R = kin()(q)
+ gz = P[:, 2] * 1e3
+ k = hold_start(jaw)
+ if k is None:
+ return dict(hold=False, grasp_release=False, release_robot=False)
+ up = np.flatnonzero(gz[k:] > gz[k] + LIFT_MM)
+ kl = k + int(up[0]) if len(up) else n
+ kw = min(kl, k + int(round(WIN_S / DT)), n)
+ dgoal = np.linalg.norm(cube[:, :2] - np.asarray(goal_xy)[None], axis=1) * 1e3
+ hit = np.flatnonzero((cmd[k:kw] > OPEN_CMD) & (dgoal[k:kw] > FAR_MM))
+ op_r = np.flatnonzero(cmd[k:kl] > OPEN_CMD)
+ nd = int(np.ceil(n / 5))
+ out = dict(hold=True, k=int(k), t_hold=round(k * DT, 2), lift=bool(len(up)),
+ t_lift=round(float(kl - k) * DT, 2) if len(up) else None,
+ plan=planned_jaw(chunk, k, nd), plan_0_1=planned_jaw(chunk, k, nd, 0.0, 1.0),
+ grasp_release=bool(len(hit)), t_grel=round(float(hit[0]) * DT, 2) if len(hit) else None,
+ release_robot=bool(len(op_r)), t_rel_robot=round(float(op_r[0]) * DT, 2) if len(op_r) else None,
+ cmd_max_win=float(cmd[k:kw].max()), jaw_max_win=float(jaw[k:kw].max()),
+ goal_mm_hold=float(dgoal[k]))
+ if len(hit):
+ t = k + int(hit[0])
+ j = min(t + 25, n - 1)
+ out["dropped"] = bool(np.linalg.norm(P[j] - cube[j, :3]) * 1e3 > 25.0)
+ s0, s1 = k + 5, min(k + 55, n)
+ if s1 > s0:
+ loc = np.einsum("nji,nj->ni", R[s0:s1], cube[s0:s1, :3] - P[s0:s1]) * 1e3 # R^T (c - p), mm
+ out["seat_mm"] = np.round(loc.mean(0), 2).tolist()
+ out["gp_above_cube_mm"] = round(float((P[s0:s1, 2] - cube[s0:s1, 2]).mean() * 1e3), 2)
+ out["closed"] = bool(np.median(np.linalg.norm(P[s0:s1] - cube[s0:s1, :3], axis=1)) * 1e3 < 25.0)
+ return out
+
+
+def run_episodes(f):
+ z = np.load(f, allow_pickle=True)
+ sq, sc, ex, ch, L = z["state_q"], z["state_cube"], z["rec_exec"], z["rec_chunk"], z["steps"]
+ goal = z["goal_xy"]
+ rows = []
+ for i in range(sq.shape[0]):
+ n = int(min(L[i], sq.shape[1]))
+ r = ep_metrics(sq[i], sc[i], ex[i], ch[i], n, goal[i])
+ r.update(ep=i, end=int(z["end"][i]), steps=n, lenient=bool(z["lenient"][i]), seed=int(z["seeds"][i]))
+ rows.append(r)
+ info = json.loads(str(z["check"])) if "check" in z else {}
+ return rows, info
+
+
+def per_start(rows, N):
+ out = []
+ for s in range(N):
+ rs = [r for r in rows if r["ep"] % N == s]
+ pl = [r["plan"] for r in rs if r["hold"] and np.isfinite(r["plan"])]
+ out.append(dict(row=s, draws=len(rs), holds=sum(r["hold"] for r in rs),
+ plan=float(np.median(pl)) if pl else None,
+ grasp_release=sum(r["grasp_release"] for r in rs),
+ release_robot=sum(r["release_robot"] for r in rs),
+ seat_mm=(np.round(np.median([r["seat_mm"] for r in rs if "seat_mm" in r], 0), 2).tolist()
+ if any("seat_mm" in r for r in rs) else None),
+ gp_above_cube_mm=(float(np.median([r["gp_above_cube_mm"] for r in rs if "gp_above_cube_mm" in r]))
+ if any("gp_above_cube_mm" in r for r in rs) else None)))
+ return out
+
+
+def counts(starts, rows, sel=None):
+ st = [s for s in starts if sel is None or s["row"] in sel]
+ rs = [r for r in rows if sel is None or r["row"] in sel]
+ pl = np.array([s["plan"] for s in st if s["plan"] is not None])
+ gr_rows = sorted(int(s["row"]) for s in st if s["grasp_release"] > 0) # Addendum B3: distinct starts
+ return dict(starts=len(st), starts_hold=int(len(pl)), loose=int((pl > LOOSE).sum()), loose6=int((pl > LOOSE6).sum()),
+ starts_grasp_release=len(gr_rows), grasp_release_starts=gr_rows,
+ plan_mean=round(float(pl.mean()), 3) if len(pl) else None,
+ plan_p50=round(float(np.median(pl)), 3) if len(pl) else None,
+ episodes=len(rs), ep_hold=sum(r["hold"] for r in rs),
+ grasp_release=sum(r["grasp_release"] for r in rs), release_robot=sum(r["release_robot"] for r in rs),
+ ep_loose=sum(bool(r["hold"] and r["plan"] > LOOSE) for r in rs))
+
+
+J224_TASKS = str(DATA / "rl_inputs/check_tasks/jit224.npz")
+J224_META = str(DATA / "rl_inputs/check_tasks/all280.json") # = sim_eps.META
+
+
+def j224_side_rows():
+ """Addendum B6: the rows of jit224 with the cube left (direction L->R) and right (R->L), from the task metadata
+ (row b -> the file's seed of row b -> its metadata entry). A re-seeded repeat keeps the file's row order."""
+ meta = json.loads(Path(J224_META).read_text())
+ by = {meta["seed0"] + m["row"]: m for m in meta["tasks"]}
+ seeds = np.load(J224_TASKS)["seeds"].astype(int)
+ d = [by[int(x)]["direction"] for x in seeds]
+ left = {b for b, x in enumerate(d) if x == "L->R"}
+ right = {b for b, x in enumerate(d) if x == "R->L"}
+ if len(left) + len(right) != len(seeds):
+ raise SystemExit("jit224: a row with no L->R / R->L direction")
+ return left, right
+
+
+def j_task(f, plane, info):
+ """sim_eps.py task metrics per direction (rows 0-111 L->R, 112-223 R->L); seeds mapped back by row."""
+ from nedm.so101_policy import task as _T # noqa: F401 (this checkout's task module first)
+ sys.path.insert(0, str(HERE))
+ import sim_eps as SE
+ meta = json.loads(SE.META.read_text())
+ z = np.load(f, allow_pickle=True)
+ seeds = z["seeds"].astype(int)
+ rows_meta = [dict(m, seed=meta["seed0"] + m["row"]) for m in meta["tasks"]]
+ by = {m["seed"]: m for m in rows_meta}
+ t224 = np.load(J224_TASKS)["seeds"].astype(int)
+ if not set(seeds) <= set(by): # a re-seeded repeat: map row b -> the file's seed of row b
+ if len(seeds) != len(t224):
+ raise SystemExit(f"{f}: {len(seeds)} rows, not the 224 of jit224")
+ rows_meta = [dict(by[int(t224[b])], seed=int(seeds[b])) for b in range(len(seeds))]
+ eps = SE.episodes(f, plane, rows_meta)
+ out = {}
+ for d, kk in (("L->R", "lr"), ("R->L", "rl")):
+ rs = [x for x in eps if x["direction"] == d]
+ out[kk] = dict(n=len(rs), grasp=sum(x["grasp"] for x in rs), lift=sum(x["lift"] for x in rs),
+ place=sum(x["place"] for x in rs), near_place=sum(x["near_place"] for x in rs),
+ carry_stop=sum(x["carry_stop"] for x in rs), stall=sum(x["stall"] for x in rs),
+ far_stop=sum(any(s["to_goal_mm"] > 30.0 for s in x["stops"]) for x in rs))
+ out["all"] = {k: out["lr"][k] + out["rl"][k] for k in out["lr"]}
+ out["per_episode"] = [dict(ep=x["ep"], grasp=x["grasp"], place=x["place"], carry_stop=x["carry_stop"],
+ near_place=x["near_place"], end=x["end"]) for x in eps]
+ return out
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("runs", nargs="+", help="TAG=file.npz:H|J")
+ p.add_argument("--out", required=True)
+ p.add_argument("--h68", default=str(DATA / "rl_inputs/check_tasks/h68.json"), help="H68 start metadata")
+ a = p.parse_args()
+ out = json.loads(Path(a.out).read_text()) if Path(a.out).exists() else {}
+ h68 = json.loads(Path(a.h68).read_text())["holds"]
+ sets = {"H30": set(range(30)), "H38": set(range(30, len(h68)))}
+ for spec in a.runs:
+ tag, rest = spec.split("=", 1)
+ f, kind = rest.rsplit(":", 1)
+ rows, info = run_episodes(f)
+ r = dict(file=f, kind=kind, info=info)
+ if kind == "H":
+ N = len(h68)
+ for x in rows:
+ x["row"], x["draw"] = x["ep"] % N, x["ep"] // N
+ st = per_start(rows, N)
+ r["starts"] = st
+ r["counts"] = {"H68": counts(st, rows), **{k: counts(st, rows, v) for k, v in sets.items()}}
+ for side in ("L", "R"):
+ sel = {m["row"] for m in h68 if m["side"] == side}
+ r["counts"][f"H68_{side}"] = counts(st, rows, sel)
+ else:
+ N = len(rows)
+ for x in rows:
+ x["row"], x["draw"] = x["ep"], 0
+ st = per_start(rows, N)
+ if N != 224:
+ raise SystemExit(f"{f}: {N} rows, not the 224 of jit224")
+ jl, jr = j224_side_rows() # Addendum B6 (was rows 0-111 / 112-223: wrong)
+ r["counts"] = {"J224": counts(st, rows), "J_L": counts(st, rows, jl), "J_R": counts(st, rows, jr)}
+ plane = info.get("plane")
+ r["task"] = j_task(f, tuple(plane) if plane else None, info)
+ r["episodes"] = rows
+ out[tag] = r
+ c = r["counts"]
+ main_key = "H68" if kind == "H" else "J224"
+ cc = c[main_key]
+ extra = (f" | task L->R g {r['task']['lr']['grasp']} p {r['task']['lr']['place']} stop {r['task']['lr']['carry_stop']}"
+ f" R->L g {r['task']['rl']['grasp']} p {r['task']['rl']['place']} stop {r['task']['rl']['carry_stop']}"
+ if kind == "J" else "")
+ print(f"{tag:26s} {main_key}: holds {cc['starts_hold']}/{cc['starts']} starts, plan mean {cc['plan_mean']} p50 "
+ f"{cc['plan_p50']}, loose {cc['loose']} (>6: {cc['loose6']}), grasp releases {cc['grasp_release']}/"
+ f"{cc['episodes']} (robot rule {cc['release_robot']}){extra}", flush=True)
+ Path(a.out).write_text(json.dumps(out, default=float))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/check/check_eval.py b/so101_pick_place/code/scripts/so101_pick_place/check/check_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..d18459fd0dd68077371d97a2e05d95d71f63e276
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/check/check_eval.py
@@ -0,0 +1,275 @@
+"""Release sim check of a camera student (v12 check, frozen runner check_eval.py sha256 f70011ab, ported): one
+closed-loop CPU MuJoCo evaluation through scripts/so101_policy/vision_viral.py eval, with the recording of the planned
+chunk per decision, the goal plate 3.9 mm thick in the renders and the drop rule at the plate top (plane runs), the
+parts override of the arm (RL = configs/so101_pick_place/parts_override_v2.json, the real-look gripper parts; GR = the
+parts of the scene real_scene_v2.json; own = the student's pinned scene), tasks re-seeded (--seed-base: seed = base +
+row + N j for draw j), the measured table plane (or --plane), the flat robot floor and NEDM_SO101_DYN from the
+environment (run_gates.sh sets the fitted servo model configs/so101_pick_place/dyn_fit_d2q.json).
+
+ NEDM_SO101_DYN="$(cat configs/so101_pick_place/dyn_fit_d2q.json)" PYTHONPATH=src python -B \
+ scripts/so101_pick_place/check/check_eval.py eval --student tb10 --arm own \
+ --tasks artifacts/so101_pick_place/rl_inputs/check_tasks/jit224.npz --horizon 2000 --tag g2_a --out OUT.npz
+
+Ported from the study's frozen runner (~/so101_r2s_claude/v12/check/lib/check_eval.py, sha256 f70011ab...): the
+paths come from this repository (code, configs/so101_pick_place, artifacts/so101_pick_place) instead of the study's
+folders; the "build68" command (it built rows 30-67 of h68.npz from robot logs with study-only scripts) is left out:
+h68.npz is released (rl_inputs/check_tasks/). The eval arguments, the patches of vision_viral.py and the recorded
+arrays are the frozen runner's (checked on one G2 smoke run: same arrays).
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import importlib.util
+import json
+import os
+import subprocess
+import time
+from pathlib import Path
+
+import numpy as np
+
+CODE = Path(__file__).resolve().parents[3] # the repository root
+WT = Path(os.environ.get("CHECK_WT", str(CODE))) # code under test: this checkout (scripts/, src/)
+DATA = CODE / "artifacts" / "so101_pick_place" # the Hub folder after reproduce.sh --steps download
+CONF = CODE / "configs" / "so101_pick_place"
+WB = Path(os.environ.get("CHECK_WB", str(CONF)))
+CALIB = Path(os.environ.get("CHECK_CALIB", str(CONF / "calib_v1.json")))
+JT = Path(os.environ.get("CHECK_JT", str(DATA / "teacher/t4_jt_h110/model_00110.pt"))) # loaded, not used for acting
+PLANE = (-0.00468, -0.03641, 0.01836)
+PLATE = 0.0039031332928005
+STUDENTS = {"D": DATA / "student/s4_v8_roll_s801/it_02000.pt", "tb10": DATA / "student/s5_v12_tb10_s1210/it_01000.pt"}
+SCENE_DIRS = [CONF, WB] + [Path(p) for p in os.environ.get("CHECK_SCENE_DIRS", "").split(":") if p]
+BASE = {"v2": Path(os.environ.get("CHECK_BASE_V2", str(CONF / "real_scene_v2.json")))}
+BASE_SHA = {"v2": "4bce0b8dd6f22b5499b556275bca0bf248d1e96b1cd3babf169b34a8cb539d82"}
+RL_PARTS = {"v2": WB / "parts_override_v2.json"}
+RL_SHA = {"v2": "3840ca99745839ff693dca975f9853720176ab61b3b7d751a42995e0e5366217"}
+REC = dict(on=False, delta=[], q=[], chunk=[], exec=[])
+
+
+def log(s):
+ print(f"[{time.strftime('%H:%M:%S')}] check_eval: {s}", flush=True)
+
+
+def sha(p):
+ return hashlib.sha256(Path(p).read_bytes()).hexdigest()
+
+
+# ---- eval ----------------------------------------------------------------------------------------------------------
+def find_scene(ck):
+ import torch
+ c = torch.load(ck, map_location="cpu", weights_only=False)["cfg"]
+ get = (lambda k: c.get(k, "")) if isinstance(c, dict) else (lambda k: getattr(c, k, ""))
+ want = get("scene_sha256")
+ own = Path(str(get("scene") or "")).expanduser()
+ if str(own) and own.is_file() and sha(own) == want: # the pinned path itself (AMD runs)
+ return own
+ for dd in SCENE_DIRS:
+ if not dd.is_dir():
+ continue
+ for p in sorted(dd.glob("*.json")):
+ try:
+ if sha(p) == want:
+ return p
+ except OSError:
+ continue
+ raise SystemExit(f"no scene file with sha256 {want[:12]} for {ck} in {[str(d) for d in SCENE_DIRS]}")
+
+
+def family(scene):
+ names = [p.get("name", "") for p in json.loads(Path(scene).read_text())["geometry"].get("parts", [])]
+ if any(n.startswith("base_clamp") for n in names):
+ raise SystemExit(f"{scene}: a scene of the study's v4 family (not part of this release)")
+ return "v2"
+
+
+def arm_parts(arm, fam):
+ if arm == "RL":
+ f = RL_PARTS[fam]
+ if sha(f) != RL_SHA[fam]:
+ raise SystemExit(f"{f}: sha256 {sha(f)[:12]} != the frozen {RL_SHA[fam][:12]}")
+ return json.loads(f.read_text()), str(f)
+ if arm == "GR":
+ f = BASE[fam]
+ if sha(f) != BASE_SHA[fam]:
+ raise SystemExit(f"{f}: sha256 {sha(f)[:12]} != the frozen {BASE_SHA[fam][:12]}")
+ return json.loads(f.read_text())["geometry"]["parts"], str(f)
+ raise SystemExit(f"arm {arm}")
+
+
+def look_of(scene, fam, arm):
+ """The look a run renders (Addendum B2): 'grey' (the family's base scene parts), 'real' (the real-look parts of
+ arm RL) or 'other'. Arm 'own' = the parts of the student's pinned scene file, compared with both lists."""
+ if arm in ("RL", "GR"):
+ return "real" if arm == "RL" else "grey"
+ own = json.loads(Path(scene).read_text())["geometry"].get("parts", [])
+ if own == arm_parts("GR", fam)[0]:
+ return "grey"
+ if own == arm_parts("RL", fam)[0]:
+ return "real"
+ return "other"
+
+
+def tile(t, n, base):
+ """The task set n times; seeds = base + row + N j (base 0: the file's own seeds, n must be 1)."""
+ N = len(t["seeds"])
+ if not base and n != 1:
+ raise SystemExit("--draws > 1 needs --seed-base")
+ out = {k: (np.concatenate([v] * n) if (np.ndim(v) and len(v) == N) else v) for k, v in t.items()}
+ if base:
+ out["seeds"] = np.concatenate([np.arange(N, dtype=np.int64) + base + j * N for j in range(n)])
+ return out
+
+
+def cmd_eval(a):
+ import torch
+ torch.set_num_threads(a.threads)
+ from nedm.so101_policy.vision import viral as VI
+ if not str(VI.__file__).startswith(str(WT)):
+ raise SystemExit(f"nedm from {VI.__file__}, not {WT}")
+ plane = None if a.plane == "sim" else (PLANE if a.plane == "measured" else tuple(float(v) for v in a.plane.split(",")))
+ if a.plane_dz:
+ if plane is None:
+ raise SystemExit("--plane-dz needs a plane")
+ plane = (plane[0] + a.plane_dz, plane[1], plane[2])
+ orig_den = VI.denormalise
+
+ def denormalise(st, p):
+ out = orig_den(st, p)
+ if REC["on"]:
+ REC["delta"].append(out.detach().float())
+ return out
+ VI.denormalise = denormalise
+ orig_call = VI.Actor.__call__
+
+ def call(self, ws, goal_pose, k=None):
+ REC["delta"], REC["on"] = [], True
+ try:
+ ex = orig_call(self, ws, goal_pose, k)
+ finally:
+ REC["on"] = False
+ delta = torch.cat(REC["delta"])
+ q = ws.q.to(delta.device, torch.float32).nan_to_num()
+ if self.q_offset is not None:
+ q = q + torch.as_tensor(self.q_offset, dtype=q.dtype, device=q.device)
+ if delta.shape[0] != q.shape[0]:
+ raise RuntimeError(f"chunk record: {delta.shape[0]} deltas for {q.shape[0]} worlds")
+ REC["q"].append(q.cpu())
+ REC["chunk"].append((q[:, None, :] + delta).cpu())
+ REC["exec"].append(ex.float().cpu())
+ return ex
+ VI.Actor.__call__ = call
+ ck = Path(STUDENTS.get(a.student, a.student)).expanduser().resolve()
+ scene = find_scene(ck)
+ fam = family(scene)
+ parts, parts_src = arm_parts(a.arm, fam) if a.arm != "own" else (None, "own scene")
+ look = look_of(scene, fam, a.arm) # Addendum B2: recorded in the run's "check" info
+ info = {}
+ orig_make_views = VI.make_views
+
+ def make_views(cfg, num_worlds, **kw):
+ geo = dict(kw.get("geometry_over") or {})
+ if plane is not None:
+ if "table_plane" not in geo:
+ raise SystemExit("check_eval: the plate patch needs the table plane")
+ geo["plate_thickness"] = PLATE
+ if parts is not None:
+ geo["parts"] = parts
+ kw["geometry_over"] = geo or None
+ views = orig_make_views(cfg, num_worlds, **kw)
+ rs = views.real.real
+ got = [p.get("name") if isinstance(p, dict) else getattr(p, "name", None) for p in rs.parts]
+ if parts is not None and len(got) != len(parts):
+ raise SystemExit(f"check_eval: the parts override did not reach the renderer ({len(got)} vs {len(parts)})")
+ info.update(parts=got, table_plane=list(rs.table_plane) if rs.table_plane is not None else None,
+ plate_mm=float(rs.plate_thickness) * 1e3)
+ log(f"render: arm {a.arm} ({fam}, {parts_src}): {len(got)} parts, table plane {info['table_plane']}, plate "
+ f"{info['plate_mm']:.2f} mm")
+ return views
+ VI.make_views = make_views
+ spec = importlib.util.spec_from_file_location("vision_viral", str(WT / "scripts/so101_policy/vision_viral.py"))
+ VV = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(VV)
+ if plane is not None:
+ orig_get = VV.EnvCache.get
+
+ def get(self, world, B):
+ new = (world, B) not in self.c
+ env = orig_get(self, world, B)
+ if new:
+ if env.task.cfg is not env.tcfg:
+ raise SystemExit("check_eval: the task config is not the env's")
+ env.tcfg.release_z = float(env.tcfg.release_z) + PLATE
+ log(f"rules: release_z -> {env.tcfg.release_z * 1e3:.1f} mm above the physics table (plate top)")
+ return env
+ VV.EnvCache.get = get
+ orig_eval = VV.evaluate
+
+ def evaluate(*p, **kw):
+ r = orig_eval(*p, **kw)
+ r["rec_q"] = torch.stack(REC["q"], 1).numpy().astype(np.float32)
+ r["rec_chunk"] = torch.stack(REC["chunk"], 1).numpy().astype(np.float32)
+ r["rec_exec"] = torch.stack(REC["exec"], 1).numpy().astype(np.float32)
+ head = subprocess.run(["git", "-C", str(WT), "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
+ if not head and (WT / "SYNC_HEAD.txt").exists():
+ head = (WT / "SYNC_HEAD.txt").read_text().strip()
+ r["check"] = np.array(json.dumps(dict(
+ tag=a.tag, student=a.student, ckpt=str(ck), ckpt_sha256=sha(ck), scene=str(scene), scene_sha256=sha(scene),
+ family=fam, arm=a.arm, look=look, parts_src=parts_src, parts=info.get("parts"), tasks=str(a.tasks),
+ tasks_sha256=sha(a.tasks), draws=a.draws, seed_base=a.seed_base, n_base=n_base, plane=plane,
+ floor=a.floor, horizon=a.horizon, hold_cap_s=a.hold_cap_s, roll_hi_deg=a.roll_hi_deg,
+ dyn=os.environ.get("NEDM_SO101_DYN", "")[:40] and json.loads(os.environ["NEDM_SO101_DYN"]).get("note"),
+ wt=str(WT), wt_head=head, check_eval_sha256=sha(__file__))))
+ return r
+ VV.evaluate = evaluate
+ t = dict(np.load(a.tasks, allow_pickle=True))
+ n_base = len(t["seeds"])
+ t = tile(t, a.draws, a.seed_base)
+ out = Path(a.out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ tf = out.parent / f"_tasks_{a.tag}.npz"
+ np.savez(tf, **t)
+ nw = len(t["seeds"])
+ args = ["eval", "--student", str(ck), "--scene-path", str(scene), "--calib-path", str(CALIB),
+ "--render-worlds", str(nw), "--jt", str(JT), "--tasks", str(tf), "--world", "mujoco",
+ "--workers", str(a.workers), "--record-states", "--horizon", str(a.horizon), "--hold-cap-s", str(a.hold_cap_s),
+ "--qd-robot", "3", "--floor", a.floor, "--seed", "0", "--out", str(out)]
+ if plane is not None:
+ args.insert(-2, f"--table-plane={plane[0]},{plane[1]},{plane[2]}")
+ if a.roll_hi_deg is not None:
+ args += ["--roll-hi-deg", str(a.roll_hi_deg)]
+ args += [x for x in os.environ.get("CHECK_EVAL_EXTRA", "").split() if x] # AMD: --nrd-ckpt, --mj-python
+ log(f"eval {a.tag}: student {ck}, scene {scene} ({fam}), arm {a.arm} (look {look}), {nw} worlds ({a.draws} draws, seed base "
+ f"{a.seed_base}), plane {plane}, dyn {'on' if os.environ.get('NEDM_SO101_DYN') else 'OFF'}")
+ try:
+ VV.main(args)
+ finally:
+ tf.unlink(missing_ok=True)
+
+
+def main():
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = p.add_subparsers(dest="cmd", required=True)
+ q = sub.add_parser("eval")
+ q.add_argument("--student", required=True, help="a STUDENTS name or a checkpoint path")
+ q.add_argument("--tag", required=True)
+ q.add_argument("--arm", choices=("RL", "GR", "own"), required=True)
+ q.add_argument("--tasks", required=True)
+ q.add_argument("--draws", type=int, default=1)
+ q.add_argument("--seed-base", type=int, default=0, help="seed = base + row + N j (0: the file's seeds, 1 draw)")
+ q.add_argument("--plane", default="measured", help="measured | sim | c0,c1,c2")
+ q.add_argument("--plane-dz", type=float, default=0.0, help="m added to the plane's height term")
+ q.add_argument("--floor", default="zero")
+ q.add_argument("--horizon", type=int, default=400)
+ q.add_argument("--hold-cap-s", type=float, default=40.0)
+ q.add_argument("--roll-hi-deg", type=float, default=None)
+ q.add_argument("--workers", type=int, default=6)
+ q.add_argument("--threads", type=int, default=6)
+ q.add_argument("--out", required=True, help="output .npz")
+ q.set_defaults(fn=cmd_eval)
+ a = p.parse_args()
+ a.fn(a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/check/gates_summary.py b/so101_pick_place/code/scripts/so101_pick_place/check/gates_summary.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5c749057f1270b3a8676eb515c75cb4af372335
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/check/gates_summary.py
@@ -0,0 +1,277 @@
+"""Gate summary for one checkpoint against D on the same platform (SELECTION_v12.md section 2, Addenda A and B).
+
+ python -B gates_summary.py --platform local --name [--ref D] --out --root DIR [--ref-root DIR]
+Runs: /runs/gates///.npz (run_gates.sh names). D's reference: /runs/gates/
+/[/ (default: the same root) with the "ref" runs (G2 repeats g2_b / g2_c, H68 block b).
+Ported from the study's ~/so101_r2s_claude/v12/check/lib/gates_summary.py: --root is required (no default check
+folder) and --validation names the check's validation result (was ]/out/validation.json).
+
+Addendum B:
+- B2: G1, G2, G3 run in the student's own pinned look (check_eval.py arm "own"). The look each run recorded is checked
+ against the arm of the name (visR / visRtbpl: the real-look parts; every other arm and D: the grey parts). D's
+ reference runs are arm GR (= D's own look; own == GR bit-identical on D, 2026-10-27). A mismatch is an error (the
+ checkpoint is then undecided). visR / visRtbpl also run g2_a_GR (grey-look G2): reported only.
+- B1: G2 tolerance A1 = max(2.5 SD sqrt(4/3), 4); G3 = max(2.5 SD sqrt(2), 4) (one D run per plane).
+- B3: the release veto from g4_h68_RL_a (block 613,000) and g4_h68_RL_b (block 613,300): grasp releases at >= 2
+ distinct starts in each block. ctrl's veto is computed and reported (rank_selection.py exempts it).
+- B6: every G2 / G3 result also gives the robot place rule (near_place: the jaw opens with the cube within 30 mm of
+ the plate centre, or a sim place) next to the sim lenient place, per direction (lr = cube left L->R, rl = cube
+ right R->L, from the task metadata).
+- G4 (a)-(d) are reported only (B3 replaces their use; A3: the check is not usable as a gate).
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+import numpy as np
+
+HERE = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import check_analyze as CA # noqa: E402
+import sel_rules as SR # noqa: E402
+
+_CACHE = {}
+G1_RUNS = ("g1_dev100", "g1_homedev100")
+G23_RUNS = ("g2_a", "g3_m3", "g3_p3")
+METRICS = ("grasp", "place", "carry_stop")
+DIRS = ("lr", "rl")
+
+
+def run(root, plat, name, r, kind):
+ f = Path(root) / f"runs/gates/{plat}/{name}/{r}.npz"
+ key = str(f)
+ if key in _CACHE:
+ return _CACHE[key]
+ if not f.exists():
+ _CACHE[key] = None
+ return None
+ rows, info = CA.run_episodes(str(f))
+ out = dict(file=str(f), info=info)
+ if kind == "G1":
+ out["n"], out["lenient"] = len(rows), sum(x["lenient"] for x in rows)
+ elif kind == "J":
+ for x in rows:
+ x["row"], x["draw"] = x["ep"], 0
+ st = CA.per_start(rows, len(rows))
+ out["counts"] = CA.counts(st, rows)
+ pl = info.get("plane")
+ t = CA.j_task(str(f), tuple(pl) if pl else None, info)
+ out["task"] = {k: v for k, v in t.items() if k != "per_episode"}
+ out["per_episode"] = t["per_episode"]
+ else:
+ N = 68
+ for x in rows:
+ x["row"], x["draw"] = x["ep"] % N, x["ep"] // N
+ st = CA.per_start(rows, N)
+ out["counts"] = CA.counts(st, rows)
+ out["plans"] = [s["plan"] for s in st]
+ _CACHE[key] = out
+ return out
+
+
+def contrast(rl, gr):
+ a = np.array([np.nan if v is None else v for v in rl["plans"]])
+ b = np.array([np.nan if v is None else v for v in gr["plans"]])
+ ok = np.isfinite(a) & np.isfinite(b)
+ return float((a[ok] - b[ok]).mean()), int(ok.sum())
+
+
+def collect(root, plat, name, is_ref, grey_g2):
+ """-> (runs dict, required run names, report-only run names)."""
+ req = list(G1_RUNS) + list(G23_RUNS) + ["g4_h68_RL_a", "g4_h68_RL_b"] + (["g2_b", "g2_c"] if is_ref else [])
+ rep = ["g4_h68_GR_a", "g4_j224_RL"] + (["g4_h68_GR_b"] if is_ref else []) + (["g2_a_GR"] if grey_g2 else [])
+ kind = {r: ("G1" if r.startswith("g1_") else "H" if "h68" in r else "J") for r in req + rep}
+ return {r: run(root, plat, name, r, kind[r]) for r in req + rep}, req, rep
+
+
+def run_look(info):
+ """The look a run rendered: the recorded 'look' (check_eval.py since Addendum B), else from the arm (GR / RL)."""
+ return info.get("look") or {"GR": "grey", "RL": "real"}.get(info.get("arm"))
+
+
+def look_errors(R, arm, is_ref):
+ """B2 checks: G1-G3 runs in the student's own look (candidates: arm 'own'); g2_a_GR in the grey look."""
+ exp = SR.own_look(arm) if arm else ("grey" if is_ref else None)
+ errs = []
+ for r in G1_RUNS + G23_RUNS + (("g2_b", "g2_c") if is_ref else ()):
+ x = R.get(r)
+ if not x:
+ continue
+ lk, am = run_look(x["info"]), x["info"].get("arm")
+ if exp and lk != exp:
+ errs.append(f"{r}: look {lk} (arm {am}), not the own look {exp} of arm {arm or 'D'} (B2)")
+ if not is_ref and am != "own":
+ errs.append(f"{r}: arm {am}, not 'own' (B2: G1-G3 in the student's own pinned look)")
+ if R.get("g2_a_GR") and run_look(R["g2_a_GR"]["info"]) != "grey":
+ errs.append(f"g2_a_GR: look {run_look(R['g2_a_GR']['info'])}, not grey")
+ for r in ("g4_h68_RL_a", "g4_h68_RL_b", "g4_j224_RL"):
+ if R.get(r) and run_look(R[r]["info"]) != "real":
+ errs.append(f"{r}: look {run_look(R[r]['info'])}, not the real look (arm RL)")
+ for r in ("g4_h68_RL_a", "g4_h68_RL_b"):
+ sb = {"g4_h68_RL_a": 613000, "g4_h68_RL_b": 613300}[r]
+ if R.get(r) and (R[r]["info"].get("seed_base"), R[r]["info"].get("draws")) != (sb, 4):
+ errs.append(f"{r}: seed base {R[r]['info'].get('seed_base')} / draws {R[r]['info'].get('draws')}, "
+ f"not {sb} / 4 (B3)")
+ return errs
+
+
+def by_direction(task):
+ """B6: per direction the sim lenient place next to the robot place rule (near_place)."""
+ return {d: dict(n=task[d]["n"], grasp=task[d]["grasp"], place_sim=task[d]["place"],
+ place_robot_rule=task[d]["near_place"], carry_stop=task[d]["carry_stop"]) for d in DIRS}
+
+
+def by_direction_mean(tasks):
+ return {d: {k: round(float(np.mean([by_direction(t)[d][k] for t in tasks])), 2)
+ for k in ("n", "grasp", "place_sim", "place_robot_rule", "carry_stop")} for d in DIRS}
+
+
+def judge(xr, ref_vals, tol, ref_dirs):
+ out = {}
+ for m in METRICS:
+ c = xr["task"]["all"][m]
+ ok = (c <= ref_vals[m] + tol[m]) if m == "carry_stop" else (c >= ref_vals[m] - tol[m])
+ out[m] = dict(cand=c, D=round(ref_vals[m], 2), tol=round(tol[m], 3), pass_=bool(ok))
+ out["pass"] = all(out[m]["pass_"] for m in METRICS)
+ out["place_robot_rule_all"] = dict(cand=xr["task"]["all"]["near_place"])
+ out["by_direction"] = by_direction(xr["task"])
+ out["D_by_direction"] = ref_dirs
+ return out
+
+
+def summarize(plat, name, ref="D", root=HERE, ref_root=HERE, validation=None):
+ is_ref = name == ref
+ arm = SR.arm_of(name)
+ run_name, it = SR.parse_ckpt(name)
+ D, dreq, _ = collect(ref_root, plat, ref, True, False)
+ X, xreq, xrep = (D, dreq, []) if is_ref and Path(root) == Path(ref_root) else \
+ collect(root, plat, name, is_ref, arm in SR.REAL_LOOK_ARMS)
+ miss = [f"{ref}:{k}" for k in dreq if D[k] is None] + ([] if is_ref else [f"{name}:{k}" for k in xreq if X[k] is None])
+ miss_rep = [f"{name}:{k}" for k in xrep if X[k] is None]
+ res = dict(platform=plat, name=name, ref=ref, arm=arm, run=run_name, it=it,
+ seed=SR.parse_run(run_name)[1] if run_name else None,
+ own_look=SR.own_look(arm) if arm else ("grey" if is_ref else None),
+ missing=miss, missing_report_only=miss_rep, errors=[])
+ if arm is None and not is_ref:
+ res["errors"].append(f"{name}: not a v12 candidate name (v12__s_it<1000|1500>)")
+ res["errors"] += look_errors(X, arm, is_ref) + ([] if is_ref else [f"D reference: {e}" for e in look_errors(D, None, True)])
+ shas = sorted({v["info"].get("ckpt_sha256") for v in X.values() if v and v["info"].get("ckpt_sha256")})
+ ckpts = sorted({v["info"].get("ckpt") for v in X.values() if v and v["info"].get("ckpt")})
+ if len(shas) > 1:
+ res["errors"].append(f"the runs of {name} used {len(shas)} different checkpoints {[s[:12] for s in shas]}")
+ res["ckpt"], res["ckpt_sha256"] = (ckpts[0] if len(ckpts) == 1 else ckpts), (shas[0] if len(shas) == 1 else shas)
+ val = Path(validation) if validation else None
+ res["check_usable_as_gate"] = json.loads(val.read_text()).get("verdict", {}).get("usable_as_gate") \
+ if val and val.exists() else None
+ G = {}
+ # G1
+ if all(X[r] and D[r] for r in G1_RUNS):
+ def pc(R):
+ return 100.0 * sum(R[r]["lenient"] for r in G1_RUNS) / sum(R[r]["n"] for r in G1_RUNS)
+ G["G1"] = dict(cand=round(pc(X), 2), D=round(pc(D), 2), line=round(pc(D) - 3.0, 2),
+ cand_sets=[X[r]["lenient"] for r in G1_RUNS], D_sets=[D[r]["lenient"] for r in G1_RUNS])
+ G["G1"]["pass"] = G["G1"]["cand"] >= G["G1"]["line"] - 1e-9
+ # G2 / G3 (tolerances from D's three G2 runs on this platform; A1 and B1)
+ if all(D[r] for r in ("g2_a", "g2_b", "g2_c")):
+ tol2, tol3, dmean, tol_range, sd1 = {}, {}, {}, {}, {}
+ for m in METRICS:
+ v = [D[r]["task"]["all"][m] for r in ("g2_a", "g2_b", "g2_c")]
+ tol_range[m] = max(1.5 * (max(v) - min(v)), 4.0) # the first rule (22:12), replaced by A1
+ M = np.array([[e[m] for e in D[r]["per_episode"]] for r in ("g2_a", "g2_b", "g2_c")], float)
+ sd1[m] = float(np.sqrt(M.var(0, ddof=1).sum())) # SD of one run's total (per-episode variances)
+ tol2[m], tol3[m] = SR.tol_g2(sd1[m]), SR.tol_g3(sd1[m])
+ dmean[m] = float(np.mean(v))
+ res["tolerance"] = dict(G2=dict(rule="A1: max(2.5 x SD x sqrt(1 + 1/3), 4) (one run vs the mean of D's 3)",
+ tol=tol2),
+ G3=dict(rule="B1: max(2.5 x SD x sqrt(2), 4) (one run vs ONE D run per plane)", tol=tol3),
+ sd_one_run=sd1, tol_first_rule_range=tol_range,
+ D_runs={m: [D[r]["task"]["all"][m] for r in ("g2_a", "g2_b", "g2_c")] for m in METRICS},
+ D_mean=dmean)
+ d2dirs = by_direction_mean([D[r]["task"] for r in ("g2_a", "g2_b", "g2_c")])
+ if X["g2_a"]:
+ G["G2"] = judge(X["g2_a"], dmean, tol2, d2dirs)
+ G["G2"]["look"] = run_look(X["g2_a"]["info"])
+ if X.get("g2_a_GR"): # B2: grey-look G2 of visR / visRtbpl, report only
+ G["G2_grey_report"] = judge(X["g2_a_GR"], dmean, tol2, d2dirs)
+ G["G2_grey_report"]["note"] = "report only (B2); D's reference = D in its own look (grey)"
+ g3 = {}
+ for r in ("g3_m3", "g3_p3"):
+ if X[r] and D[r]:
+ g3[r] = judge(X[r], {m: float(D[r]["task"]["all"][m]) for m in METRICS}, tol3, by_direction(D[r]["task"]))
+ if len(g3) == 2:
+ G["G3"] = dict(planes=g3, **{"pass": all(v["pass"] for v in g3.values())})
+ # B3 release veto (H68, real look, blocks 613,000 / 613,300; distinct starts per block)
+ def blocks(R):
+ blk = {}
+ for b, r in (("613000", "g4_h68_RL_a"), ("613300", "g4_h68_RL_b")):
+ if R.get(r):
+ c = R[r]["counts"]
+ blk[b] = dict(grasp_releases=c["grasp_release"], episodes=c["episodes"], starts=c["starts_grasp_release"],
+ start_rows=c["grasp_release_starts"], loose_starts=c["loose"])
+ return blk
+ blk, dblk = blocks(X), blocks(D)
+ sa, sb = (blk[b]["starts"] if b in blk else None for b in ("613000", "613300"))
+ res["veto"] = dict(rule=f"B3: grasp releases at >= {SR.VETO_MIN_STARTS} distinct starts in block 613,000 AND in "
+ "block 613,300", blocks=blk, vetoed=SR.vetoed(sa, sb),
+ applies=SR.veto_applies(arm) if arm else None, D_blocks=dblk)
+ # G4 (a)-(d): reported only
+ need = ("g4_h68_RL_a", "g4_h68_GR_a", "g4_h68_RL_b", "g4_h68_GR_b", "g4_j224_RL")
+ if all(D[r] for r in need) and all(X[r] for r in ("g4_h68_RL_a", "g4_h68_GR_a", "g4_j224_RL")):
+ dl = max(D["g4_h68_RL_a"]["counts"]["loose"], D["g4_h68_RL_b"]["counts"]["loose"])
+ dg = max(D["g4_h68_RL_a"]["counts"]["grasp_release"], D["g4_h68_RL_b"]["counts"]["grasp_release"])
+ dj = D["g4_j224_RL"]["counts"]["grasp_release"]
+ dc, _ = contrast(D["g4_h68_RL_a"], D["g4_h68_GR_a"])
+ xc, nc = contrast(X["g4_h68_RL_a"], X["g4_h68_GR_a"])
+ g4 = dict(a_loose=dict(cand=X["g4_h68_RL_a"]["counts"]["loose"], D=dl),
+ b_grasp_release=dict(cand=X["g4_h68_RL_a"]["counts"]["grasp_release"], D=dg),
+ c_j224_grasp_release=dict(cand=X["g4_j224_RL"]["counts"]["grasp_release"], D=dj, line=dj + 2),
+ d_contrast=dict(cand=round(xc, 3), D=round(dc, 3), n=nc),
+ plan_mean_RL=dict(cand=X["g4_h68_RL_a"]["counts"]["plan_mean"], D=D["g4_h68_RL_a"]["counts"]["plan_mean"]),
+ j224_RL_task=dict(place_sim_all=X["g4_j224_RL"]["task"]["all"]["place"],
+ by_direction=by_direction(X["g4_j224_RL"]["task"])))
+ g4["a_loose"]["pass_"] = g4["a_loose"]["cand"] <= dl
+ g4["b_grasp_release"]["pass_"] = g4["b_grasp_release"]["cand"] <= dg
+ g4["c_j224_grasp_release"]["pass_"] = g4["c_j224_grasp_release"]["cand"] <= dj + 2
+ g4["d_contrast"]["pass_"] = xc < dc
+ g4["pass"] = all(v["pass_"] for v in g4.values() if isinstance(v, dict) and "pass_" in v)
+ g4["gates"] = False
+ g4["note"] = "reported only (B3 replaces the use of G4 (a)-(d); A3: not usable as a gate)"
+ G["G4_report"] = g4
+ res["gates"] = G
+ decided = not miss and not res["errors"]
+ res["pass_G123"] = all(G.get(k, {}).get("pass", False) for k in ("G1", "G2", "G3")) if decided else None
+ res["vetoed"] = res["veto"]["vetoed"] if decided else None
+ res["eligible"] = SR.ckpt_test(res, arm) if arm else None # B4 (1) test (ctrl: veto exempt)
+ res["g2_places_own"] = X["g2_a"]["task"]["all"]["place"] if X.get("g2_a") else None # B4 (2)
+ res["gates_used"] = ["G1", "G2", "G3", "veto (B3; not ctrl)"]
+ return res, D, X
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--platform", required=True)
+ p.add_argument("--name", required=True)
+ p.add_argument("--ref", default="D")
+ p.add_argument("--root", required=True, help="folder with runs/gates///")
+ p.add_argument("--ref-root", default="", help="folder with D's reference runs (default: --root)")
+ p.add_argument("--validation", default="", help="the check's validation result (verdict.usable_as_gate)")
+ p.add_argument("--out", required=True)
+ a = p.parse_args()
+ res, D, X = summarize(a.platform, a.name, a.ref, a.root, a.ref_root or a.root, a.validation or None)
+ if res["missing"]:
+ print("missing runs:", res["missing"])
+ if res["errors"]:
+ print("errors:", res["errors"])
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
+ Path(a.out).write_text(json.dumps(res, indent=1, default=float))
+ G = res["gates"]
+ print(json.dumps({k: (v.get("pass") if isinstance(v, dict) else v) for k, v in G.items()}),
+ "veto", res["veto"]["vetoed"], {b: v["starts"] for b, v in res["veto"]["blocks"].items()},
+ "pass_G123", res["pass_G123"], "eligible", res["eligible"], "g2_places", res["g2_places_own"])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/check/run_gates.sh b/so101_pick_place/code/scripts/so101_pick_place/check/run_gates.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9aa4f1e08aee8701b54e39d15b89923d20acd312
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/check/run_gates.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+# The sim checks of a camera student (the v12 selection gates, results/sim_checks/SELECTION_v12.md on the Hub): G1
+# nominal success on the sim table, G2 the robot-like check, G3 the table plane -3 / +3 mm, the B3 release veto and
+# the G4 numbers (reported only). Every run is one check_eval.py evaluation (CPU MuJoCo + GPU renders).
+#
+# run_gates.sh run [ref] the evaluations one after the other -> /runs/gates/local//
+# run_gates.sh summary [ref_name] -> /out/gates/local/.json (gates_summary.py, against
+# D's runs in /runs/gates/local/, default D)
+# "ref" adds D's extra reference runs (G2 repeats b / c, the H68 grey repeat): run D once with "ref" before the
+# summary of another student (name D, checkpoint student/s4_v8_roll_s801/it_02000.pt). Student names for the summary:
+# v12__s_it<1000|1500> (the released student: v12_tb10_s1210_it1000).
+#
+# Per checkpoint (9 evaluations; ref: + 3):
+# g1_dev100, g1_homedev100 sim table, nominal, no servo model, roll cap 98, 1,500 steps, hold cap 20 s, own look
+# g2_a J224, measured plane, flat floor, fit_d2q, 40 s, own look (file seeds)
+# g2_b, g2_c (ref) the same, seeds 613,600 / 613,900
+# g3_m3, g3_p3 g2_a with the plane height -3 / +3 mm
+# g4_h68_RL_a, g4_h68_RL_b H68 x 4 draws, 8 s, real look (arm RL), seeds 613,000 / 613,300 (B3 veto: both blocks)
+# g4_h68_GR_a H68 grey look, seeds 613,000 (G4 (d) contrast, reported)
+# g4_h68_GR_b (ref) seeds 613,300
+# g4_j224_RL J224 in arm RL (G4 (c), reported)
+#
+# Environment: PY (Python with torch, mujoco, warp-lang, newton; default python3), WORKERS (CPU MuJoCo workers,
+# default 6), RUNNER (a command prefix for every evaluation, e.g. a memory cap), ONLY (comma list of run names: run
+# only these), HORIZON / TASK_ROWS (smoke only: shorter episodes / the first rows of the task file; the gate rules
+# need the full sets).
+# Ported from the study's runner ~/so101_r2s_claude/v12/check/run_gates.sh + lib/run_one.sh (local mode; the AMD
+# mode, the GPU lock and the memory cap of the study machine are left out). The evaluation list is the same.
+set -uo pipefail
+CODE="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
+CK="$CODE/scripts/so101_pick_place/check"
+A="$CODE/artifacts/so101_pick_place"
+J=$A/rl_inputs/check_tasks/jit224.npz
+H=$A/rl_inputs/check_tasks/h68.npz
+DEV=$A/rl_inputs/tasks/dev100.npz
+HDEV=$A/rl_inputs/tasks/home_dev100.npz
+DYN_FILE=$CODE/configs/so101_pick_place/dyn_fit_d2q.json
+PY=${PY:-python3}
+MODE=${1:?mode: run | summary}
+
+list() { # [: one line per evaluation: ]
+ local REF=$1
+ echo "fit_d2q g2_a --arm own --tasks $J --horizon 2000"
+ echo "fit_d2q g4_j224_RL --arm RL --tasks $J --horizon 2000"
+ echo "fit_d2q g3_m3 --arm own --tasks $J --horizon 2000 --plane-dz -0.003"
+ echo "fit_d2q g3_p3 --arm own --tasks $J --horizon 2000 --plane-dz 0.003"
+ [ "$REF" = ref ] && echo "fit_d2q g2_b --arm own --tasks $J --horizon 2000 --seed-base 613600"
+ [ "$REF" = ref ] && echo "fit_d2q g2_c --arm own --tasks $J --horizon 2000 --seed-base 613900"
+ echo "none g1_dev100 --arm own --tasks $DEV --plane sim --horizon 1500 --hold-cap-s 20 --roll-hi-deg 98"
+ echo "none g1_homedev100 --arm own --tasks $HDEV --plane sim --horizon 1500 --hold-cap-s 20 --roll-hi-deg 98"
+ echo "fit_d2q g4_h68_RL_a --arm RL --tasks $H --draws 4 --seed-base 613000 --horizon 400"
+ echo "fit_d2q g4_h68_RL_b --arm RL --tasks $H --draws 4 --seed-base 613300 --horizon 400"
+ echo "fit_d2q g4_h68_GR_a --arm GR --tasks $H --draws 4 --seed-base 613000 --horizon 400"
+ [ "$REF" = ref ] && echo "fit_d2q g4_h68_GR_b --arm GR --tasks $H --draws 4 --seed-base 613300 --horizon 400"
+ return 0
+}
+
+export PYTHONPATH="$CODE/src${PYTHONPATH:+:$PYTHONPATH}" PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
+export OMP_NUM_THREADS=${OMP_NUM_THREADS:-6} MKL_NUM_THREADS=${MKL_NUM_THREADS:-6}
+cd "$CODE"
+case $MODE in
+run)
+ NAME=${2:?name}; CKPT=$(readlink -f "${3:?student checkpoint}"); ROOT=${4:?output root}; REF=${5:-}
+ [ -f "$CKPT" ] || { echo "run_gates: no checkpoint $CKPT"; exit 2; }
+ O=$ROOT/runs/gates/local/$NAME; mkdir -p "$O" "$ROOT/logs"
+ T0=$(date +%s)
+ echo "[$(date +%T)] run_gates $NAME $CKPT $REF" | tee -a "$O/gates.log"
+ FAIL=0
+ while read -r dyn run args; do
+ if [ -n "${ONLY:-}" ] && [[ ",$ONLY," != *",$run,"* ]]; then continue; fi
+ [ -f "$O/$run.npz" ] && { echo "skip $run (exists)" >> "$O/gates.log"; continue; }
+ if [ -n "${TASK_ROWS:-}" ]; then # smoke: the first TASK_ROWS rows of the task file
+ set -- $args; tf=""; rest=()
+ while [ $# -gt 0 ]; do if [ "$1" = --tasks ]; then tf=$2; shift 2; else rest+=("$1"); shift; fi; done
+ sub=$O/_rows_${run}.npz
+ "$PY" -c "import numpy as np, sys; t = dict(np.load(sys.argv[1], allow_pickle=True)); n = len(t['seeds']); k = int(sys.argv[3]); np.savez(sys.argv[2], **{a: (v[:k] if np.ndim(v) and len(v) == n else v) for a, v in t.items()})" "$tf" "$sub" "$TASK_ROWS"
+ args="${rest[*]} --tasks $sub"
+ fi
+ [ -n "${HORIZON:-}" ] && args="$args --horizon $HORIZON"
+ if [ "$dyn" = none ]; then export NEDM_SO101_DYN=""; else export NEDM_SO101_DYN="$(cat "$DYN_FILE")"; fi
+ t=$(date +%s)
+ ${RUNNER:-} "$PY" -B "$CK/check_eval.py" eval --tag "gates_${NAME}_$run" --workers "${WORKERS:-6}" --student "$CKPT" \
+ --out "$O/$run.npz" $args > "$ROOT/logs/gates_${NAME}_$run.log" 2>&1 < /dev/null
+ rc=$?
+ rm -f "$O/_rows_${run}.npz"
+ echo "[$(date +%T)] $run rc $rc wall $(( $(date +%s) - t )) s" | tee -a "$O/gates.log"
+ [ "$rc" = 0 ] || FAIL=$((FAIL + 1))
+ done < <(list "$REF")
+ echo "[$(date +%T)] run_gates $NAME done, wall $(( $(date +%s) - T0 )) s, $FAIL failed" | tee -a "$O/gates.log"
+ [ "$FAIL" = 0 ] || { echo "run_gates: $FAIL evaluations failed (logs: $ROOT/logs/gates_${NAME}_*.log)" >&2; exit 1; };;
+summary)
+ NAME=${2:?name}; ROOT=${3:?root}; REFN=${4:-D}
+ mkdir -p "$ROOT/out/gates/local"
+ ${RUNNER:-} "$PY" -B "$CK/gates_summary.py" --platform local --name "$NAME" --ref "$REFN" --root "$ROOT" \
+ --out "$ROOT/out/gates/local/$NAME.json";;
+*) sed -n 2,26p "$0"; exit 2;;
+esac
diff --git a/so101_pick_place/code/scripts/so101_pick_place/check/sel_rules.py b/so101_pick_place/code/scripts/so101_pick_place/check/sel_rules.py
new file mode 100644
index 0000000000000000000000000000000000000000..12d9b54d4734f9fcaa1c30e40cfdfce03d6c8dcb
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/check/sel_rules.py
@@ -0,0 +1,161 @@
+"""Addendum B of SELECTION_v12.md (results/sim_checks/ on the Hub) as pure functions (no file I/O), used by
+gates_summary.py.
+
+- names: v12__s (a run) and v12__s_it<1000|1500> (a checkpoint); "visR" is a prefix of
+ "visRtbpl", so the arm is matched as a whole token between "v12_" and "_s".
+- B1 tolerances: G2 = max(2.5 SD sqrt(1 + 1/3), 4) (A1: one run vs the mean of D's 3), G3 = max(2.5 SD sqrt(2), 4)
+ (one run vs ONE D run).
+- B2 own look: visR and visRtbpl = the real-look parts, every other arm (and D) = the grey parts.
+- B3 veto: grasp releases at >= 2 distinct starts in block 613,000 AND at >= 2 distinct starts in block 613,300; it
+ applies to every arm except ctrl.
+- B4 (1) checkpoint: it 1500 if it passes G1, G2, G3 and is not vetoed, else it 1000 with the same test, else out;
+ (2) seed: more G2 places (own look, sim lenient rule); a difference below 20 places is a tie -> the lower seed.
+- B5 slots: 1 visual (visR, visRtbpl, visH), 2 table (tbpl, tb10, tb15, tb05), 3 table + visual (visRtbpl, visH, then
+ the next unused table arm), 4 control (ctrl, visH, then the next unused table arm); empty if no candidate.
+"""
+from __future__ import annotations
+
+import math
+import re
+
+ARMS = ("ctrl", "tb05", "tb10", "tb15", "tbpl", "visR", "visH", "visRtbpl")
+_ARM_RX = "|".join(sorted(ARMS, key=len, reverse=True)) # longest first (visRtbpl before visR)
+RUN_RX = re.compile(rf"^v12_({_ARM_RX})_s(\d+)$")
+CKPT_RX = re.compile(rf"^(v12_(?:{_ARM_RX})_s\d+)_it(1000|1500)$")
+ITS = ("it1500", "it1000") # B4 (1) order
+# SELECTION_v12.md section 1 (12 runs, 24 checkpoints; the "26" in section 1 is a miscount)
+EXPECTED_RUNS = ("v12_ctrl_s1201", "v12_ctrl_s1202", "v12_tb05_s1205", "v12_tb10_s1210", "v12_tb15_s1215",
+ "v12_tbpl_s1221", "v12_tbpl_s1222", "v12_visR_s1231", "v12_visR_s1232", "v12_visH_s1235",
+ "v12_visRtbpl_s1241", "v12_visRtbpl_s1242")
+REAL_LOOK_ARMS = ("visR", "visRtbpl")
+TIE_PLACES = 20
+VETO_MIN_STARTS = 2
+SLOT1 = ("visR", "visRtbpl", "visH")
+TABLE_ORDER = ("tbpl", "tb10", "tb15", "tb05")
+SLOT3 = ("visRtbpl", "visH") + TABLE_ORDER
+SLOT4 = ("ctrl", "visH") + TABLE_ORDER
+SLOTS = ((1, "visual", SLOT1), (2, "table", TABLE_ORDER), (3, "table + visual", SLOT3), (4, "control", SLOT4))
+
+
+def parse_run(run):
+ """'v12_visRtbpl_s1241' -> ('visRtbpl', 1241); anything else -> (None, None)."""
+ m = RUN_RX.match(run or "")
+ return (m.group(1), int(m.group(2))) if m else (None, None)
+
+
+def parse_ckpt(name):
+ """'v12_visR_s1231_it1500' -> ('v12_visR_s1231', 'it1500'); anything else -> (None, None)."""
+ m = CKPT_RX.match(name or "")
+ return (m.group(1), f"it{m.group(2)}") if m else (None, None)
+
+
+def arm_of(name):
+ """The arm of a run or checkpoint name (None if the name is not a v12 candidate)."""
+ run, _ = parse_ckpt(name)
+ return parse_run(run or name)[0]
+
+
+def own_look(arm):
+ """B2: the look of a student's pinned scene: 'real' for visR / visRtbpl, else 'grey' (D and the other arms)."""
+ return "real" if arm in REAL_LOOK_ARMS else "grey"
+
+
+def tol_g2(sd):
+ """A1 (kept by B1): one candidate run vs the mean of D's three runs."""
+ return max(2.5 * sd * math.sqrt(1.0 + 1.0 / 3.0), 4.0)
+
+
+def tol_g3(sd):
+ """B1: one candidate run vs ONE D run at each plane."""
+ return max(2.5 * sd * math.sqrt(2.0), 4.0)
+
+
+def vetoed(starts_a, starts_b):
+ """B3: grasp releases at >= 2 distinct starts in block 613,000 AND in block 613,300 (None if a block is missing)."""
+ if starts_a is None or starts_b is None:
+ return None
+ return starts_a >= VETO_MIN_STARTS and starts_b >= VETO_MIN_STARTS
+
+
+def veto_applies(arm):
+ """B3: every arm except ctrl (the training-length control)."""
+ return arm != "ctrl"
+
+
+def ckpt_test(summary, arm):
+ """B4 (1) test of one checkpoint: True (passes G1, G2, G3 and, unless ctrl, is not vetoed), False, or None
+ (undecided: a summary or a required run is missing, or an error)."""
+ if not summary or summary.get("errors"):
+ return None
+ g = summary.get("pass_G123")
+ if g is None:
+ return None
+ if not g:
+ return False
+ if not veto_applies(arm):
+ return True
+ v = summary.get("veto", {}).get("vetoed")
+ if v is None:
+ return None
+ return not v
+
+
+def pick_checkpoint(its, arm):
+ """B4 (1): its = {'it1500': summary, 'it1000': summary}. Returns dict(pick, status, why); status 'pass', 'out' or
+ 'undecided' (an undecided it 1500 is not skipped: the run is undecided until it is complete)."""
+ why = []
+ for it in ITS:
+ ok = ckpt_test(its.get(it), arm)
+ if ok is None:
+ why.append(f"{it} undecided")
+ return dict(pick=None, status="undecided", why="; ".join(why))
+ if ok:
+ why.append(f"{it} passes" + ("" if veto_applies(arm) else " G1-G3 (ctrl: veto exempt)"))
+ return dict(pick=it, status="pass", why="; ".join(why))
+ why.append(f"{it} fails ({fail_reason(its[it], arm)})")
+ return dict(pick=None, status="out", why="; ".join(why) + " -> the run is out")
+
+
+def fail_reason(summary, arm):
+ out = [g for g in ("G1", "G2", "G3") if not summary.get("gates", {}).get(g, {}).get("pass", False)]
+ if veto_applies(arm) and summary.get("veto", {}).get("vetoed"):
+ out.append("vetoed")
+ return ", ".join(out) or "?"
+
+
+def pick_seed(cands):
+ """B4 (2): cands = [dict(run, seed, places)] (passing runs of one arm). The run with more G2 places; a difference
+ below TIE_PLACES is a tie and a tie goes to the lower seed. Returns (chosen dict, why)."""
+ if not cands:
+ return None, "no passing run"
+ if len(cands) == 1:
+ return cands[0], "the only passing run"
+ best = max(c["places"] for c in cands)
+ tied = [c for c in cands if best - c["places"] < TIE_PLACES]
+ ch = min(tied, key=lambda c: c["seed"])
+ pl = ", ".join(f"s{c['seed']} {c['places']}" for c in sorted(cands, key=lambda c: c["seed"]))
+ if len(tied) > 1:
+ return ch, f"G2 places {pl}: difference below {TIE_PLACES} = tie -> the lower seed s{ch['seed']}"
+ return ch, f"G2 places {pl}: s{ch['seed']} has {TIE_PLACES} or more places more"
+
+
+def fill_slots(passing):
+ """B5: passing = the set of arms with a chosen run. Returns [dict(slot, family, arm or None, rule)]."""
+ used, out = {}, []
+ for k, fam, order in SLOTS:
+ notes, arm = [], None
+ for a in order:
+ if a not in passing:
+ notes.append(f"{a}: no passing run")
+ elif a in used:
+ notes.append(f"{a}: used in slot {used[a]}")
+ else:
+ arm = a
+ break
+ if arm is not None:
+ used[arm] = k
+ rule = f"B5 slot {k} order {' > '.join(order)}: " + "; ".join(notes + [f"-> {arm}"])
+ else:
+ rule = f"B5 slot {k} order {' > '.join(order)}: " + "; ".join(notes) + " -> empty"
+ out.append(dict(slot=k, family=fam, arm=arm, rule=rule))
+ return out
diff --git a/so101_pick_place/code/scripts/so101_pick_place/check/sim_eps.py b/so101_pick_place/code/scripts/so101_pick_place/check/sim_eps.py
new file mode 100644
index 0000000000000000000000000000000000000000..a887cdb9ff5396b5b2907afa8e63b0cfa74d814f
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/check/sim_eps.py
@@ -0,0 +1,189 @@
+"""Per-episode outcomes of the sim reproduction runs (eval_rec.py npz files) with the robot's carry-stop rule.
+
+Per episode (sim world b; heights above the PHYSICS table: the calib plane in "real" runs, z = 0 in "nominal" runs):
+ grasp the cube held (jaw 3-15 deg and the cube centre within 25 mm of the grasp point) for >= 1 s, or lifted
+ lift the cube bottom >= 20 mm above the table at any step (analyze_grasp.py LIFT rule)
+ place sim lenient success (task rule)
+ near_place robot-like place: lenient, or lifted and then the jaw opened (> 0.19 rad) with the cube centre <= 30 mm
+ (xy) from the goal centre (a drop from a hover above the plate counts; the sim's drop rules
+ release_high / unsupported end such episodes before the cube lands)
+ goal_hover_s time held with the grasp point within 30 mm (xy) of the goal centre
+ carry stop the robot rule (robot_eps.py): >= 2 s of consecutive decisions with the cube held and the planned motion
+ (max over the 5 arm joints of |last chunk step - q at the decision|) < 0.5 deg
+ stall >= 2 s of consecutive decisions with the cube held and the grasp point moving < 5 mm in the next 2 s
+ (any plan; includes a plan that pushes into the floor or the table)
+ end the sim end code (task.ENDS)
+usage: sim_eps.py OUT.json TAG=run.npz[:plane] ... (plane = 'real' for the calib plane, else nominal)
+
+Ported from the study's ~/so101_r2s_claude/v11/fullcheck/lib/sim_eps.py: code, kin points and task metadata come from
+this repository and its download folder (the study read hw_lib.py of commit ddb08332d; its tcp() is the same code).
+"""
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import numpy as np
+
+WT = Path(__file__).resolve().parents[3] # the repository root
+sys.path.insert(0, str(WT / "src"))
+sys.path.insert(0, str(WT / "scripts/so101_policy/real2sim/hw"))
+import hw_lib as H # noqa: E402
+from nedm.so101_policy import task as T # noqa: E402
+
+KIN = str(WT / "artifacts/so101_pick_place/rl_inputs/geometry/kin_points_v1.npz")
+PLANE = (-0.00468, -0.03641, 0.01836)
+META = WT / "artifacts/so101_pick_place/rl_inputs/check_tasks/all280.json" # task metadata of jit224 (direction per seed)
+DT = 0.02
+MOVE_DEG, STOP_S, STALL_MM = 0.5, 2.0, 5.0
+HELD_JAW = (3.0, 15.0)
+HELD_D = 0.025
+LIFT, DOWN, OPEN, DROP_R = 0.02, 0.005, 0.19, 0.030
+_L = None
+
+
+def layer():
+ global _L
+ if _L is None:
+ _L = H.ActionLayer(KIN)
+ return _L
+
+
+def runs(mask, min_n):
+ out, i, n = [], 0, len(mask)
+ while i < n:
+ if mask[i]:
+ j = i
+ while j < n and mask[j]:
+ j += 1
+ if j - i >= min_n:
+ out.append((i, j))
+ i = j
+ else:
+ i += 1
+ return out
+
+
+def episodes(npz, plane, meta_rows):
+ z = np.load(npz, allow_pickle=True)
+ q = z["state_q"].astype(np.float64)
+ cube = z["state_cube"].astype(np.float64)
+ steps = z["steps"].astype(int)
+ length = z["length"].astype(int)
+ goal = z["goal_xy"].astype(np.float64)
+ le = z["lenient"].astype(bool)
+ end = z["end"].astype(int)
+ rq, rc = z["rec_q"].astype(np.float64), z["rec_chunk"].astype(np.float64)
+ n, Tm = q.shape[:2]
+ seeds = z["seeds"]
+ by_seed = {m["seed"]: m for m in meta_rows}
+ tcp = layer().tcp(q.reshape(-1, 6)).reshape(n, Tm, 3)
+ per = 5 * DT
+ nstop = int(round(STOP_S / per))
+ out = []
+ for b in range(n):
+ k = max(1, min(int(steps[b]), Tm))
+ c = cube[b, :k, :3]
+ fl = np.zeros(k) if plane is None else plane[0] + plane[1] * c[:, 0] + plane[2] * c[:, 1]
+ h = c[:, 2] - T.CUBE_HALF - fl
+ jaw = np.degrees(q[b, :k, 5])
+ dist = np.linalg.norm(tcp[b, :k] - c, axis=1)
+ held = (jaw >= HELD_JAW[0]) & (jaw <= HELD_JAW[1]) & (dist < HELD_D)
+ up = np.flatnonzero(h >= LIFT)
+ k_lift = int(up[0]) if len(up) else None
+ held_runs = runs(held, int(1.0 / DT))
+ grasp = bool(held_runs) or k_lift is not None
+ rel = None
+ if k_lift is not None:
+ gone = np.flatnonzero((np.arange(k) > k_lift) & ((np.radians(jaw) > OPEN) | (h < DOWN)))
+ if len(gone):
+ g = int(gone[0])
+ rel = dict(t=round((g + 1) * DT, 2), dxy_mm=round(float(np.linalg.norm(c[g, :2] - goal[b])) * 1e3, 1),
+ h_mm=round(float(h[g]) * 1e3, 1))
+ relj = None
+ if k_lift is not None:
+ op = np.flatnonzero((np.arange(k) > k_lift) & (np.radians(jaw) > OPEN))
+ if len(op):
+ g = int(op[0])
+ relj = dict(t=round((g + 1) * DT, 2), dxy_mm=round(float(np.linalg.norm(c[g, :2] - goal[b])) * 1e3, 1),
+ h_mm=round(float(h[g]) * 1e3, 1))
+ near_goal = np.linalg.norm(tcp[b, :k, :2] - goal[b], axis=1) < DROP_R
+ goal_hover_s = round(float((held & near_goal).sum() * DT), 2)
+ # decisions: d starts at step 5 d (state index 5 d - 1; d = 0: the start state ~ index 0)
+ D = min(int(length[b]), rq.shape[1])
+ si = np.clip(5 * np.arange(D) - 1, 0, k - 1)
+ mot = np.degrees(np.abs(rc[b, :D, -1, :5] - rq[b, :D, :5])).max(1)
+ hd = held[si]
+ stops = []
+ for i0, i1 in runs(hd & (mot < MOVE_DEG), nstop):
+ ss = si[i0:i1]
+ stops.append(dict(t0=round(float(si[i0] * DT), 2), dur_s=round((i1 - i0) * per, 2),
+ motion_p50_deg=round(float(np.median(mot[i0:i1])), 2),
+ tcp_z_mm=round(float(np.median(tcp[b, ss, 2])) * 1e3, 1),
+ cube_h_mm=round(float(np.median(h[ss])) * 1e3, 1),
+ to_goal_mm=round(float(np.median(np.linalg.norm(tcp[b, ss, :2] - goal[b], axis=1))) * 1e3, 1)))
+ # stall: held and the grasp point moves < 5 mm over the next 2 s (100 steps)
+ fut = np.clip(si + int(STOP_S / DT), 0, k - 1)
+ moved = np.linalg.norm(tcp[b, fut] - tcp[b, si], axis=1) * 1e3
+ ok_f = (si + int(STOP_S / DT)) <= k - 1
+ stalls = []
+ for i0, i1 in runs(hd & ok_f & (moved < STALL_MM), 1):
+ ss = si[i0:i1]
+ stalls.append(dict(t0=round(float(si[i0] * DT), 2), dur_s=round((i1 - i0) * per + STOP_S, 2),
+ motion_p50_deg=round(float(np.median(mot[i0:i1])), 2),
+ tcp_z_mm=round(float(np.median(tcp[b, ss, 2])) * 1e3, 1),
+ cube_h_mm=round(float(np.median(h[ss])) * 1e3, 1),
+ to_goal_mm=round(float(np.median(np.linalg.norm(tcp[b, ss, :2] - goal[b], axis=1))) * 1e3, 1)))
+ m = by_seed[int(seeds[b])]
+ out.append(dict(ep=b, seed=int(seeds[b]), set=m["set"], layout=m["layout"], jitter=m["jitter"],
+ direction=m["direction"], robot_episode=m["episode"], robot_student=m["student"],
+ grasp=grasp, lift=k_lift is not None, place=bool(le[b]),
+ near_place=bool(le[b] or (relj is not None and relj["dxy_mm"] <= DROP_R * 1e3)), release=rel,
+ release_jaw=relj, goal_hover_s=goal_hover_s,
+ carry_stop=bool(stops), stops=stops, stall=bool(stalls), stalls=stalls,
+ end=T.ENDS[int(end[b])], t_end=round(k * DT, 2), held_s=round(float(held.sum() * DT), 1),
+ jaw_min_deg=round(float(jaw.min()), 1)))
+ return out
+
+
+def summary(rows):
+ def cnt(rs):
+ return dict(n=len(rs), grasp=sum(r["grasp"] for r in rs), lift=sum(r["lift"] for r in rs),
+ place=sum(r["place"] for r in rs), near_place=sum(r["near_place"] for r in rs),
+ carry_stop=sum(r["carry_stop"] for r in rs), stall=sum(r["stall"] for r in rs))
+ s = {}
+ for st in sorted({r["set"] for r in rows}):
+ rs = [r for r in rows if r["set"] == st]
+ s[st] = {d: cnt([r for r in rs if r["direction"] == d]) for d in ("R->L", "L->R")}
+ ends = {}
+ for r in rs:
+ ends[r["end"]] = ends.get(r["end"], 0) + 1
+ s[st]["ends"] = ends
+ return s
+
+
+def main():
+ meta = json.loads(META.read_text())
+ rows_meta = [dict(m, seed=meta["seed0"] + m["row"]) for m in meta["tasks"]]
+ res = {}
+ for spec in sys.argv[2:]:
+ tag, f = spec.split("=", 1)
+ pl = None
+ if f.endswith(":real"):
+ f, pl = f[:-5], PLANE
+ elif f.endswith(":realnoy"):
+ f, pl = f[:-8], (PLANE[0], PLANE[1], 0.0)
+ rows = episodes(f, pl, rows_meta)
+ s = summary(rows)
+ res[tag] = dict(file=f, plane=pl, summary=s, episodes=rows)
+ for st, v in s.items():
+ line = " | ".join(f"{d}: n {v[d]['n']} g {v[d]['grasp']} l {v[d]['lift']} p {v[d]['place']} "
+ f"np {v[d]['near_place']} stop {v[d]['carry_stop']} stall {v[d]['stall']}"
+ for d in ("R->L", "L->R"))
+ print(f"{tag:28s} {st:9s} {line} | ends {v['ends']}")
+ Path(sys.argv[1]).write_text(json.dumps(res, indent=1))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/download.py b/so101_pick_place/code/scripts/so101_pick_place/download.py
new file mode 100644
index 0000000000000000000000000000000000000000..5152ed5b57cfc0f9a8988785d67e03afa699294f
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/download.py
@@ -0,0 +1,141 @@
+"""Download the Hub files of the SO101 pick-and-place release and check the size and SHA-256 of every file.
+
+ python scripts/so101_pick_place/download.py [--groups nrd,teacher,...] [--dest DIR] [--source DIR] [--check-only]
+
+The file list, the sizes and the SHA-256 values come from so101_pick_place/release_manifest.json (repository copy).
+Files land in DEST/so101_pick_place/ (default DEST = artifacts of this checkout: the code reads its defaults
+there, nedm.so101_policy.paths). A file that is already in place with the right size and SHA-256 is not fetched again.
+
+Where the files come from:
+- the Hub (harryzhang1018/NeDM, dataset), at the manifest's pinned "hf_revision" (huggingface_hub.snapshot_download);
+- or a local folder with the layout of the Hub folder so101_pick_place/ (--source DIR, or the environment variable
+ SO101_PP_HF_SOURCE): e.g. a release staging folder or an earlier download. Files are hard-linked when the folder is
+ on the same file system, else copied. Every file is checked in the same way.
+Without a pinned revision ("PENDING") and without --source, the script only checks the files that are in place.
+
+Groups (folders of so101_pick_place/ on the Hub; sizes from the manifest are printed):
+ nrd nrd/ the policy NRD c1_s62 and the base NRD c0_s62 (main-compatible best.pt,
+ the original files in original/, the training records)
+ nrd_test nrd_test/ the sealed scripted NRD test set (3,050 episodes)
+ nrd_data nrd_data/ the 4 NRD training data parts (93,494 episodes) + the 7 PPO policies
+ teacher teacher/ without t1_expert_data/ teacher checkpoints T0, T2-T6 and their run records
+ expert_data teacher/t1_expert_data/ the 24,576 NRD expert episodes behind the BC teacher T2
+ student student/ student checkpoints S0-S5 and their run records
+ rl_inputs rl_inputs/ task sets, start banks, geometry, the task sets of the sim checks
+ results results/ sim-check and robot result files, the NRD test results
+ bundle bundle/ the folder installed on the robot computer, and its tarball
+ recordings robot/lerobot_recordings/ 2 LeRobot teleop recordings (replay input, camera calibration input)
+ robot robot/ robot logs, videos and the recordings
+ scene_calib scene_calib/ calibration and scene files (the same bytes as configs/so101_pick_place/)
+ provenance provenance/ code snapshots that are in no commit
+ card README.md the dataset card of the folder
+ all every file
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import shutil
+import sys
+from pathlib import Path
+
+CODE = Path(__file__).resolve().parents[2]
+MANIFEST = CODE / "so101_pick_place" / "release_manifest.json"
+GROUPS = {"nrd": ("nrd/",), "nrd_test": ("nrd_test/",), "nrd_data": ("nrd_data/",), "teacher": ("teacher/",),
+ "expert_data": ("teacher/t1_expert_data/",), "student": ("student/",), "rl_inputs": ("rl_inputs/",),
+ "results": ("results/",), "bundle": ("bundle/",), "recordings": ("robot/lerobot_recordings/",),
+ "robot": ("robot/",), "scene_calib": ("scene_calib/",), "provenance": ("provenance/",),
+ "card": ("README.md",), "all": ("",)}
+EXCLUDE = {"teacher": ("teacher/t1_expert_data/",)}
+
+
+def sha256(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for block in iter(lambda: f.read(1 << 20), b""):
+ h.update(block)
+ return h.hexdigest()
+
+
+def select(files, prefix, groups):
+ out = {}
+ for g in groups:
+ if g not in GROUPS:
+ sys.exit(f"unknown group {g!r} (groups: {', '.join(GROUPS)})")
+ for n, m in files.items():
+ rel = n[len(prefix):]
+ if rel.startswith(GROUPS[g]) and not rel.startswith(EXCLUDE.get(g, ("\0",))):
+ out[n] = m
+ return out
+
+
+def place(src, dst):
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ if dst.exists() or dst.is_symlink():
+ dst.unlink()
+ try:
+ os.link(src, dst)
+ except OSError:
+ shutil.copyfile(src, dst)
+
+
+def main(argv=None):
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("--groups", default="nrd,teacher,student,rl_inputs,results,bundle,recordings",
+ help="comma list (default: what reproduce.sh full needs; see above)")
+ p.add_argument("--dest", default=str(CODE / "artifacts"), help="files land in DEST/so101_pick_place/")
+ p.add_argument("--source", default=os.environ.get("SO101_PP_HF_SOURCE", ""),
+ help="local folder with the layout of the Hub folder so101_pick_place/ (instead of the Hub)")
+ p.add_argument("--manifest", default=str(MANIFEST))
+ p.add_argument("--check-only", action="store_true", help="only check the files in place")
+ p.add_argument("--quiet", action="store_true", help="print only the summary and the bad files")
+ a = p.parse_args(argv)
+ manifest = json.loads(Path(a.manifest).read_text())
+ prefix, dest = manifest["prefix"], Path(a.dest)
+ files = select(manifest["files"], prefix, [g for g in a.groups.split(",") if g])
+ for n in files:
+ if not n.startswith(prefix) or n.startswith("/") or "\\" in n or ".." in n.split("/"):
+ sys.exit(f"unsafe path in the manifest: {n}")
+ total = sum(m["bytes"] for m in files.values())
+ print(f"{len(files)} files, {total / 1e9:.3f} GB (groups {a.groups}) -> {dest / prefix}", flush=True)
+ good = lambda n: ((dest / n).is_file() and (dest / n).stat().st_size == files[n]["bytes"]
+ and sha256(dest / n) == files[n]["sha256"])
+ ok = {n: good(n) for n in sorted(files)}
+ missing = [n for n in ok if not ok[n]]
+ rev = manifest.get("hf_revision", "")
+ pinned = re.fullmatch(r"[0-9a-f]{40}", rev) is not None
+ if missing and not a.check_only:
+ if a.source:
+ src = Path(a.source)
+ print(f"{len(missing)} file(s) from the local folder {src} (hard link or copy)", flush=True)
+ for n in missing:
+ f = src / n[len(prefix):]
+ if f.is_file():
+ place(f, dest / n)
+ elif pinned:
+ try:
+ from huggingface_hub import snapshot_download
+ except ImportError:
+ sys.exit(f"{len(missing)} file(s) must be downloaded, and the download needs huggingface_hub "
+ "(pip install huggingface_hub); or give --source DIR")
+ print(f"download {len(missing)} file(s) from {manifest['repo_id']} at revision {rev}", flush=True)
+ snapshot_download(repo_id=manifest["repo_id"], repo_type="dataset", revision=rev, allow_patterns=missing,
+ local_dir=str(dest))
+ else:
+ print(f"hf_revision is {rev!r} (no pinned Hub revision) and no --source: only the check of the files "
+ f"in {dest / prefix}", flush=True)
+ ok.update({n: good(n) for n in missing})
+ for n in ok:
+ if not (a.quiet and ok[n]):
+ print(f"{'ok ' if ok[n] else 'BAD'} {dest / n}", flush=True)
+ bad = [n for n in ok if not ok[n]]
+ print(f"{len(ok) - len(bad)} of {len(ok)} files OK (size and SHA-256)", flush=True)
+ if bad:
+ sys.exit(f"{len(bad)} file(s) missing or with another size or SHA-256")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/nrd/equiv.py b/so101_pick_place/code/scripts/so101_pick_place/nrd/equiv.py
new file mode 100644
index 0000000000000000000000000000000000000000..b56291e8a66a4955ef7381d9d4cec144e0bdb606
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/nrd/equiv.py
@@ -0,0 +1,53 @@
+"""Rollouts and task metrics of one checkpoint with one code tree, for the original-vs-released check.
+
+Per data folder (all its episodes): (1) a 100-step rollout from the first recorded state, (2) a 100-step rollout
+from the recorded 4-state history at model step 100 (the grasp / carry part of the episode), both with the recorded
+commands and with the contact switches; (3) data.evaluate(by_family=True), the task metrics of training and test.
+Every tensor goes to OUT.pt, the evaluate reports to OUT.json. The code tree's own load_model, load_data and
+step_average_rates are used.
+
+ python -I equiv.py CODE_SRC_DIR CKPT DEVICE OUT_PREFIX NAME=DATA_DIR [NAME=DATA_DIR ...]
+
+Release check of the SO101 pick-and-place study (so101_pick_place/README.md, "The NRD"; reproduce.sh steps
+nrd_val, nrd_strip).
+"""
+import json
+import sys
+import time
+
+
+def main():
+ src, ckpt, device, out = sys.argv[1:5]
+ sys.path.insert(0, src)
+ import torch
+ torch.set_num_threads(8)
+ from nedm.contact_nrd import data as D, model as M
+ model, packet = M.load_model(ckpt, device)
+ kinds = set(model.config["integrate"]["kinds"])
+ tensors, reports, info = {}, {}, dict(code=M.__file__, ckpt=ckpt, device=device, torch=torch.__version__)
+ for item in sys.argv[5:]:
+ name, root = item.split("=", 1)
+ t0 = time.time()
+ data = D.load_data(root, device, model_step_s=model.dt)
+ data = D.step_average_rates(data, kinds)
+ s = data["stride"]
+ st, act = data["states"][:, ::s], data["actions"][:, ::s]
+ with torch.no_grad():
+ traj, gates = model.rollout(st[:, 0], act[:, :100], return_gates=True)
+ k0 = 100
+ hist = st[:, k0 - model.k + 1:k0 + 1]
+ ok = torch.ones(hist.shape[:2], dtype=torch.bool, device=hist.device)
+ traj2, gates2 = model.rollout_from(hist, ok, act[:, k0:k0 + 100], return_gates=True)
+ rep = D.evaluate(model, data, torch.arange(len(data["lengths"]), device=device), by_family=True)
+ tensors[name] = dict(first_state=traj.cpu(), first_state_gates=gates.cpu(), mid=traj2.cpu(), mid_gates=gates2.cpu())
+ reports[name] = rep
+ info[name] = dict(episodes=int(len(data["lengths"])), seconds=round(time.time() - t0, 1),
+ selection_score=rep.get("selection_score"))
+ print(name, json.dumps(info[name]), flush=True)
+ torch.save(tensors, out + ".pt")
+ with open(out + ".json", "w") as f:
+ json.dump(dict(info=info, reports=reports), f, default=float)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/nrd/equiv_compare.py b/so101_pick_place/code/scripts/so101_pick_place/nrd/equiv_compare.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1bed51226e5882e18cb4ccc9fc028714f36487d
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/nrd/equiv_compare.py
@@ -0,0 +1,46 @@
+"""Compare equiv.py outputs of the original file in the training code and the released file in main's code.
+
+ python -I equiv_compare.py OUT.json A_PREFIX B_PREFIX [A_PREFIX B_PREFIX ...]
+
+Per pair: every rollout tensor bit for bit (raw float64 bytes), the max abs difference, and the evaluate reports
+as canonical JSON (sorted keys) for exact equality.
+
+Release check of the SO101 pick-and-place study (so101_pick_place/README.md, "The NRD"; reproduce.sh steps
+nrd_val, nrd_strip).
+"""
+import json
+import sys
+
+import torch
+
+
+def main():
+ out, pairs = sys.argv[1], sys.argv[2:]
+ rows = []
+ for a, b in zip(pairs[::2], pairs[1::2]):
+ ta, tb = torch.load(a + ".pt", weights_only=True), torch.load(b + ".pt", weights_only=True)
+ ja, jb = json.load(open(a + ".json")), json.load(open(b + ".json"))
+ for name in ta:
+ row = dict(a=a, b=b, data=name, episodes=ja["info"][name]["episodes"])
+ for k in ta[name]:
+ x, y = ta[name][k], tb[name][k]
+ row[k] = dict(shape=list(x.shape), bitwise_equal=bool(
+ x.dtype == y.dtype and x.shape == y.shape
+ and torch.equal(x.contiguous().view(-1).view(torch.uint8), y.contiguous().view(-1).view(torch.uint8))),
+ max_abs_diff=float((x.double() - y.double()).abs().nan_to_num(0).max()))
+ ca = json.dumps(ja["reports"][name], sort_keys=True)
+ cb = json.dumps(jb["reports"][name], sort_keys=True)
+ row["evaluate_json_equal"] = ca == cb
+ row["selection_score"] = [ja["reports"][name]["selection_score"], jb["reports"][name]["selection_score"]]
+ rows.append(row)
+ print(name, a.split("/")[-1], "vs", b.split("/")[-1], {k: row[k]["bitwise_equal"] for k in ta[name]},
+ "evaluate equal", row["evaluate_json_equal"], flush=True)
+ ok = all(r["evaluate_json_equal"] and all(v["bitwise_equal"] for k, v in r.items() if isinstance(v, dict))
+ for r in rows)
+ with open(out, "w") as f:
+ json.dump(dict(all_equal=ok, rows=rows), f, indent=1)
+ print("ALL EQUAL" if ok else "DIFFERENCES FOUND")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/nrd/strip_ckpt.py b/so101_pick_place/code/scripts/so101_pick_place/nrd/strip_ckpt.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a8236cf9bdee810958f755035a01d2990a9ed3d
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/nrd/strip_ckpt.py
@@ -0,0 +1,148 @@
+"""Make a contact NRD checkpoint that origin/main's nedm.contact_nrd.model.load_model accepts, from a checkpoint of
+the SO101 study's training code (commit f6f05c21c). The study trained with a training-only geometry loss: the
+model_config key ``aux_geometry`` and two heads ``geo_collision`` / ``geo_contact`` (Linear 128 -> 12 each) that the
+step never uses. This script removes exactly these: the key from the top-level ``model_config`` and the 4 tensors
+``geo_collision.{weight,bias}``, ``geo_contact.{weight,bias}`` from ``model_state_dict``. Every other entry (also
+the training record ``runtime``, ``validation``, ``sigma``, ``stage``, ``update``) is kept unchanged and in the same
+order. Then it reloads the new file and checks every kept entry against the original bit for bit (tensors: dtype,
+shape and raw bytes; other values: exact equality).
+
+ python -I strip_ckpt.py SRC.pt DST.pt REPORT.json [EXPECTED.pt]
+
+EXPECTED.pt (e.g. the released main-compatible best.pt): the new file is compared with it, by bytes and, if the bytes
+differ, entry by entry as above. The bytes depend on the torch version (zip layout) and on the output file name (the
+zip folder name inside the file): the release files were written by torch 2.12.0 under the name best.pt.
+
+Release check of the SO101 pick-and-place study (so101_pick_place/README.md, "The NRD"); used by
+scripts/so101_pick_place/reproduce.sh, step nrd_strip.
+"""
+import hashlib
+import json
+import math
+import os
+import sys
+from collections import OrderedDict
+
+import torch
+
+GEO = ("geo_collision.", "geo_contact.")
+
+
+def sha256(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for b in iter(lambda: f.read(1 << 20), b""):
+ h.update(b)
+ return h.hexdigest()
+
+
+def load(path):
+ torch.serialization.add_safe_globals([torch.torch_version.TorchVersion])
+ return torch.load(path, map_location="cpu", weights_only=True)
+
+
+def same(a, b, where, bad):
+ """Exact equality; tensors by dtype, shape and raw bytes; floats NaN-aware; dict key order too."""
+ if torch.is_tensor(a) or torch.is_tensor(b):
+ ok = (torch.is_tensor(a) and torch.is_tensor(b) and a.dtype == b.dtype and a.shape == b.shape
+ and torch.equal(a.contiguous().view(-1).view(torch.uint8), b.contiguous().view(-1).view(torch.uint8)))
+ if not ok:
+ bad.append(where)
+ return
+ if type(a) is not type(b):
+ bad.append(f"{where} (type {type(a).__name__} vs {type(b).__name__})")
+ return
+ if isinstance(a, dict):
+ if list(a.keys()) != list(b.keys()):
+ bad.append(f"{where} (keys/order)")
+ return
+ for k in a:
+ same(a[k], b[k], f"{where}/{k}", bad)
+ ma, mb = getattr(a, "_metadata", None), getattr(b, "_metadata", None)
+ if ma is not None or mb is not None:
+ same(dict(ma or {}), dict(mb or {}), f"{where}/_metadata", bad)
+ return
+ if isinstance(a, (list, tuple)):
+ if len(a) != len(b):
+ bad.append(f"{where} (length)")
+ return
+ for i, (x, y) in enumerate(zip(a, b)):
+ same(x, y, f"{where}[{i}]", bad)
+ return
+ if isinstance(a, float) and math.isnan(a) and math.isnan(b):
+ return
+ if a != b:
+ bad.append(where)
+
+
+def main():
+ src, dst, report = sys.argv[1:4]
+ p = load(src)
+ sd = p["model_state_dict"]
+ removed = [k for k in sd if k.startswith(GEO)]
+ assert sorted(removed) == sorted(["geo_collision.weight", "geo_collision.bias", "geo_contact.weight",
+ "geo_contact.bias"]), removed
+ assert p["model_config"].get("aux_geometry") is True, p["model_config"]
+ new_sd = OrderedDict((k, v) for k, v in sd.items() if not k.startswith(GEO))
+ meta = getattr(sd, "_metadata", None)
+ if meta is not None: # per-module version records of state_dict(); drop the two removed modules' entries
+ new_sd._metadata = OrderedDict((k, v) for k, v in meta.items() if k not in ("geo_collision", "geo_contact"))
+ new = {}
+ for k, v in p.items():
+ if k == "model_config":
+ new[k] = {kk: vv for kk, vv in v.items() if kk != "aux_geometry"}
+ elif k == "model_state_dict":
+ new[k] = new_sd
+ else:
+ new[k] = v
+ torch.save(new, dst)
+
+ # check: reload both files from disk and compare everything that was kept
+ a, b = load(src), load(dst)
+ bad = []
+ if list(a.keys()) != list(b.keys()):
+ bad.append("top-level keys/order")
+ for k in a:
+ if k == "model_config":
+ same({kk: vv for kk, vv in a[k].items() if kk != "aux_geometry"}, b[k], k, bad)
+ if "aux_geometry" in b[k]:
+ bad.append("model_config still has aux_geometry")
+ elif k == "model_state_dict":
+ kept = OrderedDict((kk, vv) for kk, vv in a[k].items() if not kk.startswith(GEO))
+ ma = getattr(a[k], "_metadata", None)
+ if ma is not None:
+ kept._metadata = OrderedDict((kk, vv) for kk, vv in ma.items()
+ if kk not in ("geo_collision", "geo_contact"))
+ same(kept, b[k], k, bad)
+ if any(kk.startswith(GEO) for kk in b[k]):
+ bad.append("geo tensors still present")
+ else:
+ same(a[k], b[k], k, bad)
+ out = dict(source=src, source_bytes=int(os.path.getsize(src)), source_sha256=sha256(src),
+ released=dst, released_bytes=int(os.path.getsize(dst)), released_sha256=sha256(dst),
+ removed_model_config_keys=["aux_geometry"], removed_tensors=removed,
+ removed_parameters=int(sum(sd[k].numel() for k in removed)),
+ kept_tensors=len(b["model_state_dict"]), kept_parameters=int(sum(t.numel() for t in b["model_state_dict"].values())),
+ state_dict_metadata=meta is not None,
+ unchanged_entries=[k for k in a if k not in ("model_config", "model_state_dict")],
+ note="runtime (the training record) is unchanged: it still lists aux_geometry in runtime.model_config "
+ "and runtime.config, and runtime.parameters counts the removed heads",
+ mismatches=bad, all_kept_entries_equal=not bad, torch=torch.__version__)
+ if len(sys.argv) > 4: # compare with an expected file (the released main-compatible one)
+ exp = sys.argv[4]
+ out.update(expected=exp, expected_sha256=sha256(exp), bytes_equal_to_expected=sha256(exp) == out["released_sha256"])
+ if not out["bytes_equal_to_expected"]:
+ bad_exp = []
+ same(load(exp), b, "expected", bad_exp)
+ out["entries_equal_to_expected"] = not bad_exp
+ out["mismatches_to_expected"] = bad_exp
+ bad += [f"expected: {m}" for m in bad_exp]
+ with open(report, "w") as f:
+ json.dump(out, f, indent=1)
+ print(json.dumps({k: v for k, v in out.items() if k not in ("unchanged_entries",)}, indent=1))
+ if bad:
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/nrd/subsets.py b/so101_pick_place/code/scripts/so101_pick_place/nrd/subsets.py
new file mode 100644
index 0000000000000000000000000000000000000000..33dede0a56e370d7d86a89d36b9d563f40d50ced
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/nrd/subsets.py
@@ -0,0 +1,74 @@
+"""Copy N episodes of one split (default splits == 1, the validation episodes; evenly spaced over the rows of that
+split) of each NRD data part into a small data folder (unified_data.npz with every per-episode array sliced,
+system.json copied). N = 0: every episode of the split. --split family: the first N train and the first N validation
+episodes of every family (smoke training runs need both splits in every family).
+
+ python -I subsets.py OUT N [--split 1|2|family] name=PART_DIR [name=PART_DIR ...]
+
+Release checks of the SO101 pick-and-place study (so101_pick_place/README.md, "The NRD"; reproduce.sh steps nrd_val,
+nrd_strip and the smoke of nrd_train). The release used: N = 64 of each of the 4 parts (original-vs-main check) and
+N = 0 of production_plus (2,853 validation episodes, the validation columns of the README).
+"""
+import hashlib
+import json
+import shutil
+import sys
+from pathlib import Path
+
+import numpy as np
+
+
+def sha256(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for b in iter(lambda: f.read(1 << 24), b""):
+ h.update(b)
+ return h.hexdigest()
+
+
+def main():
+ out_root, n = Path(sys.argv[1]), int(sys.argv[2])
+ args, split = sys.argv[3:], "1"
+ if args[:1] == ["--split"]:
+ split, args = args[1], args[2:]
+ record = {}
+ for item in args:
+ name, src = item.split("=", 1)
+ src = Path(src)
+ out = out_root / name
+ out.mkdir(parents=True, exist_ok=True)
+ with np.load(src / "unified_data.npz") as p:
+ files = list(p.files)
+ splits = p["splits"]
+ total = len(splits)
+ if split == "family":
+ fam_all = p["family"]
+ val = np.sort(np.concatenate([np.flatnonzero((fam_all == f) & (splits == sp))[:n]
+ for f in np.unique(fam_all) for sp in (0, 1)]))
+ pick = val
+ else:
+ val = np.flatnonzero(splits == int(split))
+ pick = val if n == 0 or n >= len(val) else val[np.linspace(0, len(val) - 1, n).round().astype(np.int64)]
+ assert len(np.unique(pick)) == len(pick), "not enough episodes"
+ arrays = {}
+ for k in files: # one array at a time (the large parts are several GB)
+ a = p[k]
+ if a.ndim == 0 or a.shape[0] != total:
+ raise ValueError(f"{src}: array {k} {a.shape} is not per episode")
+ arrays[k] = np.ascontiguousarray(a[pick])
+ del a
+ np.savez(out / "unified_data.npz", **arrays)
+ shutil.copy2(src / "system.json", out / "system.json")
+ fam = arrays.get("family")
+ families = [f["name"] for f in json.loads((src / "system.json").read_text()).get("families", [])]
+ record[name] = dict(source=str(src), source_npz_sha256=sha256(src / "unified_data.npz"),
+ source_episodes=int(total), split=split, source_split_episodes=int(len(val)),
+ rows=pick.tolist(), subset_npz_sha256=sha256(out / "unified_data.npz"),
+ families={families[int(f)]: int(c) for f, c in zip(*np.unique(fam, return_counts=True))}
+ if fam is not None else None)
+ print(name, total, "episodes,", len(val), f"in split {split}, picked", len(pick), record[name]["families"], flush=True)
+ (out_root / "subsets.json").write_text(json.dumps(record, indent=1))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/nrd/summarize.py b/so101_pick_place/code/scripts/so101_pick_place/nrd/summarize.py
new file mode 100644
index 0000000000000000000000000000000000000000..f20c291c2e69415a1ed3bb898ce72b80d8466a94
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/nrd/summarize.py
@@ -0,0 +1,92 @@
+"""Table of the task metrics (data.evaluate reports) of the SO101 NRDs: validation reports of the training runs and
+reports of origin/main's `python -m nedm.contact_nrd.test` (validation re-score and sealed test).
+
+ python -I summarize.py OUT_PREFIX LABEL=FILE[:MODEL][@GROUP] ...
+
+FILE: a training validation.json (MODEL empty) or a test.py --output JSON (MODEL = the --model name).
+GROUP: selected (default), all, or a family name. Writes OUT_PREFIX.json and OUT_PREFIX.md.
+
+Release check of the SO101 pick-and-place study (so101_pick_place/README.md, "The NRD"; reproduce.sh steps
+nrd_val, nrd_strip).
+"""
+import json
+import math
+import sys
+
+ROWS = [ # label, path in the report, scale, format
+ ("episodes", ("episodes",), 1, "{:.0f}"),
+ ("1 s windows: cube position p50 (mm)", ("windows", "1.0", "cube", "pos_m", "median"), 1e3, "{:.2f}"),
+ ("1 s windows: cube position p95 (mm)", ("windows", "1.0", "cube", "pos_m", "p95"), 1e3, "{:.2f}"),
+ ("1 s windows: cube angle p50 (deg)", ("windows", "1.0", "cube", "angle_rad", "median"), 180 / math.pi, "{:.2f}"),
+ ("1 s windows: cube angle p95 (deg)", ("windows", "1.0", "cube", "angle_rad", "p95"), 180 / math.pi, "{:.2f}"),
+ ("1 s windows: arm joint RMS p95 (mrad)", ("windows", "1.0", "arm", "joint_rms_rad", "p95"), 1e3, "{:.2f}"),
+ ("1 s windows (count)", ("windows", "1.0", "windows"), 1, "{:.0f}"),
+ ("4 s from the first state: cube position p50 (mm)", ("free", "target", "cube", "pos_m", "median"), 1e3, "{:.2f}"),
+ ("4 s from the first state: cube position p95 (mm)", ("free", "target", "cube", "pos_m", "p95"), 1e3, "{:.2f}"),
+ ("4 s from the first state: cube angle p95 (deg)", ("free", "target", "cube", "angle_rad", "p95"), 180 / math.pi, "{:.2f}"),
+ ("4 s path RMS of the cube p95 (mm)", ("free", "path_rmse_m", "p95"), 1e3, "{:.2f}"),
+ ("contact events: wrong per recorded event", ("free", "contacts", "all", "event_error_rate"), 1, "{:.3f}"),
+ ("contact switch accuracy", ("free", "contacts", "all", "gate_accuracy"), 1, "{:.4f}"),
+ ("lifted: disagreement (%)", ("free", "flags", "lifted", "disagreement"), 100, "{:.2f}"),
+ ("dropped: disagreement (%)", ("free", "flags", "dropped", "disagreement"), 100, "{:.2f}"),
+ ("finite rollouts", ("finite_fraction",), 1, "{:.4f}"),
+ ("selection score (lower is better)", ("selection_score",), 1, "{:.3f}"),
+]
+
+
+def dig(x, path):
+ for p in path:
+ if not isinstance(x, dict) or p not in x:
+ return None
+ x = x[p]
+ return x
+
+
+def group_of(report, group):
+ if group == "all":
+ return report
+ if group == "selected":
+ return report.get("selected")
+ return (report.get("families") or {}).get(group)
+
+
+def main():
+ out = sys.argv[1]
+ cols, cache = [], {}
+ for item in sys.argv[2:]:
+ label, spec = item.split("=", 1)
+ spec, group = (spec.split("@", 1) + ["selected"])[:2]
+ path, model = (spec.split(":", 1) + [""])[:2]
+ if path not in cache:
+ cache[path] = json.load(open(path))
+ rep = cache[path]["models"][model] if model else cache[path]
+ g = group_of(rep, group)
+ cols.append((label, path, model, group, g))
+ table = {}
+ for name, path, scale, fmt in ROWS:
+ table[name] = {}
+ for label, _, _, _, g in cols:
+ v = dig(g, path) if g is not None else None
+ table[name][label] = None if v is None else v * scale
+ families = {}
+ for label, path, model, group, _ in cols:
+ rep = cache[path]["models"][model] if model else cache[path]
+ for fam, block in (rep.get("families") or {}).items():
+ v = dig(block, ("windows", "1.0", "cube", "pos_m", "p95"))
+ families.setdefault(fam, {})[label] = None if v is None else 1e3 * v
+ lines = ["| Metric | " + " | ".join(c[0] for c in cols) + " |", "|---|" + "---|" * len(cols)]
+ for name, path, scale, fmt in ROWS:
+ lines.append(f"| {name} | " + " | ".join("-" if table[name][c[0]] is None else fmt.format(table[name][c[0]])
+ for c in cols) + " |")
+ lines += ["", "1 s windows, cube position p95 (mm) per family (whole report of each column):", "",
+ "| Family | " + " | ".join(c[0] for c in cols) + " |", "|---|" + "---|" * len(cols)]
+ for fam, vals in families.items():
+ lines.append(f"| {fam} | " + " | ".join("-" if vals.get(c[0]) is None else f"{vals[c[0]]:.2f}" for c in cols) + " |")
+ open(out + ".md", "w").write("\n".join(lines) + "\n")
+ json.dump(dict(columns=[dict(label=c[0], file=c[1], model=c[2], group=c[3]) for c in cols], metrics=table,
+ family_cube_pos_1s_p95_mm=families), open(out + ".json", "w"), indent=1)
+ print("\n".join(lines))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_pick_place/reproduce.sh b/so101_pick_place/code/scripts/so101_pick_place/reproduce.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d9cff80b33683d65c7503a272d056ea87445742c
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/reproduce.sh
@@ -0,0 +1,872 @@
+#!/usr/bin/env bash
+# =====================================================================================================================
+# scripts/so101_pick_place/reproduce.sh: the SO101 pick-and-place chain NRD -> state teacher (PPO in the NRD) ->
+# camera student (online DAgger in the NRD with ray-traced images) -> sim checks -> robot bundle
+# (so101_pick_place/README.md).
+#
+# A real SO101 arm picks a 30 mm cube and places it on a plate. Every training step of every policy ran inside the
+# NRD below; no real image was a training sample. This script repeats the steps from the released files; the robot
+# test itself is a manual step on the robot computer (README "Deploy").
+#
+# NRD (every teacher and student step below runs in it)
+# Hub harryzhang1018/NeDM (dataset), so101_pick_place/nrd/c1_s62/best.pt at the revision pinned in
+# so101_pick_place/release_manifest.json; sha256 2d1a24926d463c5432a8dcb6897c05fe1082f04095c773ec914dd53986d66abc
+# (10,893,663 bytes). Main's nedm.contact_nrd.model.load_model loads it with no code change: it is the
+# study's file (original/best.pt, sha256 f45ee8be...) with the two training-only geometry heads removed;
+# its rollouts are bit-identical to the original's in the training code (README "The NRD").
+# Base so101_pick_place/nrd/c0_s62/ (the start weights of c1_s62; the same layout).
+# Data so101_pick_place/nrd_data/{production_plus,noisy_v1,expert_v2,policy_v3}/ (10.6 GB, --with-nrd-data);
+# sealed test so101_pick_place/nrd_test/ (3,050 scripted episodes, 0.34 GB).
+#
+# Steps (each step reads the released parents unless --parents own and this script's own run exists in OUT/runs)
+# setup contact_nrd/so101_grasp/fetch_sources.py: the MuJoCo Menagerie SO101 model at the pinned revision
+# (vendor/, 27 MB; needs git and github.com); exact
+# download scripts/so101_pick_place/download.py: the Hub files (size + sha256 of every file); --hf-source DIR
+# (or SO101_PP_HF_SOURCE) takes them from a local folder with the Hub layout instead of the Hub
+# geometry kin.save_points and TaskGeometry.from_mujoco rebuild rl_inputs/geometry/ (exact)
+# nrd main's load_model on both NRDs; a 100-step rollout of 4 test episodes; the sha256 of the files
+# nrd_collect the collector (nedm.contact_nrd.collect.so101_grasp) regenerates the first episode of every family
+# of nrd_test/ and compares the arrays (exact); chain: the 4 scripted campaigns in full, their episode
+# counts compared with the released manifests
+# nrd_train base NRD and fine-tune with the training code of commit f6f05c21c (branch so101-pick-place-study;
+# a git worktree under OUT; main's train.py lacks its options); needs --with-nrd-data. Smoke: --smoke
+# runs of the training code on 4 train + 4 validation episodes of every family of each data part
+# nrd_strip scripts/so101_pick_place/nrd/strip_ckpt.py: the main-compatible file of an NRD of the training code
+# (geometry heads removed). Released originals: the result is compared with the released best.pt. Own
+# nrd_train runs: OUT/nrd_main//best.pt; with --parents own the policy stages then run in the own
+# c1. With commit f6f05c21c present: the original in the training code vs the new file in main's code
+# (equiv.py: 100-step rollouts, contact switches, task metrics; validation episodes of the 4 data parts
+# with --with-nrd-data, else test episodes)
+# nrd_test main's python -m nedm.contact_nrd.test on nrd_test/ (smoke: 2 episodes per family), next to the
+# released results/nrd/sealed_test.json (the README numbers); also the own NRDs of nrd_strip
+# nrd_val (--with-nrd-data) main's python -m nedm.contact_nrd.test on the validation episodes (split 1) of
+# production_plus, then the validation / sealed-test table of the README (scripts/so101_pick_place/nrd/)
+# t0 .. t6 the teacher stages (README "Training chain"): t0 decoder PPO from scratch (train_ppo.py), t1 expert
+# data, t2 behaviour cloning, t3 / t4 joint-target PPO, t5 / t6 the robot-round fine-tunes
+# s0 .. s5 the student stages: s0 offline rounds from ImageNet ResNet18, s1 .. s5 online DAgger
+# simcheck scripts/so101_pick_place/check/run_gates.sh on the released (or own) tb10 and on D; gates_summary
+# bundle scripts/so101_policy/real2sim/hw/make_orin_bundle.sh -> OUT/bundle/so101_hw_v13_tb10, compared with the
+# released bundle (MANIFEST.txt)
+# fake the bundle on this machine with a fake robot (no device opened): robot_test.sh check, eval 1 6 and
+# replay of 3 recordings; the replay is repeated with the released bundle and the action chunks are
+# compared
+# robot (--with-robot) the robot result tables from the released logs (build_results.py), next to the
+# released results.json
+# summary the numbers of this run next to the released ones
+#
+# Modes
+# smoke every step of full with tiny sizes (about 5 min on one RTX 5090 once the files are local): a setup check
+# full setup, download, geometry, nrd, nrd_collect, nrd_strip, nrd_test, t6, s5, simcheck, bundle, fake, summary
+# (default): the last teacher and student stages from the released parents (T5, S4), the sim checks, the
+# bundle. About 2 GPU-h (t6 0.8, s5 0.5 + its in-run evaluations, simcheck 21 evaluations) + CPU
+# chain every stage from scratch: nrd_collect (full), nrd_train, nrd_strip, nrd_val, t0 .. t6, s0 .. s5, simcheck,
+# bundle, fake. About 22 GPU-h on one MI350X / MI300X per job (README table); a cluster is advised. Needs
+# --with-nrd-data (and the expert data come from t1; --with-expert-data downloads the released ones). The
+# policy stages run in the own NRD c1 of nrd_train / nrd_strip (else in the released one)
+#
+# Options
+# --steps LIST comma list of steps (default: those of the mode). Without download no file is fetched or checked
+# --out DIR outputs (default artifacts/so101_pick_place_repro; smoke: a new smoke_ folder in it)
+# --hf-source DIR take the Hub files from DIR (a folder with the layout of the Hub folder so101_pick_place/)
+# --parents own|released start each stage from this script's parent run (own) or from the released parent
+# (default released; chain: own)
+# --device DEV torch device (default cuda)
+# --workers N CPU MuJoCo worker processes of the evaluations (default 8)
+# --with-nrd-data also download the 4 NRD data parts (10.6 GB; nrd_val / nrd_train and t1 need them; t0 uses
+# the 28 MB start bank rl_inputs/banks/bank_pp_s0.npz)
+# --with-expert-data also download the released expert data of t1 (0.83 GB; t2 with --parents released)
+# --with-robot also download the robot logs and videos (1.15 GB; robot step)
+# Environment
+# PY Python with torch, torchvision, numpy, scipy, mujoco 3.15.0, warp-lang 1.13.0, newton 1.2.0,
+# huggingface_hub (default python3); requirements-so101-pick-place.txt. The renderer needs an
+# NVIDIA GPU with CUDA (or the ROCm build of Warp on AMD GPUs)
+# SO101_PP_HF_SOURCE default of --hf-source
+# Files: all data go to artifacts/so101_pick_place of this checkout (nedm.so101_policy.paths: the code reads its
+# defaults there; link artifacts/ to another disk if needed). Run records: OUT/runs//.
+# =====================================================================================================================
+set -euo pipefail
+
+CODE="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+PY="${PY:-python3}"
+MODE=full
+STEPS=""
+OUT=""
+SOURCE="${SO101_PP_HF_SOURCE:-}"
+PARENTS=""
+DEVICE=cuda
+WORKERS=8
+WITH_NRD_DATA=0
+WITH_EXPERT=0
+WITH_ROBOT=0
+
+die() { echo "reproduce.sh: $*" >&2; exit 1; }
+log() { echo "[reproduce $(date +%H:%M:%S)] $*"; }
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ full|smoke|chain) MODE="$1" ;;
+ --steps) STEPS="$2"; shift ;;
+ --out) OUT="$2"; shift ;;
+ --hf-source) SOURCE="$2"; shift ;;
+ --parents) PARENTS="$2"; shift ;;
+ --device) DEVICE="$2"; shift ;;
+ --workers) WORKERS="$2"; shift ;;
+ --with-nrd-data) WITH_NRD_DATA=1 ;;
+ --with-expert-data) WITH_EXPERT=1 ;;
+ --with-robot) WITH_ROBOT=1 ;;
+ -h|--help) sed -n '3,/^# =====/p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;
+ *) die "unknown argument $1 (see --help)" ;;
+ esac
+ shift
+done
+
+ALL_STEPS="setup download geometry nrd nrd_collect nrd_train nrd_strip nrd_test nrd_val t0 t1 t2 t3 t4 t5 t6 s0 s1 s2 s3 s4 s5 simcheck bundle fake robot summary"
+case "$MODE" in
+ full) : "${STEPS:=setup,download,geometry,nrd,nrd_test,nrd_strip,nrd_collect,t6,s5,simcheck,bundle,fake,summary}" "${PARENTS:=released}" ;;
+ smoke) : "${STEPS:=setup,download,geometry,nrd,nrd_test,nrd_strip,nrd_collect,t6,s5,simcheck,bundle,fake,summary}" "${PARENTS:=released}" ;;
+ chain) : "${STEPS:=setup,download,nrd_collect,nrd_train,nrd_strip,nrd_val,t0,t1,t2,t3,t4,t5,t6,s0,s1,s2,s3,s4,s5,simcheck,bundle,fake,summary}" "${PARENTS:=own}" ;;
+esac
+case "$PARENTS" in own|released) ;; *) die "--parents must be own or released" ;; esac
+[ "$WITH_ROBOT" = 1 ] && [[ ",$STEPS," != *",robot,"* ]] && STEPS="$STEPS,robot"
+[[ ",$STEPS," == *",robot,"* ]] && WITH_ROBOT=1 # the robot step needs the robot logs in the download
+for s in ${STEPS//,/ }; do [[ " $ALL_STEPS " == *" $s "* ]] || die "unknown step $s ($ALL_STEPS)"; done
+has_step() { case ",$STEPS," in *",$1,"*) return 0 ;; *) return 1 ;; esac; }
+
+OUT="${OUT:-$CODE/artifacts/so101_pick_place_repro}"
+[ "$MODE" = smoke ] && OUT="$OUT/smoke_$(date +%m%d_%H%M%S)"
+A="$CODE/artifacts/so101_pick_place" # the Hub folder so101_pick_place/ after the download
+mkdir -p "$OUT" "$A"
+OUT="$(cd "$OUT" && pwd)"
+RUNS="$OUT/runs"
+TINY=0; [ "$MODE" = smoke ] && TINY=1
+export PYTHONPATH="$CODE/src${PYTHONPATH:+:$PYTHONPATH}" PYTHONUNBUFFERED=1
+cd "$CODE"
+mkdir -p "$RUNS" "$OUT/configs" "$OUT/tasks"
+log "mode $MODE, steps $STEPS, parents $PARENTS, out $OUT, data $A${SOURCE:+, Hub files from $SOURCE}"
+
+# ---------------------------------------------------------------------------------------------------- inputs
+NRD=$A/nrd/c1_s62/best.pt
+T=$A/rl_inputs/tasks
+B=$A/rl_inputs/banks
+SCENE=$CODE/configs/so101_pick_place/real_scene_v2.json # sha256 4bce0b8d... (pinned in every student)
+CALIB=$CODE/configs/so101_pick_place/calib_v1.json # sha256 3b7a2124... (pinned in every student)
+# the scene file names the study's home path of the calibration: every student run passes both (as the runs did)
+SETS=(jaw_lead=0 "scene=\"$SCENE\"" "calib=\"$CALIB\"")
+REL_T=(t0:teacher/t0_nC1_s62_b/model_00171.pt t2:teacher/t2_bc_all/bc.pt t3:teacher/t3_jt_b140/model_00140.pt
+ t4:teacher/t4_jt_h110/model_00110.pt t5:teacher/t5_tppo_roll_v8_s21/model_00200.pt
+ t6:teacher/t6_tppo_v12_fr10_s122/model_00200.pt s0:student/s0_v2_start_s2/r2/last.pt
+ s1:student/s1_v2_online_s18/it_03000.pt s2:student/s2_v2_online2_s28/it_03000.pt
+ s3:student/s3_v4_relabel_s63/it_02000.pt s4:student/s4_v8_roll_s801/it_02000.pt
+ s5:student/s5_v12_tb10_s1210/it_01000.pt)
+OWN_T=(t0:t0_nC1_s62_b/ckpt/model_00171.pt t2:t2_bc_all/bc.pt t3:t3_jt_b140/ckpt/model_00140.pt
+ t4:t4_jt_h110/ckpt/model_00110.pt t5:t5_tppo_roll_v8_s21/ckpt/model_00200.pt
+ t6:t6_tppo_v12_fr10_s122/ckpt/model_00200.pt s0:s0_v2_start_s2/r2/last.pt s1:s1_v2_online_s18/ckpt/it_03000.pt
+ s2:s2_v2_online2_s28/ckpt/it_03000.pt s3:s3_v4_relabel_s63/ckpt/it_02000.pt s4:s4_v8_roll_s801/ckpt/it_02000.pt
+ s5:s5_v12_tb10_s1210/ckpt/it_01000.pt)
+lookup() { local k=$1; shift; for e in "$@"; do [ "${e%%:*}" = "$k" ] && { echo "${e#*:}"; return 0; }; done; return 1; }
+ckpt() { # ckpt : the parent checkpoint (own run if --parents own and it exists, else released)
+ local own; own="$RUNS/$(lookup "$1" "${OWN_T[@]}")"
+ if [ "$PARENTS" = own ] && [ "$TINY" = 0 ]; then
+ [ -f "$own" ] || die "no own checkpoint $own (run step $1, or --parents released)"
+ echo "$own"
+ elif [ "$PARENTS" = own ] && [ -f "$own" ]; then echo "$own"
+ else echo "$A/$(lookup "$1" "${REL_T[@]}")"; fi
+}
+tiny_or() { [ "$TINY" = 1 ] && echo "$1" || echo "$2"; }
+
+# ---------------------------------------------------------------------------------------------------- checks
+if has_step t0 || has_step t1 || has_step t2 || has_step t3 || has_step t4 || has_step t5 || has_step t6 || \
+ has_step s0 || has_step s1 || has_step s2 || has_step s3 || has_step s4 || has_step s5 || has_step simcheck; then
+ "$PY" -c "import torch, torchvision, numpy, scipy, mujoco" 2>/dev/null \
+ || die "$PY needs torch, torchvision, numpy, scipy and mujoco 3.15.0 (requirements-so101-pick-place.txt; set PY)"
+ if [ "$DEVICE" != cpu ]; then
+ "$PY" -c "import torch, sys; sys.exit(0 if torch.cuda.is_available() else 1)" || die "no GPU for --device $DEVICE"
+ fi
+fi
+if has_step s0 || has_step s1 || has_step s2 || has_step s3 || has_step s4 || has_step s5 || has_step simcheck; then
+ "$PY" -c "import warp, newton" 2>/dev/null || die "$PY needs warp-lang 1.13.0 and newton 1.2.0 for the renderer"
+fi
+
+# ---------------------------------------------------------------------------------------------------- setup
+if has_step setup; then
+ log "setup: MuJoCo Menagerie SO101 at the pinned revision (contact_nrd/so101_grasp/vendor/)"
+ "$PY" -I contact_nrd/so101_grasp/fetch_sources.py
+fi
+
+# ---------------------------------------------------------------------------------------------------- download
+DL_GROUPS=nrd,nrd_test,teacher,student,rl_inputs,results,bundle,recordings
+[ "$WITH_NRD_DATA" = 1 ] && DL_GROUPS="$DL_GROUPS,nrd_data"
+[ "$WITH_EXPERT" = 1 ] && DL_GROUPS="$DL_GROUPS,expert_data"
+[ "$WITH_ROBOT" = 1 ] && DL_GROUPS="$DL_GROUPS,robot"
+if has_step download; then
+ log "download + sha256 check ($DL_GROUPS)"
+ "$PY" -I scripts/so101_pick_place/download.py --groups "$DL_GROUPS" --dest "$CODE/artifacts" --quiet \
+ ${SOURCE:+--source "$SOURCE"}
+fi
+
+# smoke task files: the first rows of the released sets (dev100 rows 0-3 = tasks --kind C --n 4 --dev, bit for bit)
+TS="$T"
+if [ "$TINY" = 1 ] && [ ! -f "$T/dev100.npz" ]; then
+ for s in t1 t2 t3 t4 t5 t6 s0 s1 s2 s3 s4 s5; do
+ has_step $s && die "no task files in $T (step $s): run the download step first"
+ done
+elif [ "$TINY" = 1 ]; then
+ "$PY" - "$T" "$OUT/tasks" <<'EOF'
+import sys
+from pathlib import Path
+import numpy as np
+src, out = Path(sys.argv[1]), Path(sys.argv[2])
+for name, n in (("dev100", 4), ("home45_dev100", 4), ("home_dev100", 4), ("train_mix45_16k", 256)):
+ if not (src / f"{name}.npz").is_file():
+ continue
+ t = dict(np.load(src / f"{name}.npz", allow_pickle=True))
+ N = len(t["seeds"])
+ np.savez(out / f"{name}.npz", **{k: (v[:n] if np.ndim(v) and len(v) == N else v) for k, v in t.items()})
+EOF
+ TS="$OUT/tasks"
+fi
+
+# ---------------------------------------------------------------------------------------------------- geometry
+if has_step geometry; then
+ log "geometry: rebuild the kin points and the task geometry from MuJoCo, compare with rl_inputs/geometry/"
+ mkdir -p "$OUT/geometry"
+ "$PY" - "$A/rl_inputs/geometry" "$OUT/geometry" <<'EOF'
+import hashlib, sys
+from pathlib import Path
+import numpy as np
+from nedm.so101_policy import kin, task
+rel, out = Path(sys.argv[1]), Path(sys.argv[2])
+kin.save_points(out / "kin_points_v1.npz")
+task.TaskGeometry.from_mujoco().save(out / "task_geom_v2.npz")
+sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
+for f in ("kin_points_v1.npz", "task_geom_v2.npz"):
+ a, b = np.load(out / f), np.load(rel / f)
+ same = sorted(a.files) == sorted(b.files) and all(np.array_equal(a[k], b[k]) for k in a.files)
+ print(f"{f}: arrays {'EQUAL' if same else 'DIFFER'} to the released file; sha256 "
+ f"{'equal' if sha(out / f) == sha(rel / f) else 'differs (zip records)'}")
+ if not same:
+ sys.exit(f"{f}: the rebuilt arrays differ from rl_inputs/geometry/{f}")
+EOF
+fi
+
+# ---------------------------------------------------------------------------------------------------- nrd
+if has_step nrd; then
+ log "nrd: main's nedm.contact_nrd.model.load_model on c1_s62 and c0_s62, 100-step rollouts of 4 test episodes"
+ "$PY" - "$A" "$DEVICE" <<'EOF'
+import hashlib, json, sys
+from pathlib import Path
+import torch
+from nedm.contact_nrd import data as D
+from nedm.contact_nrd.model import load_model
+A, dev = Path(sys.argv[1]), sys.argv[2]
+man = json.loads((Path("so101_pick_place/release_manifest.json")).read_text())["files"]
+data = None
+for run in ("c1_s62", "c0_s62"):
+ f = A / f"nrd/{run}/best.pt"
+ sha = hashlib.sha256(f.read_bytes()).hexdigest()
+ model, packet = load_model(str(f), dev)
+ n = sum(p.numel() for p in model.parameters())
+ if data is None:
+ root = A / "nrd_test"
+ data = D.step_average_rates(D.load_data(str(root), dev, model_step_s=model.dt), set(model.config["integrate"]["kinds"]))
+ s = data["stride"]
+ st, act = data["states"][:4, ::s], data["actions"][:4, ::s]
+ with torch.no_grad():
+ traj = model.rollout(st[:, 0], act[:, :100])
+ ic = [b["name"] for b in model.system["bodies"] if b["moving"]].index("cube")
+ err = (traj[:, 100, ic, :3] - st[:, 100, ic, :3]).norm(dim=-1) * 1e3
+ print(f"{run}: sha256 {sha[:16]} ({'= manifest' if sha == man['so101_pick_place/nrd/' + run + '/best.pt']['sha256'] else 'NOT the manifest'}), "
+ f"{n:,} parameters, update {packet.get('update')}, rollout {tuple(traj.shape)} finite {bool(torch.isfinite(traj).all())}, "
+ f"cube position error at 2 s (mm): {[round(float(e), 2) for e in err]}")
+EOF
+fi
+
+# ---------------------------------------------------------------------------------------------------- nrd_collect
+if has_step nrd_collect; then
+ log "nrd_collect: regenerate the first episode of every family of nrd_test/ with the collector (exact check)"
+ "$PY" -P - "$A/nrd_test" <<'EOF'
+import json, sys, time
+import numpy as np
+from nedm.contact_nrd.collect import so101_grasp as g
+data = sys.argv[1]
+cfg = g.load_config(); s = g.Scene(cfg)
+master = cfg["campaigns"]["test"]["master_seed"]
+with np.load(f"{data}/unified_data.npz") as f:
+ fam_all, fidx, lengths, seeds = f["family"], f["family_index"], f["lengths"], f["seed"]
+ rows = sorted(int(np.flatnonzero(fam_all == k)[0]) for k in np.unique(fam_all))
+ a = {key: f[key][rows] for key in ("arm", "cube", "action", "contacts")}
+same = []
+for j, row in enumerate(rows):
+ ep = g.make_episode(s, int(fam_all[row]), int(fidx[row]), master)
+ n = int(lengths[row])
+ ok = (len(ep["action"]) == n and int(ep["seed"]) == int(seeds[row])
+ and np.array_equal(ep["states"]["arm"][:n].astype(np.float32), a["arm"][j, :n])
+ and np.array_equal(ep["states"]["cube"][:n].astype(np.float32), a["cube"][j, :n])
+ and np.array_equal(ep["action"][:n].astype(np.float32), a["action"][j, :n])
+ and np.array_equal(ep["contacts"], a["contacts"][j, :n - 1]))
+ same.append(ok)
+ print(f" {cfg['families'][int(fam_all[row])]['name']:14s} row {row}: {'identical' if ok else 'DIFFERENT'}", flush=True)
+print(f"{sum(same)} of {len(same)} test episodes regenerated bit for bit (campaign test, master seed {master})")
+if not all(same):
+ sys.exit("the collector does not regenerate the released test episodes on this machine (MuJoCo version?)")
+EOF
+ if [ "$MODE" = chain ]; then
+ for c in production extra noisy_v1 test; do
+ log "nrd_collect: campaign $c (CPU MuJoCo; about 15 min on 24 workers each)"
+ FAM=() # the released extra part: 4 of the campaign's 13 families (production_plus/extra_manifest.json)
+ [ "$c" = extra ] && FAM=(--families one_sided near_miss weak_closure push)
+ [ -f "$OUT/nrd_data/$c/system.json" ] || "$PY" -P -m nedm.contact_nrd.collect.so101_grasp collect \
+ --campaign "$c" --workers "$WORKERS" --out "$OUT/nrd_data/$c" "${FAM[@]}"
+ "$PY" -P -m nedm.contact_nrd.collect.validate "$OUT/nrd_data/$c" --output "$OUT/nrd_data/$c/validate.json"
+ done
+ "$PY" - "$OUT/nrd_data" "$A" <<'EOF'
+import json, sys
+from pathlib import Path
+out, A = Path(sys.argv[1]), Path(sys.argv[2])
+REL = {"production": "nrd_data/production_plus/production_manifest.json", "extra": "nrd_data/production_plus/extra_manifest.json",
+ "noisy_v1": "nrd_data/noisy_v1/manifest.json", "test": "nrd_test/manifest.json"}
+bad = []
+for c, rel in REL.items():
+ mine = json.loads((out / c / "manifest.json").read_text())["episode_counts"]
+ ref = json.loads((A / rel).read_text())["episode_counts"]
+ print(f"nrd_collect {c}: {sum(mine.values())} episodes in {len(mine)} families (released {sum(ref.values())} in "
+ f"{len(ref)}): {'same counts' if mine == ref else 'DIFFERENT counts'}")
+ bad += [c] if mine != ref else []
+if bad:
+ sys.exit(f"nrd_collect: episode counts differ from the release in {bad}")
+EOF
+ log "nrd_collect: expert_v2 and policy_v3 are not re-collected (their collector is in no commit / needs the 7 "
+ log " policies; README): the released parts are used by nrd_train"
+ fi
+fi
+
+# ---------------------------------------------------------------------------------------------------- nrd_train
+# The training options of these two NRDs are not in main's train.py: train with the study code (README).
+ST="$OUT/study_f6f05c21c"
+study_tree() { # study_tree [optional]: a git worktree of commit f6f05c21c (the NRD training code) at $ST
+ [ -d "$ST/src/nedm/contact_nrd" ] && return 0
+ if ! git -C "$CODE" cat-file -e f6f05c21c^{commit} 2>/dev/null; then
+ git -C "$CODE" fetch origin so101-pick-place-study 2>/dev/null || true
+ fi
+ if ! git -C "$CODE" cat-file -e f6f05c21c^{commit} 2>/dev/null; then
+ [ "${1:-}" = optional ] && return 1
+ die "commit f6f05c21c not found: git fetch origin so101-pick-place-study"
+ fi
+ # no LFS files: the training code needs none of the .pt files that f6f05c21c tracks under artifacts/
+ GIT_LFS_SKIP_SMUDGE=1 git -C "$CODE" worktree add --quiet --detach "$ST" f6f05c21c || {
+ [ "${1:-}" = optional ] && return 1; die "git worktree add of commit f6f05c21c failed"; }
+ # f6f05c21c tracks files under artifacts/: link only the data folder of this release into it
+ mkdir -p "$ST/artifacts"
+ ln -sfn "$CODE/artifacts/so101_pick_place" "$ST/artifacts/so101_pick_place"
+ cp -r "$CODE/contact_nrd/so101_grasp/vendor" "$ST/contact_nrd/so101_grasp/" 2>/dev/null || true
+}
+need_nrd_data() { # need_nrd_data : the 4 NRD data parts of the Hub (--with-nrd-data)
+ local d
+ for d in production_plus noisy_v1 expert_v2 policy_v3; do
+ [ -f "$A/nrd_data/$d/unified_data.npz" ] \
+ || die "step $1 needs the NRD data ($A/nrd_data/$d missing): add --with-nrd-data to the download"
+ done
+}
+if has_step nrd_train; then
+ need_nrd_data nrd_train
+ study_tree
+ SMOKE_FLAG=()
+ ND="$A/nrd_data"
+ if [ "$TINY" = 1 ]; then # --smoke runs of the training code on 4 train + 4 validation episodes per family
+ SMOKE_FLAG=(--smoke)
+ ND="$OUT/nrd_data_smoke"
+ [ -f "$ND/subsets.json" ] || "$PY" -I scripts/so101_pick_place/nrd/subsets.py "$ND" 4 --split family \
+ production_plus="$A/nrd_data/production_plus" noisy_v1="$A/nrd_data/noisy_v1" \
+ expert_v2="$A/nrd_data/expert_v2" policy_v3="$A/nrd_data/policy_v3" > "$OUT/nrd_data_smoke.log"
+ fi
+ PP="$ND/production_plus"
+ if [ "$TINY" = 0 ] && [ -f "$OUT/nrd_data/production/system.json" ] && [ -f "$OUT/nrd_data/extra/system.json" ]; then
+ PP="$OUT/nrd_data/production_plus" # the own scripted campaigns of nrd_collect (chain)
+ [ -f "$PP/system.json" ] || (cd "$ST" && PYTHONPATH="$ST/src" "$PY" -P scripts/contact_nrd/merge_data.py "$PP" \
+ "$OUT/nrd_data/production" "$OUT/nrd_data/extra")
+ fi
+ log "nrd_train: base NRD c0_s62 from scratch on $PP (about 8.5 GPU-h; the study ran it with the uncommitted code of provenance/code_v16_base_nrd.tar.gz: recipe only)"
+ # seed 62 = the run's seed (base_c0.json says 61; the run's command line set 62, as here)
+ [ -f "$RUNS/nrd_c0_s62/complete.json" ] || (cd "$ST" && PYTHONPATH="$ST/src" "$PY" -P -m nedm.contact_nrd.train \
+ --data "$PP" --seed 62 --config "$CODE/configs/so101_pick_place/nrd/base_c0.json" --output "$RUNS/nrd_c0_s62" \
+ --device "$DEVICE" "${SMOKE_FLAG[@]}")
+ M="$OUT/nrd_data/merged_r3_pp_noisy_expert_policy_x2.5"
+ [ "$TINY" = 1 ] && M="$ND/merged"
+ log "nrd_train: merge production_plus + noisy_v1 + expert_v2 + policy_v3 (train rows of policy_v3 x 2.5) -> $M (13.6 GB at full size)"
+ [ -f "$M/system.json" ] || (cd "$ST" && PYTHONPATH="$ST/src" "$PY" -P scripts/so101_policy/collect_round.py merge \
+ --base "$PP" --extra "$ND/noisy_v1" "$ND/expert_v2" "$ND/policy_v3" \
+ --repeat "$ND/policy_v3=2.5" --out "$M")
+ # array-level check of the merge: the split counts vs the fine-tune's run record (np.savez stores zip times, so the
+ # file's sha256 cannot equal the record's data_sha256 6ef821f0...)
+ "$PY" - "$M/unified_data.npz" "$A/nrd/c1_s62/run_config.json" "$TINY" <<'EOF'
+import json, sys
+import numpy as np
+with np.load(sys.argv[1]) as f:
+ sp = f["splits"]
+rec = json.load(open(sys.argv[2]))
+n0, n1 = int((sp == 0).sum()), int((sp == 1).sum())
+print(f"merged data: {len(sp)} episodes, train {n0}, validation {n1} (released fine-tune record: train "
+ f"{rec['training_episodes']}, validation {rec['validation_episodes']})")
+if sys.argv[3] == "0" and (n0, n1) != (rec["training_episodes"], rec["validation_episodes"]):
+ sys.exit("the merged data do not have the episode counts of the released fine-tune")
+EOF
+ # init_from as an absolute path (the training runs in the study worktree): the own base run with --parents own,
+ # else the released original base NRD (nrd/c0_s62/original/best.pt)
+ FT="$OUT/configs/ft_c1_s62.json"
+ if [ "$PARENTS" = own ] && [ -f "$RUNS/nrd_c0_s62/best.pt" ]; then INIT_RUN="$RUNS/nrd_c0_s62"; INIT_CK=best.pt
+ else INIT_RUN="$A/nrd/c0_s62"; INIT_CK=original/best.pt; fi
+ "$PY" - "$CODE/configs/so101_pick_place/nrd/ft_c1_s62.json" "$FT" "$INIT_RUN" "$INIT_CK" <<'EOF'
+import json, sys
+c = json.load(open(sys.argv[1]))
+c["init_from"].update(run=sys.argv[3], checkpoint=sys.argv[4])
+json.dump(c, open(sys.argv[2], "w"), indent=1)
+EOF
+ log "nrd_train: fine-tune c1_s62 (20,000 updates, best at update 2,500; 1.6 GPU-h); init_from $INIT_RUN/$INIT_CK"
+ [ -f "$RUNS/nrd_c1_s62/complete.json" ] || (cd "$ST" && PYTHONPATH="$ST/src" "$PY" -P -m nedm.contact_nrd.train \
+ --data "$M" --output "$RUNS/nrd_c1_s62" --config "$FT" --device "$DEVICE" "${SMOKE_FLAG[@]}")
+fi
+
+# ---------------------------------------------------------------------------------------------------- nrd_strip
+if has_step nrd_strip; then
+ mkdir -p "$OUT/nrd_strip"
+ for r in c1_s62 c0_s62; do # the released originals: the new file vs the released main-compatible best.pt
+ log "nrd_strip: $r: strip_ckpt.py on the released original, compared with the released best.pt"
+ mkdir -p "$OUT/nrd_strip/$r"
+ "$PY" -I scripts/so101_pick_place/nrd/strip_ckpt.py "$A/nrd/$r/original/best.pt" "$OUT/nrd_strip/$r/best.pt" \
+ "$OUT/nrd_strip/$r.json" "$A/nrd/$r/best.pt" > "$OUT/nrd_strip/$r.log" \
+ || die "nrd_strip: $r differs from the released best.pt ($OUT/nrd_strip/$r.json)"
+ "$PY" - "$OUT/nrd_strip/$r.json" "$r" <<'EOF'
+import json, sys
+r = json.load(open(sys.argv[1]))
+same = r["bytes_equal_to_expected"]
+print(f" {sys.argv[2]}: kept entries equal to the original: {r['all_kept_entries_equal']}; bytes equal to the released "
+ f"best.pt: {same}" + ("" if same else f" (every entry equal: {r['entries_equal_to_expected']}; the bytes depend on the torch version)"))
+EOF
+ done
+ for r in c1_s62 c0_s62; do # own nrd_train runs -> main-compatible files for the tests and the policy stages
+ [ -f "$RUNS/nrd_$r/best.pt" ] || continue
+ log "nrd_strip: own run $RUNS/nrd_$r -> $OUT/nrd_main/$r/best.pt"
+ mkdir -p "$OUT/nrd_main/$r"
+ "$PY" -I scripts/so101_pick_place/nrd/strip_ckpt.py "$RUNS/nrd_$r/best.pt" "$OUT/nrd_main/$r/best.pt" \
+ "$OUT/nrd_main/$r.json" > "$OUT/nrd_main/$r.log" || die "nrd_strip: own $r ($OUT/nrd_main/$r.json)"
+ done
+ # the original in the training code vs the new file in main's code: 100-step rollouts, contact switches, metrics
+ if study_tree optional; then
+ EQ="$OUT/nrd_strip/equiv"; mkdir -p "$EQ"
+ N_EQ=$(tiny_or 4 64)
+ if [ -f "$A/nrd_data/policy_v3/unified_data.npz" ]; then # as the release: 64 validation episodes of each part
+ N_EQ=64 # (also in smoke: the per-family task metrics need every scored family with 1 s windows)
+ [ -f "$EQ/data/subsets.json" ] || "$PY" -I scripts/so101_pick_place/nrd/subsets.py "$EQ/data" "$N_EQ" \
+ production_plus="$A/nrd_data/production_plus" noisy_v1="$A/nrd_data/noisy_v1" \
+ expert_v2="$A/nrd_data/expert_v2" policy_v3="$A/nrd_data/policy_v3" > "$EQ/subsets.log"
+ SETS_EQ=(production_plus="$EQ/data/production_plus" noisy_v1="$EQ/data/noisy_v1"
+ expert_v2="$EQ/data/expert_v2" policy_v3="$EQ/data/policy_v3")
+ else # without the NRD data: test episodes
+ [ -f "$EQ/data/subsets.json" ] || "$PY" -I scripts/so101_pick_place/nrd/subsets.py "$EQ/data" "$N_EQ" \
+ --split 2 nrd_test="$A/nrd_test" > "$EQ/subsets.log"
+ SETS_EQ=(nrd_test="$EQ/data/nrd_test")
+ fi
+ PAIRS=()
+ for r in c1_s62 c0_s62; do
+ log "nrd_strip: $r: original/best.pt in the training code (f6f05c21c) vs best.pt in main's code ($N_EQ episodes per folder, $DEVICE)"
+ "$PY" -I scripts/so101_pick_place/nrd/equiv.py "$ST/src" "$A/nrd/$r/original/best.pt" "$DEVICE" \
+ "$EQ/${r}_train" "${SETS_EQ[@]}" > "$EQ/${r}_train.log"
+ "$PY" -I scripts/so101_pick_place/nrd/equiv.py "$CODE/src" "$A/nrd/$r/best.pt" "$DEVICE" \
+ "$EQ/${r}_main" "${SETS_EQ[@]}" > "$EQ/${r}_main.log"
+ PAIRS+=("$EQ/${r}_train" "$EQ/${r}_main")
+ done
+ "$PY" -I scripts/so101_pick_place/nrd/equiv_compare.py "$EQ/equiv.json" "${PAIRS[@]}" > "$EQ/equiv.log" \
+ || die "nrd_strip: equiv_compare.py failed ($EQ/equiv.log)"
+ echo " original (training code) vs main-compatible (main's code): $(tail -1 "$EQ/equiv.log") ($EQ/equiv.json)"
+ grep -q "^ALL EQUAL" "$EQ/equiv.log" || die "nrd_strip: the main-compatible files do not step like the originals"
+ else
+ log "nrd_strip: commit f6f05c21c not available (git fetch origin so101-pick-place-study): no training-code comparison"
+ fi
+fi
+# the NRD of the policy stages: the own c1 with --parents own when nrd_strip made it, else the released one
+if [ "$PARENTS" = own ] && [ -f "$OUT/nrd_main/c1_s62/best.pt" ]; then NRD="$OUT/nrd_main/c1_s62/best.pt"; fi
+NRD_MODELS=(c1_s62="$A/nrd/c1_s62" c0_s62="$A/nrd/c0_s62")
+for r in c1_s62 c0_s62; do
+ if [ -f "$OUT/nrd_main/$r/best.pt" ]; then NRD_MODELS+=("own_$r=$OUT/nrd_main/$r"); fi
+done
+
+# ---------------------------------------------------------------------------------------------------- nrd_test
+if has_step nrd_test; then
+ D_TEST="$A/nrd_test"
+ if [ "$TINY" = 1 ]; then # 2 episodes per family (24 of 3,050)
+ D_TEST="$OUT/nrd_test_subset"
+ "$PY" - "$A/nrd_test" "$D_TEST" <<'EOF'
+import json, shutil, sys
+from pathlib import Path
+import numpy as np
+src, out = Path(sys.argv[1]), Path(sys.argv[2])
+out.mkdir(parents=True, exist_ok=True)
+with np.load(src / "unified_data.npz") as f:
+ fam = f["family"]
+ rows = sorted(r for k in np.unique(fam) for r in np.flatnonzero(fam == k)[:2].tolist())
+ np.savez(out / "unified_data.npz", **{k: f[k][rows] for k in f.files})
+shutil.copy2(src / "system.json", out / "system.json")
+(out / "rows.json").write_text(json.dumps(rows))
+EOF
+ fi
+ log "nrd_test: python -m nedm.contact_nrd.test on $D_TEST (main's code, unchanged)"
+ mkdir -p "$OUT/nrd"
+ "$PY" -P -m nedm.contact_nrd.test --data "$D_TEST" --model "${NRD_MODELS[@]}" \
+ --output "$OUT/nrd/nrd_test.json" --device "$DEVICE" > "$OUT/nrd/nrd_test.txt"
+ "$PY" - "$OUT/nrd/nrd_test.json" "$A/results/nrd/sealed_test.json" "$D_TEST" <<'EOF'
+import json, sys
+from pathlib import Path
+mine, ref = json.loads(Path(sys.argv[1]).read_text()), json.loads(Path(sys.argv[2]).read_text())
+rows_f = Path(sys.argv[3]) / "rows.json"
+rows = json.loads(rows_f.read_text()) if rows_f.exists() else None
+for m in mine["models"]:
+ if m not in ref["models"]: # own NRDs (nrd_strip): no released counterpart
+ print(f"{m}: selected score {mine['models'][m]['selected']['selection_score']:.4f}")
+ continue
+ a, b = mine["models"][m], ref["models"][m]
+ if rows is None:
+ print(f"{m}: selected score {a['selected']['selection_score']:.4f} (released {b['selected']['selection_score']:.4f}); "
+ f"all {a['selection_score']:.4f} (released {b['selection_score']:.4f})")
+ else: # per-episode free-rollout errors of the same episodes (the batch differs: float noise possible)
+ def flat(x, p=""):
+ if isinstance(x, dict):
+ for k, v in x.items():
+ yield from flat(v, f"{p}/{k}")
+ elif isinstance(x, (int, float)) and not isinstance(x, bool):
+ yield p, float(x)
+ diff, n = 0.0, 0
+ for j, r in enumerate(rows):
+ ea, eb = dict(flat(a["per_episode"][j]["free"])), dict(flat(b["per_episode"][r]["free"]))
+ for k in ea.keys() & eb.keys():
+ diff, n = max(diff, abs(ea[k] - eb[k])), n + 1
+ print(f"{m}: {len(rows)} test episodes, {n} per-episode free-rollout values vs the released test: max |diff| {diff:.3g}")
+EOF
+fi
+
+# ---------------------------------------------------------------------------------------------------- nrd_val
+if has_step nrd_val; then
+ [ -f "$A/nrd_data/production_plus/unified_data.npz" ] \
+ || die "step nrd_val needs production_plus: add --with-nrd-data to the download"
+ V_DIR="$OUT/nrd_val"
+ log "nrd_val: the validation episodes (split 1) of production_plus -> $V_DIR (smoke: 24 of 2,853)"
+ [ -f "$V_DIR/subsets.json" ] || "$PY" -I scripts/so101_pick_place/nrd/subsets.py "$V_DIR" "$(tiny_or 24 0)" \
+ production_plus="$A/nrd_data/production_plus" > "$OUT/nrd_val.log"
+ log "nrd_val: python -m nedm.contact_nrd.test on them (main's code, unchanged)"
+ mkdir -p "$OUT/nrd"
+ "$PY" -P -m nedm.contact_nrd.test --data "$V_DIR/production_plus" --model "${NRD_MODELS[@]}" \
+ --output "$OUT/nrd/validation.json" --device "$DEVICE" > "$OUT/nrd/validation.txt"
+ TEST_JSON="$A/results/nrd/sealed_test.json" # the README table: validation next to the sealed test
+ [ "$TINY" = 0 ] && [ -f "$OUT/nrd/nrd_test.json" ] && TEST_JSON="$OUT/nrd/nrd_test.json"
+ COLS=("c0 validation=$OUT/nrd/validation.json:c0_s62" "c0 test=$TEST_JSON:c0_s62"
+ "c1 validation=$OUT/nrd/validation.json:c1_s62" "c1 test=$TEST_JSON:c1_s62")
+ for r in c1_s62 c0_s62; do
+ if [ -f "$OUT/nrd_main/$r/best.pt" ]; then COLS+=("own $r validation=$OUT/nrd/validation.json:own_$r"); fi
+ done
+ "$PY" -I scripts/so101_pick_place/nrd/summarize.py "$OUT/nrd/summary_selected" "${COLS[@]}" > /dev/null
+ "$PY" - "$OUT/nrd/validation.json" "$A/results/nrd/validation_rescore.json" "$TINY" <<'EOF'
+import json, sys
+mine, ref = (json.load(open(p))["models"] for p in sys.argv[1:3])
+for m, v in mine.items():
+ r = ref.get(m)
+ note = "" if not r else (f" (released validation re-score {r['selected']['selection_score']:.4f}"
+ + ("; smoke: 24 episodes only)" if sys.argv[3] == "1" else ")"))
+ print(f"nrd_val {m}: selected score {v['selected']['selection_score']:.4f}{note}")
+EOF
+ echo "table: $OUT/nrd/summary_selected.md"
+fi
+
+# ---------------------------------------------------------------------------------------------------- teachers
+# smoke env configs: the stage's env config with 200-step episodes
+smoke_env() { # smoke_env -> a copy with horizon 200 (smoke) or the config itself
+ if [ "$TINY" = 1 ]; then
+ local o="$OUT/configs/$(basename "$1")"
+ "$PY" -c "import json, sys; c = json.load(open(sys.argv[1])); c['horizon'] = 200; json.dump(c, open(sys.argv[2], 'w'), indent=1)" "$1" "$o"
+ echo "$o"
+ else echo "$1"; fi
+}
+teacher_ppo() { # teacher_ppo
+ # [ (then also --dev-match-env)]
+ local run="$RUNS/$1" init="$2" ecfg; ecfg="$(smoke_env "$3")"; local tc="$4" cw="$5" it="$6" every="$7" seed="$8"
+ shift 8
+ local dev=(--dev-tasks "$1"); shift
+ [ $# -gt 0 ] && dev+=(--dev-tasks-extra "$@" --dev-match-env)
+ local size=(--envs 8192 --iterations "$it" --eval-every "$every" --save-every "$every" --critic-warmup "$cw")
+ [ "$TINY" = 1 ] && size=(--envs 256 --iterations 2 --eval-every 2 --save-every 2 --critic-warmup 1)
+ [ -e "$run/ckpt" ] && { log "skip $run (exists)"; return 0; }
+ log "teacher PPO $(basename "$run"): init $init, env $ecfg"
+ env -u NEDM_SO101_DYN "$PY" -P scripts/so101_policy/vision_viral_teacher.py ppo --nrd-ckpt "$NRD" --init "$init" \
+ --env-config "$ecfg" --train-config "$tc" "${size[@]}" "${dev[@]}" --seed "$seed" --out "$run" \
+ --mj-python "$PY" --device "$DEVICE"
+}
+if has_step t0; then
+ run="$RUNS/t0_nC1_s62_b"
+ # the study job stopped at its time limit (--max-hours 3.3) after 171 iterations on one MI350X; here the run
+ # stops at 171 iterations (model_00171.pt) on any GPU
+ size=(--num-envs 16384 --max-iterations 171 --max-hours 1000 --val-every 10 --save-every 10 --val-n 512 --print-every 5)
+ [ "$TINY" = 1 ] && size=(--num-envs 256 --max-iterations 1 --val-every 1 --save-every 1 --val-n 16 --print-every 1)
+ log "t0: decoder PPO from scratch in the NRD (train_ppo.py; 171 iterations as the study: 3.3 h on one MI350X, model_00171)"
+ [ -e "$run/done.json" ] || "$PY" -P scripts/so101_policy/train_ppo.py train --world nrd --out "$run" \
+ --env-cfg configs/so101_policy/ppo/env_v2.json --train-cfg configs/so101_policy/ppo/train_v2.json \
+ --curriculum configs/so101_policy/ppo/curriculum_tol_v3.json "${size[@]}" --starts "$B/bank_pp_s0.npz" \
+ --set env.geom_path="\"$A/rl_inputs/geometry/task_geom_v2.npz\"" env.kin_points="\"$A/rl_inputs/geometry/kin_points_v1.npz\"" \
+ --ckpt "$NRD" --seed 2 --set 'env.grasp_shaping={"w_x":20.0,"w_y":10.0,"w_yaw":2.0}' algorithm.desired_kl=0.02 \
+ --device "$DEVICE"
+fi
+if has_step t1; then
+ [ -f "$A/nrd_data/production_plus/unified_data.npz" ] \
+ || die "step t1 reads its start states from nrd_data/production_plus (split 0): add --with-nrd-data to the download"
+ log "t1: expert data, T0 + the action decoder in the NRD (recipe only: the study code was not committed)"
+ mkdir -p "$RUNS/t1_expert_data"
+ for spec in "e0_n1 1.0 0 0" "e1_n2 2.0 1 8192" "e2_n15 1.5 2 16384"; do
+ set -- $spec
+ [ -f "$RUNS/t1_expert_data/$1.npz" ] || "$PY" -P scripts/so101_policy/vision_viral_teacher.py expert \
+ --teacher "$(ckpt t0)" --nrd-ckpt "$NRD" --n "$(tiny_or 64 8192)" --noise "$2" --noise-frac 0.5 --seed "$3" \
+ --first "$4" --mj-python "$PY" --device "$DEVICE" --out "$RUNS/t1_expert_data/$1.npz"
+ done
+fi
+if has_step t2; then
+ E="$RUNS/t1_expert_data" # own t1 data if this run made them (smoke: always), else the released data
+ { [ "$PARENTS" = released ] && [ "$TINY" = 0 ]; } || [ ! -f "$E/e2_n15.npz" ] && E="$A/teacher/t1_expert_data"
+ [ -f "$E/e2_n15.npz" ] || die "t2 needs the expert data: run step t1, or download them (--with-expert-data)"
+ log "t2: behaviour cloning of the joint-target teacher on $E (recipe only)"
+ [ -f "$RUNS/t2_bc_all/bc.pt" ] || "$PY" -P scripts/so101_policy/vision_viral_teacher.py bc \
+ --data "$E/e0_n1.npz" "$E/e1_n2.npz" "$E/e2_n15.npz" --steps "$(tiny_or 20 60000)" --batch "$(tiny_or 512 8192)" \
+ --hidden 1024 512 256 --lr 0.001 --seed 0 --device "$DEVICE" --out "$RUNS/t2_bc_all"
+fi
+# t3 / t4: the study planned 400 / 200 iterations and cancelled the jobs; the adaptive-lr loop does not depend on the
+# planned count, so this script stops at the released checkpoint's iteration (140 / 110)
+if has_step t3; then
+ teacher_ppo t3_jt_b140 "$(ckpt t2)" configs/so101_pick_place/teacher/env_jt_b140.json \
+ configs/so101_policy/ppo/joint_ppo_v3.json 20 140 10 0 "$TS/dev100.npz"
+fi
+if has_step t4; then
+ teacher_ppo t4_jt_h110 "$(ckpt t3)" configs/so101_pick_place/teacher/env_jt_h110.json \
+ configs/so101_policy/ppo/joint_ppo_v3.json 5 110 10 0 "$TS/dev100.npz"
+fi
+if has_step t5; then
+ teacher_ppo t5_tppo_roll_v8_s21 "$(ckpt t4)" configs/so101_policy/ppo/r2s/teacher_roll_v8.json \
+ configs/so101_policy/ppo/r2s/joint_ppo_v3_kl02.json 20 200 20 21 "$TS/home45_dev100.npz" "$TS/dev100.npz"
+fi
+if has_step t6; then
+ teacher_ppo t6_tppo_v12_fr10_s122 "$(ckpt t5)" configs/so101_policy/ppo/r2s/teacher_roll_v12_fr10.json \
+ configs/so101_policy/ppo/r2s/joint_ppo_v3_kl02.json 20 200 20 122 "$TS/home45_dev100.npz" "$TS/dev100.npz" \
+ "$TS/home_dev100.npz"
+fi
+
+# ---------------------------------------------------------------------------------------------------- students
+GUARD=("$T/fresh100.npz" "$T/home45_fresh100.npz")
+student_online() { # student_online [--oset ...]
+ local run="$RUNS/$1" init="$2" jt="$3" oc="$4" seed="$5"; shift 5
+ local oset=("$@") size=(--render-worlds 128 --eval-workers 16)
+ local ev=(--eval-tasks "$T/dev100.npz" "$T/home45_dev100.npz")
+ if [ "$TINY" = 1 ]; then
+ size=(--render-worlds 16 --eval-workers 2); ev=(--eval-tasks "$TS/dev100.npz")
+ oset=(--oset iterations=12 eval_every=12 save_every=12 log_every=4 envs=64 buffer=4096
+ $(for o in "$@"; do case "$o" in roll_hi_deg=*) echo "$o" ;; esac; done))
+ fi
+ [ -e "$run/curve.csv" ] && { log "skip $run (exists)"; return 0; }
+ log "student online $(basename "$run"): init $init, teacher $jt, $(basename "$oc")"
+ "$PY" -P scripts/so101_policy/vision_viral.py online --init "$init" --out "$run" --jt "$jt" --nrd-ckpt "$NRD" \
+ --mj-python "$PY" --tasks "$TS/train_mix45_16k.npz" "${ev[@]}" --guard-tasks "${GUARD[@]}" \
+ --config configs/so101_policy/vision/viral_r2s_v1.json --set "${SETS[@]}" --online-config "$oc" \
+ --eval-randomise "${size[@]}" --seed "$seed" --device "$DEVICE" "${oset[@]}"
+}
+if has_step s0; then
+ run="$RUNS/s0_v2_start_s2"
+ size=(--r0-tasks 4096 --rounds 2 --round-tasks 2048 --train-steps0 10000 --train-steps 4000 --render-worlds 256
+ --eval-workers 16 --eval-tasks "$T/dev100.npz" "$T/home45_dev100.npz")
+ [ "$TINY" = 1 ] && size=(--r0-tasks 32 --rounds 1 --round-tasks 16 --train-steps0 4 --train-steps 2 --render-worlds 16
+ --eval-workers 2 --eval-tasks "$TS/dev100.npz")
+ log "s0: first student (offline rounds, ImageNet ResNet18 encoders from torchvision), labels of T4"
+ [ -e "$run/r$([ "$TINY" = 1 ] && echo 1 || echo 2)/last.pt" ] || "$PY" -P scripts/so101_policy/vision_viral.py run \
+ --out "$run" --jt "$(ckpt t4)" --nrd-ckpt "$NRD" --mj-python "$PY" --tasks "$TS/train_mix45_16k.npz" \
+ --guard-tasks "${GUARD[@]}" --config configs/so101_policy/vision/viral_r2s_v1.json \
+ --set "scene=\"$SCENE\"" "calib=\"$CALIB\"" --teacher-share 0.5 --noise 1.0 --r0-noise-frac 0.5 \
+ --collect-randomise --eval-randomise --seed 2 --device "$DEVICE" "${size[@]}"
+fi
+V=configs/so101_policy/vision
+if has_step s1; then student_online s1_v2_online_s18 "$(ckpt s0)" "$(ckpt t4)" $V/viral_r2s_online_v1.json 18; fi
+if has_step s2; then student_online s2_v2_online2_s28 "$(ckpt s1)" "$(ckpt t4)" $V/viral_r2s_online_v1.json 28; fi
+if has_step s3; then # exact code of this stage: commit 977863c9e (550a58cb6 changed the relabel mask; README)
+ student_online s3_v4_relabel_s63 "$(ckpt s2)" "$(ckpt t4)" $V/viral_r2s_online_relabel_v4.json 63
+fi
+if has_step s4; then
+ student_online s4_v8_roll_s801 "$(ckpt s3)" "$(ckpt t5)" $V/viral_r2s_online_relabel_roll_v8.json 801 \
+ --oset iterations=2000
+fi
+if has_step s5; then # the teacher: --parents own and an own t6 run, else the released T6
+ student_online s5_v12_tb10_s1210 "$(ckpt s4)" "$(ckpt t6)" $V/viral_r2s_online_v12_tb10.json 1210 \
+ --oset iterations=1500 eval_every=750 save_every=250 roll_hi_deg=98
+fi
+
+# ---------------------------------------------------------------------------------------------------- simcheck
+STUDENT="$(ckpt s5)"
+if has_step simcheck; then
+ G="$OUT/simcheck"
+ if [ "$TINY" = 1 ]; then
+ log "simcheck (smoke): G2-type evaluation of $STUDENT, 4 J224 tasks, 300 steps"
+ ONLY=g2_a TASK_ROWS=4 HORIZON=300 WORKERS=4 PY="$PY" scripts/so101_pick_place/check/run_gates.sh run \
+ v12_tb10_s1210_it1000 "$STUDENT" "$G"
+ "$PY" - "$G/runs/gates/local/v12_tb10_s1210_it1000/g2_a.npz" <<'EOF'
+import json, sys
+sys.path.insert(0, "scripts/so101_pick_place/check")
+import numpy as np
+import check_analyze as CA
+f = sys.argv[1]
+rows, info = CA.run_episodes(f)
+t = CA.j_task(f, tuple(info["plane"]) if info.get("plane") else None, info)
+print("g2_a smoke:", json.dumps(t["all"]), "| check info: look", info.get("look"), "scene", info.get("scene_sha256", "")[:8])
+EOF
+ else
+ log "simcheck: D's reference runs (12 evaluations), then tb10 (9); about 8-10 GPU-h of renders + CPU MuJoCo"
+ WORKERS="$WORKERS" PY="$PY" scripts/so101_pick_place/check/run_gates.sh run D "$A/student/s4_v8_roll_s801/it_02000.pt" "$G" ref
+ WORKERS="$WORKERS" PY="$PY" scripts/so101_pick_place/check/run_gates.sh run v12_tb10_s1210_it1000 "$STUDENT" "$G"
+ PY="$PY" scripts/so101_pick_place/check/run_gates.sh summary v12_tb10_s1210_it1000 "$G"
+ fi
+fi
+
+# ---------------------------------------------------------------------------------------------------- bundle
+BUNDLE="$OUT/bundle/so101_hw_v13_tb10"
+if has_step bundle; then
+ log "bundle: make_orin_bundle.sh $STUDENT -> $BUNDLE"
+ SO101_KIN_POINTS="$A/rl_inputs/geometry/kin_points_v1.npz" PYTHON="$PY" \
+ scripts/so101_policy/real2sim/hw/make_orin_bundle.sh "$STUDENT" "$BUNDLE" "$CALIB"
+ "$PY" - "$BUNDLE/MANIFEST.txt" "$A/bundle/so101_hw_v13_tb10/MANIFEST.txt" <<'EOF'
+import sys
+read = lambda p: {l.split(None, 1)[1].strip(): l.split()[0] for l in open(p).read().splitlines()[3:]}
+mine, ref = read(sys.argv[1]), read(sys.argv[2])
+same = sorted(k for k in mine.keys() & ref.keys() if mine[k] == ref[k])
+diff = sorted(k for k in mine.keys() & ref.keys() if mine[k] != ref[k])
+print(f"bundle vs the released bundle: {len(same)} files equal, {len(diff)} differ {diff}, only here "
+ f"{sorted(mine.keys() - ref.keys())}, only in the released one {sorted(ref.keys() - mine.keys())}")
+EOF
+fi
+
+# ---------------------------------------------------------------------------------------------------- fake robot
+if has_step fake; then
+ [ -d "$BUNDLE" ] || die "no bundle $BUNDLE (run the bundle step)"
+ FB="$OUT/fakebin"; mkdir -p "$FB"
+ PYABS="$(command -v "$PY")"
+ cat > "$FB/python" < "$F/check.log" 2>&1) || rc=$?
+ echo "check exit $rc (nonzero expected off the robot computer); $(grep -c -i 'fail\|missing' "$F/check.log") lines with FAIL / missing"
+ log "fake: robot_test.sh eval 1 6 (one 6 s episode on the fake robot)"
+ rc=0; (cd "$b" && PATH="$FB:$PATH" CONDA_DEFAULT_ENV=lerobot RUNS="$F/runs" timeout 900 \
+ script -qec "./robot_test.sh eval 1 6" /dev/null > "$F/eval.log" 2>&1) || rc=$?
+ echo "eval exit $rc"; [ "$rc" = 0 ] || die "fake eval failed ($F/eval.log)"
+ fi
+ log "fake: robot_test.sh replay with the $tag bundle (3 recordings)"
+ rc=0; (cd "$b" && PATH="$FB:$PATH" CONDA_DEFAULT_ENV=lerobot RUNS="$F/runs_$tag" DATA_ROOT="$REC" timeout 1800 \
+ ./robot_test.sh replay > "$F/replay_$tag.log" 2>&1) || rc=$?
+ echo "replay ($tag) exit $rc"; [ "$rc" = 0 ] || die "fake replay failed ($F/replay_$tag.log)"
+ done
+ "$PY" - "$F/runs_built" "$F/runs_released" <<'EOF'
+import sys
+from pathlib import Path
+import numpy as np
+def chunks(root):
+ out = {}
+ for f in sorted(Path(root).rglob("*.npz")):
+ z = np.load(f, allow_pickle=False)
+ key = str(f.relative_to(root)).split("/", 1)[-1]
+ out[key] = {k: z[k] for k in ("q_sim", "qd_sim", "qry_step", "qry_thumbs", "qry_chunk") if k in z.files}
+ return out
+a, b = chunks(sys.argv[1]), chunks(sys.argv[2])
+if not a or a.keys() != b.keys():
+ sys.exit(f"replay outputs differ in their files: {sorted(a)} vs {sorted(b)}")
+worst, n = 0.0, 0
+for k in a:
+ for name in a[k].keys() & b[k].keys():
+ x, y = a[k][name], b[k][name]
+ n += 1
+ worst = max(worst, float(np.abs(x.astype(np.float64) - y.astype(np.float64)).max()) if x.shape == y.shape else float("inf"))
+print(f"replay, built vs released bundle: {len(a)} recordings, {n} arrays compared, max |diff| {worst:.3g}")
+EOF
+fi
+
+# ---------------------------------------------------------------------------------------------------- robot results
+if has_step robot; then
+ log "robot: the result tables from the released logs (build_results.py), next to results/robot/results.json"
+ mkdir -p "$OUT/robot"
+ "$PY" -I scripts/so101_pick_place/robot/build_results.py --logs "$A/robot/logs" \
+ --stress "$A/results/robot/stress_episodes.json" --out "$OUT/robot" > "$OUT/robot/build.log"
+ "$PY" - "$OUT/robot/results.json" "$A/results/robot/results.json" <<'EOF'
+import json, sys
+a, b = (json.load(open(p)) for p in sys.argv[1:3])
+for d in (a, b):
+ for k in ("built_by", "logs_root", "stress_meta"):
+ d.pop(k)
+ for s in d["students"].values():
+ s.pop("local_bundle")
+t = a["per_student"]["tb10"]["stress_20261027"]
+print(f"robot tables: equal to the released results.json (source paths aside): {a == b}; tb10 stress {t['placed']}/{t['n']}")
+EOF
+fi
+
+# ---------------------------------------------------------------------------------------------------- summary
+if has_step summary; then
+ log "summary: this run next to the released records"
+ "$PY" - "$RUNS" "$A" <<'EOF'
+import json, sys
+from pathlib import Path
+runs, A = Path(sys.argv[1]), Path(sys.argv[2])
+REL = {"t3_jt_b140": None, "t4_jt_h110": None, "t5_tppo_roll_v8_s21": "teacher/t5_tppo_roll_v8_s21/dev_evals.jsonl",
+ "t6_tppo_v12_fr10_s122": "teacher/t6_tppo_v12_fr10_s122/dev_evals.jsonl"}
+for name, rel in REL.items():
+ f = runs / name / "dev_evals.jsonl"
+ if not f.is_file():
+ continue
+ last = json.loads(f.read_text().splitlines()[-1])
+ ref = json.loads((A / rel).read_text().splitlines()[-1]) if rel else None
+ for s, v in last["sets"].items():
+ r = (ref or {}).get("sets", {}).get(s, {}) if ref else {}
+ print(f"{name} it {last['iteration']} {s}: lenient {v['lenient']:.2f} strict {v['strict']:.2f} | released it "
+ f"{ref['iteration'] if ref else '-'}: {r.get('lenient', '-')} / {r.get('strict', '-')}")
+for d in sorted(runs.glob("s[1-5]_*")):
+ f = d / "progress.jsonl"
+ if not f.is_file():
+ continue
+ rel = A / "student" / d.name / "progress.jsonl"
+ ev = lambda p: [json.loads(l) for l in p.read_text().splitlines() if '"stage": "eval' in l]
+ mine, ref = ev(f), (ev(rel) if rel.is_file() else [])
+ for e in mine[-2:]:
+ print(f"{d.name} {e['stage']}: lenient {e['lenient']:.2f} strict {e['strict']:.2f}")
+ for e in ref[-2:]:
+ print(f"{d.name} released {e['stage']}: lenient {e['lenient']:.2f} strict {e['strict']:.2f}")
+EOF
+ G="$OUT/simcheck/out/gates/local/v12_tb10_s1210_it1000.json"
+ if [ -f "$G" ]; then
+ "$PY" - "$G" "$A/results/sim_checks/v12_tb10_s1210_it1000.json" <<'EOF'
+import json, sys
+a, b = (json.load(open(p)) for p in sys.argv[1:3])
+for k in ("G2",):
+ for m in ("grasp", "place", "carry_stop"):
+ print(f"sim check G2 {m}: {a['gates'][k][m]['cand']} (released, AMD MI350X: {b['gates'][k][m]['cand']})")
+for p in ("g3_m3", "g3_p3"):
+ print(f"sim check G3 {p}: " + ", ".join(f"{m} {a['gates']['G3']['planes'][p][m]['cand']} / {b['gates']['G3']['planes'][p][m]['cand']}"
+ for m in ("grasp", "place", "carry_stop")))
+print(f"G1 {a['gates']['G1']['cand']} % (released {b['gates']['G1']['cand']} %); veto {a['vetoed']} (released {b['vetoed']})")
+EOF
+ fi
+fi
+log "done: $OUT"
diff --git a/so101_pick_place/code/scripts/so101_pick_place/robot/build_results.py b/so101_pick_place/code/scripts/so101_pick_place/robot/build_results.py
new file mode 100644
index 0000000000000000000000000000000000000000..867cf8539427d72a4cbd0975acb9112221ba22e9
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/robot/build_results.py
@@ -0,0 +1,321 @@
+"""Robot evidence tables for the SO101 pick-and-place release (read-only on robot_logs).
+
+Reads the raw session logs (session.json + ep_*/episode_live.{json,npz}) and writes results.json / results.md.
+Student identity = the bundle folder in ep_*/episode_live.json setup.kin_points (/home/sbel//assets/...);
+the logs hold no checkpoint hash. The checkpoint and sha256 of each bundle are the study's record of its local copy of
+that bundle (MANIFEST.txt, assets/student.pt), read from the released results.json (--students).
+Place = session.json episodes[].place (the "p" letter typed by the person at the robot); re-checked against the typed
+code and against ep_*/episode_live.json outcome.
+
+ python3 build_results.py --logs --stress --out DIR \
+ [--students ] [--bundles DIR]
+
+Ported from the study's release script (the folders are arguments). Only the tb10 bundle is released
+(bundle/so101_hw_v13_tb10/ on the Hub), so the bundle line, checkpoint and student.pt sha256 of each robot bundle come
+from the "students" record of the released results.json (default: next to --stress); with --bundles DIR (a folder
+that holds /MANIFEST.txt and /assets/student.pt) a bundle found there is read and checked against the
+record. The results.json written equals the released one except the source paths it names; results.md has the Hub
+checkpoint paths in place of the study's local ones.
+
+The cube / plate positions, the direction labels and the end distances come from stress_episodes.json: an image +
+kinematics analysis of the study whose script was not found (it is not released). This script only reads them.
+"""
+import argparse
+import glob
+import hashlib
+import json
+import math
+import os
+import sys
+
+import numpy as np
+
+LOGS = OUT = STRESS_JSON = BUNDLE_DIR = None # set by main() from the arguments
+BUNDLES = {} # bundle -> (label, record): main() fills it from --students
+
+STRESS = ["eval_20261027_145520", "eval_20261027_150916", "eval_20261027_151136", "eval_20261027_151953",
+ "eval_20261027_153045", "eval_20261027_153943"]
+SCREEN = ["eval_20261027_133039", "eval_20261027_133521", "eval_20261027_133953", "eval_20261027_134411",
+ "eval_20261027_134903", "eval_20261027_135259", "eval_20261027_135657", "eval_20261027_140036"]
+
+# bundle folder on the robot computer -> label; the record of each bundle (MANIFEST.txt line 1, checkpoint, sha256 of
+# assets/student.pt) is the "students" block of the released results.json
+LABELS = {"so101_hw_v8_roll801": "D", "so101_hw_v13_tb10": "tb10", "so101_hw_v13_visR500": "visR500",
+ "so101_hw_v13q_visR_s1304_it750": "visR_s1304_it750",
+ "so101_hw_v13q_visRtb05_s1301_it500": "visRtb05_s1301_it500", "so101_hw_v13_tb05": "tb05",
+ "so101_hw_v13_visR0_250": "visR0_250"}
+# the released checkpoints on the Hub (the other robot students are not released)
+HUB_CKPT = {"tb10": "student/s5_v12_tb10_s1210/it_01000.pt", "D": "student/s4_v8_roll_s801/it_02000.pt"}
+# plain names of the screened students (results/sim_checks/LAB_PLAN_v13.md on the Hub)
+PLAIN = {"tb10": "lower table 10 mm, 1,000 steps (released)", "D": "previous robot student (released)",
+ "visR500": "visual fix, seed 1231, 500 steps", "visR_s1304_it750": "visual fix, seed 1304, 750 steps",
+ "visRtb05_s1301_it500": "visual fix + 5 mm lower table, 500 steps", "tb05": "lower table 5 mm, 1,500 steps",
+ "visR0_250": "real-look gripper, no randomisation, 250 steps"}
+
+
+def load_bundles(students_json):
+ """BUNDLES from the "students" block of the released results.json (label -> bundle, built, checkpoint, sha256)."""
+ rec = json.load(open(students_json))["students"]
+ for name, label in LABELS.items():
+ r = rec[label]
+ if r["bundle"] != name:
+ raise SystemExit(f"{students_json}: student {label} has bundle {r['bundle']}, expected {name}")
+ BUNDLES[name] = (label, {k: r[k] for k in ("built", "student_ckpt_local", "student_sha256")})
+
+
+def sha256(p):
+ h = hashlib.sha256()
+ with open(p, "rb") as f:
+ for b in iter(lambda: f.read(1 << 20), b""):
+ h.update(b)
+ return h.hexdigest()
+
+
+def wilson(k, n, z=1.96):
+ if n == 0:
+ return (float("nan"), float("nan"))
+ p = k / n
+ d = 1 + z * z / n
+ c = (p + z * z / (2 * n)) / d
+ h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
+ return (c - h, c + h)
+
+
+def bundle_info(name):
+ label, rec = BUNDLES[name]
+ path = f"{BUNDLE_DIR}/{name}" if BUNDLE_DIR else None
+ if path is None or not os.path.exists(f"{path}/MANIFEST.txt"):
+ return dict(label=label, bundle=name, local_bundle=None, **rec)
+ man = open(f"{path}/MANIFEST.txt").read().splitlines()
+ ck = man[1].split()[1] if man[1].startswith("student ") else None
+ out = dict(label=label, bundle=name, local_bundle=path, built=man[0], student_ckpt_local=ck,
+ student_sha256=sha256(f"{path}/assets/student.pt"))
+ if out["student_sha256"] != rec["student_sha256"]:
+ raise SystemExit(f"{path}: student.pt sha256 {out['student_sha256'][:16]} is not the recorded "
+ f"{rec['student_sha256'][:16]}")
+ return out
+
+
+def session_student(sess):
+ names = set()
+ for e in sorted(glob.glob(f"{LOGS}/{sess}/ep_*/episode_live.json")):
+ kp = json.load(open(e))["setup"]["kin_points"]
+ names.add(kp.split("/")[3])
+ assert len(names) == 1, (sess, names)
+ return names.pop()
+
+
+def all_d_sessions():
+ out = []
+ for d in sorted(glob.glob(f"{LOGS}/eval_2026102[4-7]_*")):
+ s = os.path.basename(d)
+ if not os.path.exists(f"{d}/session.json"):
+ continue
+ if session_student(s) == "so101_hw_v8_roll801":
+ out.append(s)
+ return out
+
+
+def parse_code(typed):
+ code = (typed or "").strip().partition(" ")[0].lower()
+ return dict(grasp="g" in code, lift="l" in code, place="p" in code)
+
+
+def episodes(sess, group, binfo, stress_idx):
+ S = json.load(open(f"{LOGS}/{sess}/session.json"))
+ rows, excluded = [], []
+ listed = {e["episode"] for e in S["episodes"]}
+ for epdir in sorted(glob.glob(f"{LOGS}/{sess}/ep_*")):
+ k = int(epdir.rsplit("_", 1)[1])
+ J = json.load(open(f"{epdir}/episode_live.json"))
+ if k not in listed:
+ excluded.append(dict(session=sess, ep=f"ep_{k:02d}", end_reason=J.get("end_reason"),
+ outcome=J.get("outcome"), episode_start=J.get("episode_start"),
+ why="not in session.json episodes[]; no policy step was run"))
+ for e in S["episodes"]:
+ k = e["episode"]
+ epdir = f"{LOGS}/{sess}/ep_{k:02d}"
+ J = json.load(open(f"{epdir}/episode_live.json"))
+ z = np.load(f"{epdir}/episode_live.npz", allow_pickle=False)
+ t = z["t"]
+ qt = z["qry_t"]
+ pc = parse_code(e.get("typed"))
+ o = J.get("outcome") or {}
+ r = dict(session=sess, ep=f"ep_{k:02d}", group=group, student=binfo["label"], bundle=binfo["bundle"],
+ student_sha8=binfo["student_sha256"][:8], start=e.get("start"), typed=e.get("typed"),
+ grasp=e.get("grasp"), lift=e.get("lift"), place=int(bool(e.get("place"))),
+ end_reason=e.get("end_reason"), duration_s=round(float(t[-1]), 2), n_steps=int(len(t)),
+ n_queries=int(len(qt)),
+ check_typed_code=(pc["place"] == bool(e.get("place")) and pc["grasp"] == bool(e.get("grasp"))
+ and pc["lift"] == bool(e.get("lift"))),
+ check_episode_json=(o.get("place") == e.get("place") and o.get("typed") == e.get("typed")))
+ sid = f"{sess.split('_')[-1]}/ep_{k:02d}"
+ if stress_idx is not None:
+ s = stress_idx.get(sid)
+ if s is None:
+ r["stress_row"] = None
+ else:
+ r.update(dir=s["dir"], cube_side=s["side"], cube_r_mm=round(s["cube_r"], 1),
+ cube_deg=round(s["cube_deg"], 1), plate_r_mm=round(s["plate_r"], 1),
+ plate_deg=round(s["plate_deg"], 1),
+ end_to_plate_mm=(None if s.get("end_to_plate") is None else round(s["end_to_plate"], 1)),
+ fail_class=s.get("fail"),
+ plate_minus_cube_y_mm=round(s["plate_r"] * math.sin(math.radians(s["plate_deg"]))
+ - s["cube_r"] * math.sin(math.radians(s["cube_deg"])), 1),
+ check_stress_json=(bool(s["placed"]) == bool(e.get("place")) and s["typed"] == e.get("typed")))
+ rows.append(r)
+ return rows, excluded
+
+
+def tally(rows):
+ k, n = sum(r["place"] for r in rows), len(rows)
+ lo, hi = wilson(k, n)
+ return dict(placed=k, n=n, rate=round(k / n, 4) if n else None, wilson95=[round(lo, 4), round(hi, 4)])
+
+
+def main():
+ global LOGS, OUT, STRESS_JSON, BUNDLE_DIR
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("--logs", required=True, help="robot/logs of the Hub folder (one folder per session)")
+ p.add_argument("--stress", required=True, help="results/robot/stress_episodes.json of the Hub folder")
+ p.add_argument("--out", required=True, help="folder for results.json and results.md")
+ p.add_argument("--students", default="", help="the released results/robot/results.json (its 'students' record; "
+ "default: results.json next to --stress)")
+ p.add_argument("--bundles", default="", help="optional folder with local bundle copies (checked against the record)")
+ a = p.parse_args()
+ LOGS, OUT, STRESS_JSON, BUNDLE_DIR = a.logs, a.out, a.stress, a.bundles or None
+ missing = [s for s in STRESS + SCREEN if not glob.glob(f"{LOGS}/{s}/ep_*/episode_live.json")]
+ if missing:
+ sys.exit(f"robot logs not found in {LOGS} ({len(missing)} sessions, e.g. {missing[0]}): download the robot "
+ f"group (reproduce.sh --with-robot, or download.py --groups robot)")
+ load_bundles(a.students or os.path.join(os.path.dirname(os.path.abspath(a.stress)), "results.json"))
+ os.makedirs(OUT, exist_ok=True)
+ stress_list = json.load(open(STRESS_JSON))
+ sidx = {s["id"]: s for s in stress_list}
+ binfo = {}
+ rows, excluded = [], []
+ sessions = {}
+ d_sessions = all_d_sessions()
+ plan = [(s, "stress_tb10") for s in STRESS] + [(s, "screening_20261027") for s in SCREEN] + \
+ [(s, "D_20261024_26") for s in d_sessions if s not in SCREEN]
+ for sess, group in plan:
+ bname = session_student(sess)
+ if bname not in binfo:
+ binfo[bname] = bundle_info(bname)
+ rr, ex = episodes(sess, group, binfo[bname], sidx if group == "stress_tb10" else None)
+ rows += rr
+ excluded += ex
+ sessions[sess] = dict(group=group, student=binfo[bname]["label"], bundle=bname, n_episodes=len(rr),
+ placed=sum(r["place"] for r in rr), start=json.load(open(f"{LOGS}/{sess}/session.json"))["start"])
+
+ stress = [r for r in rows if r["group"] == "stress_tb10"]
+ # independent recount (raw session.json only, no stress_episodes.json)
+ raw_place = 0
+ raw_n = 0
+ for s in STRESS:
+ S = json.load(open(f"{LOGS}/{s}/session.json"))
+ raw_n += len(S["episodes"])
+ raw_place += sum(1 for e in S["episodes"] if e.get("place") is True)
+ by_dir = {}
+ for d in ("R->L", "L->R"):
+ by_dir[d] = tally([r for r in stress if r.get("dir") == d])
+ stress_ids = {f"{r['session'].split('_')[-1]}/{r['ep']}" for r in stress}
+ recount = dict(
+ source="robot_logs//session.json episodes[].place for the 6 stress sessions",
+ n_episodes=raw_n, placed=raw_place, report_claim="36/50", agrees=(raw_place == 36 and raw_n == 50),
+ typed_code_agrees_all=all(r["check_typed_code"] for r in stress),
+ episode_json_agrees_all=all(r["check_episode_json"] for r in stress),
+ stress_json_agrees_all=all(r.get("check_stress_json") for r in stress),
+ stress_json_ids_match=(stress_ids == set(sidx)),
+ dir_matches_lateral_y=sum((r["plate_minus_cube_y_mm"] > 0) == (r["dir"] == "R->L") for r in stress),
+ dir_near_ambiguous_lt15mm=[f"{r['session']}/{r['ep']}" for r in stress if abs(r["plate_minus_cube_y_mm"]) < 15],
+ by_dir=by_dir,
+ by_session={s: sessions[s]["placed"] for s in STRESS},
+ )
+
+ screen = [r for r in rows if r["group"] == "screening_20261027"]
+ d_all = [r for r in rows if r["student"] == "D"]
+ per_student = {}
+ for lab in [v[0] for v in BUNDLES.values()]:
+ per_student[lab] = dict(
+ screening_20261027=tally([r for r in screen if r["student"] == lab]),
+ )
+ per_student["tb10"]["stress_20261027"] = tally(stress)
+ per_student["tb10"]["stress_by_dir"] = by_dir
+ per_student["tb10"]["all_20261027"] = tally([r for r in rows if r["student"] == "tb10"])
+ per_student["D"]["all_20261024_27"] = tally(d_all)
+ per_student["D"]["by_day"] = {day: tally([r for r in d_all if r["session"].startswith(f"eval_{day}")])
+ for day in ("20261024", "20261025", "20261026", "20261027")}
+
+ res = dict(
+ built_by="scripts/so101_pick_place/robot/build_results.py", logs_root=LOGS, stress_meta=STRESS_JSON,
+ students={b["label"]: {k: v for k, v in b.items() if k != "label"} for b in binfo.values()},
+ sessions=sessions, excluded=excluded, stress_recount=recount, per_student=per_student,
+ screening_all=tally(screen), episodes=rows)
+ json.dump(res, open(f"{OUT}/results.json", "w"), indent=1)
+
+ # ---- markdown
+ L = []
+ L.append("# SO101 robot results (from the raw logs)\n")
+ L.append("Source: the session logs of the Hub folder `robot/logs//` (`session.json`: typed outcome; "
+ "`ep_NN/episode_live.{json,npz}`), counted by `scripts/so101_pick_place/robot/build_results.py`. "
+ "Place = the person at the robot typed `p` (cube on the plate). Cube / plate positions and directions: "
+ "`results/robot/stress_episodes.json` (an image + kinematics estimate; the script that wrote it was not "
+ "found and is not released).\n")
+ L.append("## Students\n")
+ L.append("| Label | Student | Bundle on the robot computer | Checkpoint on the Hub | student.pt sha256 (first 16) |")
+ L.append("|---|---|---|---|---|")
+ for b in binfo.values():
+ L.append(f"| {b['label']} | {PLAIN.get(b['label'], '')} | {b['bundle']} | "
+ f"{('`' + HUB_CKPT[b['label']] + '`') if b['label'] in HUB_CKPT else 'not released'} "
+ f"| {b['student_sha256'][:16]} |")
+ L.append("")
+ L.append("The logs do not record a checkpoint hash: the student of each session is known from the bundle folder "
+ "named in the logs (`setup.kin_points`) and the study's local copy of that bundle; the files on the robot "
+ "computer were not compared with `MANIFEST.txt`.\n")
+ L.append("## Totals\n")
+ L.append("| Student | Test | Places | Rate | 95 % (Wilson) |")
+ L.append("|---|---|---|---|---|")
+
+ def row(lab, test, t):
+ L.append(f"| {lab} | {test} | {t['placed']}/{t['n']} | {100 * t['rate']:.0f} % | "
+ f"{100 * t['wilson95'][0]:.0f}-{100 * t['wilson95'][1]:.0f} % |")
+ row("tb10", "stress 10-27 (6 sessions)", per_student["tb10"]["stress_20261027"])
+ for d in ("R->L", "L->R"):
+ row("tb10", f"stress, {d}", by_dir[d])
+ row("tb10", "all 10-27 (screening + stress)", per_student["tb10"]["all_20261027"])
+ row("D", "all 10-24..10-27 (7 sessions)", per_student["D"]["all_20261024_27"])
+ for day, t in per_student["D"]["by_day"].items():
+ row("D", f"day {day}", t)
+ for lab in per_student:
+ row(lab, "screening 10-27", per_student[lab]["screening_20261027"])
+ row("all 7", "screening 10-27", tally(screen))
+ L.append("")
+ L.append("## Independent recount of the stress test\n")
+ L.append(f"- session.json place flags, 6 sessions: **{raw_place}/{raw_n}** (report claim 36/50; agrees: "
+ f"{recount['agrees']}).")
+ L.append(f"- Per session: " + ", ".join(f"{s.split('_')[-1]} {sessions[s]['placed']}/{sessions[s]['n_episodes']}"
+ for s in STRESS))
+ L.append(f"- Typed code letters agree with the flags: {recount['typed_code_agrees_all']}; "
+ f"ep_NN/episode_live.json outcome agrees: {recount['episode_json_agrees_all']}; "
+ f"stress_episodes.json placed/typed agree: {recount['stress_json_agrees_all']}; "
+ f"same 50 episode ids: {recount['stress_json_ids_match']}.")
+ L.append(f"- Direction label (stress_episodes.json `dir`) = sign of the arm-frame lateral offset plate y - cube y "
+ f"(y = r sin(deg)): {recount['dir_matches_lateral_y']}/50 agree; |offset| < 15 mm (near ambiguous): "
+ f"{', '.join(recount['dir_near_ambiguous_lt15mm']) or 'none'}.")
+ for x in excluded:
+ L.append(f"- Excluded: {x['session']}/{x['ep']} ({x['end_reason']}; {x['why']}).")
+ L.append("")
+ L.append("## Episodes\n")
+ L.append("| Session | Ep | Group | Student | Typed | Place | Dir | Cube r mm / deg | End reason | Duration s |")
+ L.append("|---|---|---|---|---|---|---|---|---|---|")
+ for r in rows:
+ geo = f"{r['cube_r_mm']:.0f} / {r['cube_deg']:+.0f}" if "cube_r_mm" in r else ""
+ L.append(f"| {r['session']} | {r['ep']} | {r['group']} | {r['student']} | {r['typed']} | {r['place']} | "
+ f"{r.get('dir', '')} | {geo} | {r['end_reason']} | {r['duration_s']:.1f} |")
+ open(f"{OUT}/results.md", "w").write("\n".join(L) + "\n")
+ print(json.dumps(dict(recount=recount, per_student=per_student, excluded=excluded), indent=1))
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/so101_pick_place/code/scripts/so101_pick_place/robot/render_videos.py b/so101_pick_place/code/scripts/so101_pick_place/robot/render_videos.py
new file mode 100644
index 0000000000000000000000000000000000000000..32d46c377fb3cc6a2133ca699ab774a44fb2a4f0
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_pick_place/robot/render_videos.py
@@ -0,0 +1,224 @@
+"""Robot test videos from the logged student input images (read-only on robot_logs).
+
+Source per episode: ep_NN/episode_live.npz qry_thumbs [n_query, 2 (external, wrist), 112, 112, 3] uint8 RGB and qry_t (s).
+These are the student's 224 px input images (external: crop 52,103,288,288 of the 640x480 frame; wrist: the full frame
+squashed to a square), logged at 112 px at every policy query (about 7.8 Hz). No full-resolution recording exists.
+
+Outputs (H.264, CRF 23, yuv420p):
+ videos/stress_tb10/_.mp4 one per stress episode, real time, 25 fps (each image held until the next query)
+ videos/tb10_stress_20261027_4x.mp4 all 50 stress episodes at 4x with a title card each + a final card
+ videos/screening_20261027_4x.mp4 the 10-27 screening (8 sessions x 4, 7 students) at 4x
+
+ python3 render_videos.py [all|per_episode|stress_comp|screen_comp] --logs \
+ --results --out DIR (needs ffmpeg with libx264)
+
+Ported from the study's ~/so101_r2s_claude/release/robot/scripts/render_videos.py: the folders are arguments.
+"""
+import argparse
+import json
+import os
+import subprocess
+
+import cv2
+import numpy as np
+
+LOGS = OUT = RESULTS = None # set from the arguments
+FPS = 25
+UP = 3
+PANEL = 112 * UP # 336
+W = 2 * PANEL # 672
+HDR = 78
+H = PANEL + HDR # 414
+FONT = cv2.FONT_HERSHEY_SIMPLEX
+
+
+def encoder(path):
+ cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
+ "-s", f"{W}x{H}", "-r", str(FPS), "-i", "-", "-c:v", "libx264", "-preset", "medium", "-crf", "23",
+ "-pix_fmt", "yuv420p", "-threads", "4", "-movflags", "+faststart", path]
+ return subprocess.Popen(cmd, stdin=subprocess.PIPE)
+
+
+def text(img, s, y, scale=0.48, color=(255, 255, 255), x=6, th=1):
+ cv2.putText(img, s, (x, y), FONT, scale, color, th, cv2.LINE_AA)
+
+
+def panels(th):
+ ext = cv2.resize(th[0], (PANEL, PANEL), interpolation=cv2.INTER_NEAREST)
+ wr = cv2.resize(th[1], (PANEL, PANEL), interpolation=cv2.INTER_NEAREST)
+ im = np.concatenate([ext, wr], 1)
+ text(im, "external", PANEL - 8, 0.45, (255, 255, 0))
+ text(im, "wrist", PANEL - 8, 0.45, (255, 255, 0), x=PANEL + 6)
+ return im
+
+
+def frame(th, lines, colors=None):
+ f = np.zeros((H, W, 3), np.uint8)
+ f[:HDR] = 30
+ for i, s in enumerate(lines):
+ text(f, s, 20 + 24 * i, color=(colors or {}).get(i, (255, 255, 255)))
+ f[HDR:] = panels(th)
+ return f
+
+
+def card(lines, big=None):
+ f = np.zeros((H, W, 3), np.uint8)
+ f[:] = 20
+ y = 60
+ if big:
+ sz = cv2.getTextSize(big, FONT, 1.6, 3)[0]
+ text(f, big, y + 30, 1.6, (255, 255, 255), x=(W - sz[0]) // 2, th=3)
+ y += 90
+ for s in lines:
+ text(f, s, y, 0.55)
+ y += 28
+ return f
+
+
+def load_ep(sess, ep):
+ z = np.load(f"{LOGS}/{sess}/{ep}/episode_live.npz", allow_pickle=False)
+ return z["qry_thumbs"], z["qry_t"], float(z["t"][-1])
+
+
+def episode_frames(th, qt, t_end, speed, header, place):
+ """Frames at FPS; output frame k shows real time k * speed / FPS (latest image logged at or before it)."""
+ n = int(np.floor(t_end * FPS / speed)) + 1
+ for k in range(n):
+ tk = k * speed / FPS
+ i = max(int(np.searchsorted(qt, tk, side="right")) - 1, 0)
+ yield frame(th[i], header(tk), {1: outcome_color(place)})
+
+
+def short(sess):
+ return sess.split("_")[-1]
+
+
+def outcome_color(place):
+ return (120, 255, 120) if place else (255, 120, 120)
+
+
+def main(which):
+ R = json.load(open(RESULTS))
+ eps = R["episodes"]
+ stud = R["students"]
+ sizes = {}
+ stress = [r for r in eps if r["group"] == "stress_tb10"]
+ tb = stud["tb10"]
+ tb_ck = "v12_tb10_s1210 it_01000, sha256 " + tb["student_sha256"][:8]
+
+ if which in ("all", "per_episode"):
+ os.makedirs(f"{OUT}/videos/stress_tb10", exist_ok=True)
+ for r in stress:
+ th, qt, t_end = load_ep(r["session"], r["ep"])
+ sid = f"{short(r['session'])}/{r['ep']}"
+ geo = (f"{r['dir']} cube r {r['cube_r_mm']:.0f} mm {r['cube_deg']:+.0f} deg, "
+ f"plate r {r['plate_r_mm']:.0f} mm {r['plate_deg']:+.0f} deg")
+ res = "PLACED" if r["place"] else "NOT PLACED"
+
+ def hdr(tk, r=r, sid=sid, geo=geo, res=res):
+ return [f"tb10 stress {sid} | {r['typed']} | t {tk:5.1f} s",
+ f"{res} | {geo}",
+ f"real SO101 2026-10-27, student {tb_ck}, 1x"]
+ p = f"{OUT}/videos/stress_tb10/{r['session']}_{r['ep']}.mp4"
+ enc = encoder(p)
+ for f in episode_frames(th, qt, t_end, 1.0, hdr, r["place"]):
+ enc.stdin.write(f.tobytes())
+ enc.stdin.close()
+ assert enc.wait() == 0, p
+ sizes[p] = os.path.getsize(p)
+ print(p, sizes[p], flush=True)
+
+ if which in ("all", "stress_comp"):
+ p = f"{OUT}/videos/tb10_stress_20261027_4x.mp4"
+ enc = encoder(p)
+ rc = R["stress_recount"]
+ intro = card(["Real SO101 pick-and-place stress test, 2026-10-27 14:55-15:48",
+ f"Student tb10: {tb_ck}",
+ "Trained in simulation; bundle built 09:32, before the first test",
+ "50 policy episodes, 6 sessions; 4x speed",
+ "Images: the student's own camera inputs (logged at 112 px)",
+ "left: external camera (crop), right: wrist camera",
+ "Outcome typed by the person at the robot"], big="tb10 stress test")
+ for _ in range(FPS * 4):
+ enc.stdin.write(intro.tobytes())
+ for j, r in enumerate(stress, 1):
+ th, qt, t_end = load_ep(r["session"], r["ep"])
+ sid = f"{short(r['session'])}/{r['ep']}"
+ res = "PLACED" if r["place"] else "NOT PLACED"
+ c = card([f"{r['dir']}: cube r {r['cube_r_mm']:.0f} mm {r['cube_deg']:+.0f} deg, "
+ f"plate r {r['plate_r_mm']:.0f} mm {r['plate_deg']:+.0f} deg",
+ f"typed: {r['typed']}",
+ f"result: {res}"], big=f"{j}/50 {sid}")
+ for _ in range(int(FPS * 1.2)):
+ enc.stdin.write(c.tobytes())
+
+ def hdr(tk, r=r, sid=sid, res=res, j=j):
+ return [f"tb10 stress {sid} | {r['typed']} | t {tk:5.1f} s",
+ f"{res} | {r['dir']} | episode {j}/50",
+ "real SO101 2026-10-27, 4x speed"]
+ for f in episode_frames(th, qt, t_end, 4.0, hdr, r["place"]):
+ enc.stdin.write(f.tobytes())
+ bd = rc["by_dir"]
+ fin = card([f"R->L (plate left of the cube): {bd['R->L']['placed']}/{bd['R->L']['n']}",
+ f"L->R: {bd['L->R']['placed']}/{bd['L->R']['n']}",
+ "Session 150916 ep_03 was stopped at HOME before",
+ "the policy ran: not counted",
+ f"Student {tb_ck}"], big=f"{rc['placed']}/{rc['n_episodes']} placed")
+ for _ in range(FPS * 5):
+ enc.stdin.write(fin.tobytes())
+ enc.stdin.close()
+ assert enc.wait() == 0
+ sizes[p] = os.path.getsize(p)
+ print(p, sizes[p], flush=True)
+
+ if which in ("all", "screen_comp"):
+ p = f"{OUT}/videos/screening_20261027_4x.mp4"
+ enc = encoder(p)
+ scr = [r for r in eps if r["group"] == "screening_20261027"]
+ intro = card(["Real SO101, 2026-10-27 13:30-14:04",
+ "8 sessions x 4 episodes, 7 students (D at the start and the end)",
+ "Every session: ep 1-2 cube right, ep 3-4 cube left. 4x speed",
+ "Images: the student's own camera inputs (112 px logs)",
+ "left: external camera (crop), right: wrist camera",
+ "Outcome typed by the person at the robot"], big="Screening 10-27")
+ for _ in range(FPS * 4):
+ enc.stdin.write(intro.tobytes())
+ for j, r in enumerate(scr, 1):
+ th, qt, t_end = load_ep(r["session"], r["ep"])
+ sid = f"{short(r['session'])}/{r['ep']}"
+ res = "PLACED" if r["place"] else "NOT PLACED"
+ ck = stud[r["student"]]["student_ckpt_local"].split("/ckpt/")[-1]
+ c = card([f"student {r['student']} ({ck}, sha256 {r['student_sha8']})",
+ f"typed: {r['typed']}", f"result: {res}"], big=f"{j}/32 {sid}")
+ for _ in range(int(FPS * 1.2)):
+ enc.stdin.write(c.tobytes())
+
+ def hdr(tk, r=r, sid=sid, res=res, j=j):
+ return [f"{r['student']} screening {sid} | {r['typed']} | t {tk:5.1f} s",
+ f"{res} | episode {j}/32",
+ "real SO101 2026-10-27, 4x speed"]
+ for f in episode_frames(th, qt, t_end, 4.0, hdr, r["place"]):
+ enc.stdin.write(f.tobytes())
+ ps = R["per_student"]
+ lines = [f"{lab}: {ps[lab]['screening_20261027']['placed']}/{ps[lab]['screening_20261027']['n']}"
+ for lab in ps]
+ a = R["screening_all"]
+ fin = card(lines + [f"all: {a['placed']}/{a['n']}"], big="Screening places")
+ for _ in range(FPS * 5):
+ enc.stdin.write(fin.tobytes())
+ enc.stdin.close()
+ assert enc.wait() == 0
+ sizes[p] = os.path.getsize(p)
+ print(p, sizes[p], flush=True)
+
+
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("which", nargs="?", default="all", choices=("all", "per_episode", "stress_comp", "screen_comp"))
+ ap.add_argument("--logs", required=True)
+ ap.add_argument("--results", required=True)
+ ap.add_argument("--out", required=True, help="the videos go to /videos/")
+ a = ap.parse_args()
+ LOGS, RESULTS, OUT = a.logs, a.results, a.out
+ main(a.which)
diff --git a/so101_pick_place/code/scripts/so101_policy/real2sim/hw/QDGAIN_TEST.md b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/QDGAIN_TEST.md
new file mode 100644
index 0000000000000000000000000000000000000000..3f5929f521a5cf8073cb33f8f1dc8ae88eecd50c
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/QDGAIN_TEST.md
@@ -0,0 +1,101 @@
+# Robot test: joint-speed input gain (`--qd-gain`)
+
+> Historical test plan of 2026-10-22 for an option that the released student does not use (kept because the
+> robot bundle carries this file).
+
+Written 2026-10-22 evening for an agent that guides the user at the SO101 robot (proxy, Jetson AGX Orin). The user runs
+every command at the robot. The agent explains, reads the outputs and the logs, and keeps the rules below.
+
+## 1. Why this test
+
+| Item | Value |
+|---|---|
+| 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. |
+| 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. |
+| 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. |
+| 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. |
+| 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. |
+
+The gripper decision itself does not change: the student must first get low enough. If the gain works, the arm keeps
+moving down to the plate and the student releases as in the sim.
+
+## 2. Rules (must)
+
+1. The user runs all commands. The agent does not run `dry`, `live` or `eval`, and does not open the robot port or
+ the cameras.
+2. Never write motor EEPROM, never recalibrate, never run LeRobot tools (`lerobot-calibrate`, `lerobot-setup-motors`,
+ `lerobot-teleoperate` ...) in this test.
+3. Keep a hand near the arm. Stop keys: space, q, Esc or Ctrl+C. After a stop the arm holds (torque on).
+4. Stop the test and lower the gain if the arm hits the table, presses the cube into the table, or oscillates.
+5. Do not change files in `~/so101_hw_robot` (the launcher refuses changed files).
+
+## 3. Before the first episode
+
+1. `cd ~/so101_hw_robot && ./robot_test.sh check` must end with `CHECK OK`. The first line under "bundle files"
+ must name git commit `bbcf9f792` or later (the commit that added `--qd-gain`).
+2. Start from the folded rest pose. In the `q real` line of the run output: the 2nd value (shoulder lift) must be
+ between -88 and -100, the 3rd value (elbow) between 80 and 90. Else the run refuses (move the arm by hand with the
+ torque off, then start again).
+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
+ has sim roll 0 = 75.8 deg real, before 120.8 deg; the cable pulled out once on 10-22).
+4. The cameras must stay in their USB ports (external = port 4.1.4, wrist = port 4.1.1). The script uses these paths.
+
+## 4. Test plan
+
+Use the layout that worked on 10-22 for most episodes (from behind the robot, looking where the arm points at HOME):
+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
+square to the forward direction. Also use the mirrored layout (cube left, mat right) and 2 other layouts inside
+15-27 cm from the shoulder axis.
+
+| Block | Command | Episodes | Layouts |
+|---|---|---|---|
+| A | `./robot_test.sh eval 4 --qd-gain 2` | 4 | 2 x working layout, 2 x mirrored |
+| B | `./robot_test.sh eval 4 --qd-gain 2.5` | 4 | same 4 layouts |
+| C | `./robot_test.sh eval 4 --qd-gain 3` | 4 | same 4 layouts, only if A and B had no table contact |
+| D (optional) | `./robot_test.sh eval 4` (gain 1, reference) | 4 | same 4 layouts |
+
+Episode limit: 40 s (the default of `eval`). A typical successful episode on 10-22 took about 22 s.
+
+Each episode:
+1. At HOME, place the cube and the mat, then type `RUN`.
+2. Watch the arm. Push space when the cube is on the mat and the arm has moved away, or at a failure.
+3. Type the result: `g` grasp, `l` lift, `p` placed on the mat, for example `glp`, or `-`. Add a short note after a
+ space, for example `glp clean`, `gl hover 2cm`, `gl dropped high`, `g- slipped`, `table contact`.
+4. Type `r`: the arm goes back to HOME (the gripper opens). Reset the scene.
+
+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
+arm (torque off), or `h` to keep holding.
+
+## 5. What to watch for
+
+| Sign | Meaning | Action |
+|---|---|---|
+| The arm goes down onto the mat and opens | The fix works | Continue |
+| Hover 1-5 cm above the mat, no release (as on 10-22) | Gain too low | Next block (higher gain) |
+| The gripper touches the table during the approach or the place | Gain too high | Stop; go back to the lower gain |
+| Fast jerky motion or oscillation | Gain too high | Stop (space); lower the gain |
+| "guard: command floor" or "measured floor" stop | The guard stopped a low command | Note it; if it repeats, lower the gain |
+| 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 |
+
+## 6. What to send back
+
+- The session folders: `~/so101_hw_runs/eval__/` (each has `session.json` with the typed results and
+ `ep_NN/episode_live.npz/json`).
+- For each block: the gain, the typed results, and anything unusual.
+- A phone video of 1-2 episodes per block helps.
+
+## 7. Version
+
+Bundle built from git commit noted in `~/so101_hw_robot/MANIFEST.txt` (line 1), which must include `--qd-gain`
+(`./robot_test.sh eval 1 --qd-gain 2` prints the line `qdot input gain 2.0` after the joint map lines). Earlier bundles
+reject `--qd-gain` with "unrecognized arguments".
+
+## 8. Known issues from 10-22
+
+| Issue | What to do |
+|---|---|
+| `preflight failed: measured q outside the calibrated range` | The rest pose is off. Use the ranges in section 3. |
+| `HOME path refused` | Same. |
+| 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. |
+| `run` typed in lowercase | Refused: type `RUN`. The menu then appears. |
+| Do not push `r` repeatedly after a stop near the table | Each hold lets the arm sag a little. Use `t` with a hand under the arm. |
diff --git a/so101_pick_place/code/scripts/so101_policy/real2sim/hw/README.md b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8185b358a12890726ef88d13288e5ab5d574143f
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/README.md
@@ -0,0 +1,241 @@
+# SO101 camera student on the real robot
+
+> Study notes of 2026-10-22 to 10-24 (older students, the study's paths and tests that are not in this release),
+> kept because the robot bundle carries this file. The current guide is "Deploy on the robot" in
+> `so101_pick_place/README.md`.
+
+Status 2026-10-24: eval sessions on the robot on 2026-10-22 / 23 (logs `~/so101_r2s_claude/robot_logs`); the
+changes of 2026-10-24 (next section) ran only on the fake robot and in replay. First status (2026-10-22, before the
+robot): student for the robot: `robot_v2_s28_it03000.pt` (AMD `runs/v2_online2_s28/ckpt/it_03000.pt`; cameras
+`external` + `wrist`, 224 px, crops pinned in the checkpoint: external [52, 103, 288, 288], wrist [0, 0, 640, 480]).
+It was chosen for the robot because it keeps 89-91 % success in CPU MuJoCo on the measured (lower, tilted) real table,
+held-out tasks; the sim-best student (`final_v2_s26_it03000.pt`)
+falls to 36-48 % there (`~/so101_r2s_claude/eval/SELECTION_RULE.md`). Checks done on luffy only (logs in
+`~/so101_r2s_claude/hw_final/`, made with the sim-best student; the code path is the same): replay of 3 recordings
+from the extracted bundle equals the worktree run exactly; dry and live loops on the fake robot; the HOME check from
+the 15 recorded rest poses.
+
+| File | What |
+|---|---|
+| `run_student_real.py` | modes `replay` (recording, no robot), `dry` (robot read only), `live` (moves the robot) |
+| `hw_lib.py` | joint map, limits, image crop, action layer, hardware guard, joint paths, student wrapper, fake robot |
+| `make_orin_bundle.sh` | builds the folder + `.tar.gz` for the Orin (sources, collision points, student, calib_v1.json, `assets/deploy.json`) |
+| `robot_test.sh` | one command for each test on the Orin: check / replay / dry / live / live-tilt / eval (bundle root) |
+| `tests/so101_policy/test_real2sim_hw.py` | 32 unit tests (CPU, about 15 s) |
+| `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 |
+
+## Changes 2026-10-24 (read before the next robot day)
+
+| Item | Before | Now |
+|---|---|---|
+| 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 %. |
+| 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) |
+| 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) |
+| Two students in one episode (commit 39d2e5b72) | a second-student flag and bundle asset | removed (no policy stitching) |
+| Bundle | student + calib | + `assets/deploy.json` (floor mode, table plane source, HOME, eval guard; `robot_test.sh` reads it) |
+
+## Floor modes (the table floor; `run_student_real.py --floor-mode`, `assets/deploy.json`)
+
+The action-layer floor must have the clearance above the real mat that the student was trained with (sysid
+`~/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
+observed cube and plate positions (calibrated plane z = -4.7 mm - 36.4 x + 18.4 y, mm per m; +-3 mm). The bundle
+script reads the mode from the checkpoint (`v8_online.table_bias` present with p > 0 = plane, unless
+`v8_online.student_floor` is `observed` = flat); live mode refuses another mode (`--allow-floor-mismatch` overrides).
+The banner of every run prints the mode and these numbers.
+
+| 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) |
+|---|---|---|---|---|
+| 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) |
+| 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 |
+| 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) |
+
+Plane mode measures the floor stops above the plane, so the flat eval stops (-15 / -20 mm) on top of the plane would
+put them 15-20 mm into the mat (double lowering): live refuses plane-mode stops deeper than 5 mm (command) / 8 mm
+(measured). Live also refuses, in plane mode: a `--table-plane c0,c1,c2` that is more than 1 mm below the calibrated
+plane anywhere on r 0.15-0.27 m, +-90 deg (`--allow-floor-mismatch` overrides; write a negative c0 with the = form,
+`--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` /
+`--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
+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
+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
+the plane would let them press 8-18 mm lower than in training. With the plane floor and the servo-error integral, a
+student that pushes down on the plate or the mat can reach the command stop (2 mm below the mat); that ends the
+episode ("command floor") and is the intended protection.
+
+## Servo-error integral: anti-windup (2026-10-24)
+
+On 10-23 two eval episodes ended with "stall: wrist_roll blocked" (eval_20261023_141614 ep 6, eval_20261023_144431
+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
+101.21 deg (LeRobot range end), and the integral correction grew to +3 deg; the stall check compares the measured q
+with the command without the correction (101.21 - 3 = 98.2 deg): 2.5 deg >= 0.9 x lead band for 25 steps. Now
+(`GuardConfig.i_antiwindup`, default on): on a joint whose target is at / beyond its LeRobot-unit range, or whose
+corrected command would be clipped there, the error is not integrated; the correction is 0 while the target is at /
+beyond the range (either sign: the command is then the range end, as without the integral) and never pushes the
+command past the range otherwise. Offline replay of the Guard on the two logged episodes (`~/so101_r2s_claude/v8/deploy/stall_replay.json`):
+the old rule reproduces the logged commands exactly and stalls at the logged step; the new rule has no stall, the same
+commands on the other 5 joints at every step, and the roll differs only after the first step at the range end (by up
+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
+robot episodes with the integral on (144,785 steps, `~/so101_r2s_claude/v8/deploy/stall_replay_all.json`): the old
+rule reproduces 100 logs exactly (2 early live runs of 10-22 ran older guard code) and all 9 logged stalls (8 wrist
+roll, 1 shoulder pan, every one a wind-up at the range end); the new rule: 0 stalls, commands changed only on the
+pan (417 steps) and the roll (13,355 steps), always after the first step at the range end. The replay is open loop
+(the logged q), so the later steps of a changed episode are not what the robot would have done. `{"i_antiwindup":
+false}` in `--guard` gives the old rule. Training has the same rule as an option, off by default
+(`joint_env.RobotDynConfig.i_antiwindup`).
+
+## Closed gripper at the start (fixed 2026-10-22)
+
+A closed real gripper (LeRobot < 3) is below the sim jaw limit; 9 of the 15 recordings start like that. The HOME and
+return path checks now accept a measured end pose outside the sim range (the path stays between its ends). The
+calibrated LeRobot range is still checked.
+
+## 1. Build (luffy) and copy (you)
+
+```bash
+cd /home/harry/.t3/worktrees/NeDM-push-ppo/r2s-v8 # branch claude/r2s-v8
+scripts/so101_policy/real2sim/hw/make_orin_bundle.sh ~/so101_r2s_claude/ckpt/c1_relabel_s63_it02000.pt \
+ ~/so101_r2s_claude/v8/deploy/bundles/so101_hw_c1 # prints "floor mode flat"
+scripts/so101_policy/real2sim/hw/make_orin_bundle.sh \
+ ~/so101_r2s_claude/v8/deploy/bundles/so101_hw_v8 # prints "floor mode plane"
+scp ~/so101_r2s_claude/v8/deploy/bundles/so101_hw_c1.tar.gz sbel@proxy:~/ # you do this
+```
+
+The script reads the checkpoint (Python with torch: `$PYTHON`, default the so101_vision env) and writes
+`assets/deploy.json` (floor mode, table plane source, HOME, eval guard; `HOME_SIM_DEG=a,b,c,d,e,f` sets another
+HOME). MANIFEST.txt: 3 header lines (built, student + floor mode, calib), then the sha256 of every file.
+
+On the Orin: `cd ~ && tar xzf so101_hw_c1.tar.gz && cd so101_hw_c1 && sed -n '4,$p' MANIFEST.txt | sha256sum -c --quiet`
+(no output = all files intact). Needs only the `lerobot` conda env (torch, numpy, cv2, pyarrow, LeRobot 0.6.2); no
+mujoco. Run every command below from the bundle folder (e.g. `~/so101_hw_c1`), in an interactive terminal (desktop or `ssh -t`): the stop
+keys q / space / Esc need a TTY, else only Ctrl+C stops. Do not pipe into `tee` (Ctrl+C also stops `tee`); the
+`--out` folder keeps the log.
+
+## 2. Commands on the Orin
+
+Short form (`robot_test.sh`, in the bundle root; it activates `lerobot`, writes to `~/so101_hw_runs/_`,
+refuses dry / live without a TTY or with changed bundle files; `[s]` = the time limit; it refuses `--time-limit`,
+`--q-offset-deg`, `--out` in the extra arguments, and `--floor-mode`, `--table-z`, `--table-plane`, `--home`: every
+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
+port and the cameras, while one of your processes has one of them open, or while a LeRobot robot tool
+(`lerobot-teleoperate`, `-record`, `-calibrate`, ...) or another dry / live run of any user runs. The open files of
+other users' processes (root, docker) are not visible: stop those yourself.
+
+```bash
+cd ~/so101_hw_c1
+./robot_test.sh check # files, deploy settings, env, port, cameras, calibration (opens no device)
+./robot_test.sh replay # a) below
+./robot_test.sh dry # b) below, 30 s
+./robot_test.sh live # c) below, 15 s (live-tilt = c) + --q-offset-deg 0,-2.086,0,0,0; flat bundles only)
+./robot_test.sh eval [n] [s] # d) below: n episodes in a row (default 10 x 40 s)
+```
+
+d) Eval session (first robot day, 2026-10-22: grasp, lift and carry worked with these settings). `eval` = live with
+the floor mode and HOME of `assets/deploy.json`, `--amp 0`, `--guard ` and
+`--episodes-n n` (the table in "Floor modes": flat students `{"cmd_floor_m":-0.015,"hard_floor_m":-0.02,
+"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,
+"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
+sim table (the default floor stops at -2 / -5 mm ended good grasps); without the integral correction the real servos
+(P 16, gearbox friction) did not follow the student's 0.45 deg lift steps after the grasp and the arm stayed on the
+table. Flow: MOVE (HOME) -> each episode: reset the scene, RUN,
+the student (space ends the episode), type the result (g grasp, l lift, p placed, for example `glp`; a note after a
+space), `r` = back to HOME for the next episode (the gripper opens), `s` = end -> menu (r return to the start pose,
+t torque off). Logs: `/ep_NN/episode_live.{npz,json}` (outcome in the json), `/session.json`.
+
+e) Joint-speed input gain (`--qd-gain g`, default 1 = off; 2026-10-22 evening). The student's step size follows the
+measured joint speed; the real arm is about 5 x slower than the sim arm, so near the plate the steps shrink until the
+arm holds still and never releases (10 of 12 eval episodes). `--qd-gain` multiplies only the student's qdot input (the
+guard and the log keep the measured qdot). CPU MuJoCo, today's student, 12 real layouts x 4: robot-like dynamics
+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).
+Test plan: QDGAIN_TEST.md. Example: `./robot_test.sh eval 5 --qd-gain 2`.
+
+Long form:
+
+```bash
+conda activate lerobot
+cd ~/so101_hw_robot
+S="--student assets/student.pt --calib assets/calib_v1.json"
+F="--floor-mode flat --table-z 0 --home 0,-5,-15,92,0,30" # plane students: --floor-mode plane --table-plane calib ...
+# a) replay (no robot; Orin inference time; compare with luffy)
+python scripts/so101_policy/real2sim/hw/run_student_real.py replay $S $F --data-root /home/sbel/lerobot/data \
+ --episodes green_cube_red_plate:0,green_cube_red_plate:2,green_cube_red_plate_1:5 --out ~/so101_hw_runs/replay_orin
+# b) dry (robot and cameras connected, NO motor writes, torque untouched; stop other LeRobot processes first)
+python scripts/so101_policy/real2sim/hw/run_student_real.py dry $S $F --out ~/so101_hw_runs/dry_1 --time-limit 30
+# c) live (moves the robot)
+python scripts/so101_policy/real2sim/hw/run_student_real.py live --i-am-supervising $S $F \
+ --out ~/so101_hw_runs/live_1 --time-limit 15
+```
+
+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,
+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
+15 deg/s peak; `--floor-mode auto` (the student's: flat `--table-z 0` or plane `--table-plane calib`); `--configure
+auto`; guard = `GuardConfig` defaults (table below). The run checks that `--calib` is the calibration the student was trained with (live refuses a mismatch).
+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 /
+12.1 mm (bf16 on another GPU: small differences are normal). About 16 mm of the cube error is height (next section).
+
+## 3. Pre-run checklist (live)
+
+1. Dry run first. Check: the printed q matches the arm; `first_frames.npz` / the logged thumbnails show the fixed
+ camera as `external` and the gripper camera as `wrist` (a swap is not detected); the end of the run prints the
+ model and step time (p50 / p95). Gripper >= 5 (above).
+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
+ (sim 0; before 2026-10-24: 120.8 deg real).
+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
+ of straight ahead, 6-30 cm apart, plate yaw within 30 deg of the cube yaw (mod 90). Place them after HOME, before
+ you type `RUN`. (8 of the 15 recorded cubes were 0.28-0.34 m out: outside the training region.)
+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
+ 15 recorded cubes). Keep `--table-z 0`: the gripper floor then stays 5 mm or more above the real table.
+ CPU MuJoCo with this table (held-out tasks, 100 each): the robot student 89 % (normal starts) / 91 % (HOME).
+ Optional correction `--q-offset-deg 0,-2.086,0,0,0` (shoulder_lift joint-map offset = the x tilt of the fitted
+ table plane; correct only if the arm base is really tilted, not for a shoulder_lift calibration error): 90 / 94 %.
+ Flat students only (`live-tilt`); never with a plane bundle (the floor would go 2-8.5 mm into the mat; refused).
+ A flat table 10 mm lower: 96 / 98 %. Level table: 98 / 98 %. If you can, make the table level with the arm base.
+ `--table-z` is one flat height: a value below -0.005 lets the gripper reach the table at the high side.
+ Students trained with the v8 table randomisation (checkpoint `v8_online.table_bias`; configs
+ `configs/so101_policy/vision/viral_r2s_online_v8_*`) learned to go down to the real table: they run in floor mode
+ plane (section "Floor modes"; the bundle and `--floor-mode auto` choose it): the floor and the guard's floor
+ checks 1.5 mm / -5 mm / -2 mm above the calibrated table plane, never `--table-z 0` (that floor is ~13 mm above the
+ real table at the cubes and holds the descent up), never the flat eval stops on top of the plane and never
+ `live-tilt` / `--q-offset-deg`.
+5. Workspace clear, you at the robot, one hand near the arm, the other on the keyboard (q / space / Esc / Ctrl+C).
+ 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
+ 0.03-0.04 rad.
+6. At the end the torque stays ON (holding). Menu: `r` slow return to the start pose, then `t` + `TORQUE OFF`
+ with a hand under the arm. `h` (or Enter) exits holding.
+
+## 4. What the live run does
+
+1. Before any write: LeRobot calibration file present and equal to the motors' registers; 3 joint reads finite and
+ inside the calibrated range; both cameras 640 x 480, frames younger than 200 ms.
+2. `--configure auto`: only if a register differs from LeRobot's `configure` values, it asks for `CONFIGURE` (torque
+ off for a moment; the arm must rest on its stops).
+3. HOME: the joint path is checked (sim joint range, calibrated range, lowest gripper point, grasp-point box); you
+ type `MOVE`; goal = present position, torque on, cosine move; the path waits while the arm lags > 0.25 rad and
+ stops after 2 s of lag.
+4. You place the cube and the plate and type `RUN`: the student loop, up to `--time-limit` s (sim episodes are 8 s).
+5. End (time, key, guard): HOLD (arm goal = measured q, gripper = its last command), then the menu.
+
+| Per control step (20 ms; a student query every 5 steps) | Value |
+|---|---|
+| Images | newest frame of each camera, crop of the checkpoint (`cfg.crops`), resize to 224 (INTER_AREA), RGB |
+| Joints | LeRobot units <-> sim rad by `calib_v1.json` `joint_map`; qdot from the last 3 reads |
+| 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 |
+| 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 |
+
+## 5. What to record
+
+- The `--out` folders (dry, live, replay): `episode_*.npz` / `.json`, `first_frames.npz`, `replay_*`.
+- A phone video from the side, started before `RUN`.
+- A photo of the scene and the cube / plate positions (x, y from the base, yaw) before `RUN`.
+- Per run: end reason, reached the cube (yes / no), grasp height vs the cube, lift, place, manual stops.
+- The timing lines at the end of the dry run (`latency ms_model`, `ms_step`, overruns).
+
+## Not tested / open
+
+- Nothing ran against the real bus or cameras (`LeRobotIO` was checked only against LeRobot's source).
+- 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
+ (46.7 Hz instead of 50). The Orin's time is unknown (dry run / replay a).
+- Blank or wrong camera images are not detected (only the frame age). On the fake robot (constant grey images) the
+ student moved the arm 87 deg (shoulder lift) and 127 deg (wrist roll) in 15 s with no stop.
+- The jaw may open at the measured arm pose even if the moving jaw then goes lower; the command-floor stop (-2 mm)
+ can end a good release. If so: `--guard '{"cmd_floor_m": -0.005}'`.
+- Servo dynamics (STS3215, LeRobot P 16 / D 32) were not compared with the sim actuators. Replay images are H.264
+ re-encodes, live images MJPG decodes. No undistortion (the student was trained on renders with the calibrated fisheye models).
diff --git a/so101_pick_place/code/scripts/so101_policy/real2sim/hw/hw_lib.py b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/hw_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a6a2b305bb3fa299e031ace8df552049cd4d4a7
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/hw_lib.py
@@ -0,0 +1,1140 @@
+"""Real-robot side of the SO101 camera student (real2sim study): the pieces that the replay, dry and live modes of
+``run_student_real.py`` share, and that ``tests/so101_policy/test_real2sim_hw.py`` tests.
+
+Pure numpy / torch (+ cv2 for images). No mujoco, no newton / warp, no LeRobot import in this file: it must run on
+the Jetson AGX Orin of the real robot (aarch64, torch 2.11, LeRobot 0.6.2, no mujoco).
+
+Units and frames
+- Real joints = LeRobot 0.6.2 ``so101_follower`` units (``use_degrees=True``): 5 arm joints in degrees
+ (0 = middle of the calibrated range: deg = (raw - (range_min + range_max) / 2) * 360 / 4095), gripper 0-100
+ (0 = range_min). Order ``JOINTS``.
+- Sim joints = the pinned MuJoCo Menagerie so101 joint angles (rad), same order, gripper = the moving jaw angle.
+- Joint map (``calib_v1.json`` "joint_map"): sim_rad[i] = sign[i] * radians(real_deg[i]) + offset_rad[i] for the 5 arm
+ joints, sim jaw rad = a * real_gripper + b. ``JointMap.placeholder_identity`` (sign +1, offset 0, a = pi / 180,
+ b = 0) is a placeholder only (signs and offsets NOT verified); live mode refuses it.
+- World = arm base frame, z up, sim table top z = 0 (``table_z`` shifts the floor if the real table is elsewhere; the
+ floor mode "plane" puts it above the calibrated real mat plane instead, ``student_floor_mode``).
+
+Control timing (as in the sim: ``joint_env``): one 20 ms step per target; a student query every ``n_exec`` (5) steps
+= 0.1 s; the query sees the measured q, a qdot estimate and the newest camera frames; it returns a chunk of 10 absolute
+targets, the first 5 are executed, each through the stateless action layer (``ActionLayer`` = ``joint_env.safety``:
+lead band around the measured q of THAT step, the collector's joint range, the table floor from the kinematics).
+The hardware guard (``Guard``) adds limits that the sim does not have (command change per step, LeRobot-unit range
+and max relative target, workspace box, hard floor, tracking error); it never loosens the action layer.
+"""
+from __future__ import annotations
+
+import json
+import math
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+
+JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper")
+ARM = 5
+DT = 0.02 # s, one control step (world.CONTROL_DT)
+FPS_REC = 30 # LeRobot recordings
+STS_RES = 4096 # STS3215 ticks per turn (LeRobot: max_res = resolution - 1 = 4095)
+REAL_CAMERAS = ("external", "wrist")
+DEFAULT_CAM_MAP = {"top": "external", "external": "external", "wrist": "wrist"}
+# HOME45 pose in SIM degrees (the sim teacher check and its task sets, ``teacher_home_check.py``; the robot's HOME until
+# 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)
+# 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
+# 95.1 %, McNemar p 0.002 on the 500 tasks not used to choose it; roll 30-60 all >= 97 %, roll -45 91 %;
+# ~/so101_r2s_claude/teacher_check). Real LeRobot degrees with calib_v1: (0.0, -3.2, -6.5, 93.1, 120.8), gripper 31.2.
+HOME_SIM_DEG = (0.0, -5.0, -15.0, 92.0, 45.0, 30.0)
+# The robot's default HOME (run_student_real.py --home, the bundles' assets/deploy.json; 2026-10-24): HOME45 with wrist
+# roll 0. The real wrist roll stops at +101.2 sim deg (RealLimits: calibrated range end - 3 deg); from roll 45 many
+# episodes turn the roll into that stop (115 robot episodes: 26 reached it, 9 stalls; sysid_v8.json "roll"). Sim
+# tests with the real roll stop (2026-10-24): robot-feasible success C1 59-66 % -> 87-88 %, s28 60-68 % -> 95 % with
+# 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,
+# 0.14) m, lowest gripper point 121 mm.
+ROBOT_HOME_SIM_DEG = (0.0, -5.0, -15.0, 92.0, 0.0, 30.0)
+
+
+# ---- calibration file ---------------------------------------------------------------------------------------------
+def parse_table_plane(spec, calib=None):
+ """``run_student_real.py --table-plane``: "" (off -> None), "calib" (calib_v1 scene.table_plane coef, the measured
+ real table) or "c0,c1,c2" (m, z = c0 + c1 x + c2 y) -> (c0, c1, c2) or None."""
+ spec = (spec or "").strip()
+ if not spec:
+ return None
+ if spec == "calib":
+ try:
+ c = (calib or {})["scene"]["table_plane"]["coef"]
+ except (KeyError, TypeError):
+ raise ValueError("--table-plane calib: the calibration has no scene.table_plane.coef") from None
+ else:
+ c = [float(v) for v in spec.split(",")]
+ c = tuple(float(v) for v in c)
+ if len(c) != 3 or not all(math.isfinite(v) for v in c):
+ raise ValueError(f"--table-plane {spec!r}: 'calib' or c0,c1,c2 (m)")
+ return c
+
+
+# ---- floor mode (run_student_real.py --floor-mode; README "Floor") --------------------------------------------------
+# The action-layer floor must have the clearance above the real mat that the student was trained with
+# (~/so101_r2s_claude/v8/sysid/sysid_v8.json table_dz_range_m.coupling_rule):
+# - "flat": students trained on the sim table only (C1, s28, the roll-cap students): floor FLOOR (1.5 mm) above sim
+# z = table_z (0), as in their training; the guard's floor stops are relative to the same z.
+# - "plane": students trained with the v8 table randomisation (checkpoint ``v8_online.table_bias``): in training the
+# floor stays FLOOR above the TRUE table, i.e. above the table plane in the student's (= the real robot's) joint
+# frame; on the robot: FLOOR above the calibrated mat plane (calib_v1 scene.table_plane), and the guard's floor
+# stops relative to that plane too. Today's flat eval stops (-15 / -20 mm, set because the real mat is 8-18 mm
+# below the sim table) must NOT be used on top of the plane (double lowering: stops 15-20 mm into the real mat).
+# - round v12 (2026-10-26): students trained with a FIXED table plane and the flat observed-frame floor (checkpoint
+# ``v8_online.student_floor`` "observed", ``viral.OnlineConfig.student_floor``): in training the floor is flat 1.5
+# mm above z = 0 of the student's (= the robot's) joint frame, i.e. raised by the drop in the true frame -> "flat"
+# (as C1 / D), never the plane floor. Such a student already corrects for the real table: no --q-offset-deg
+# (live-tilt) on top (``floor_frame_problems`` table_frame).
+FLOOR_MODES = ("flat", "plane")
+STUDENT_FLOORS = ("true", "observed") # v8_online.student_floor (absent = "true", the v8 coupling rule)
+# The guard's floor stops of the eval session (robot_test.sh eval, via the bundle's assets/deploy.json) per mode, m:
+# flat = the eval values of 2026-10-22 .. 23 (relative to sim z = table_z 0; unchanged); plane = the GuardConfig
+# defaults, relative to the calibrated mat plane.
+EVAL_FLOOR_GUARD = {"flat": {"cmd_floor_m": -0.015, "hard_floor_m": -0.020},
+ "plane": {"cmd_floor_m": -0.002, "hard_floor_m": -0.005}}
+# ... with the servo-error integral correction (both modes; anti-windup at the real joint range, GuardConfig)
+EVAL_I_GUARD = {"i_time_s": 0.2, "i_max_deg": 3.0, "i_antiwindup": True}
+# Plane mode: floor stops deeper than this below the mat plane are refused in live mode (double lowering; m)
+PLANE_STOP_MIN_M = {"cmd_floor_m": -0.005, "hard_floor_m": -0.008}
+# The calibrated mat plane at the 184 observed cube and plate positions of the robot logs, mm relative to sim z = 0
+# (sysid_v8.json table.json "plane at cubes + plates" min / max): for the banner's flat-mode clearances
+OBSERVED_MAT_MM = (-17.47, -8.31)
+# ... 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;
+# sysid_v8.json table_dz_range_m.deployment.plane_on_task_annulus_mm): the mat is highest at the far +y edge
+TASK_R_M, TASK_DEG = (0.15, 0.27), 75.0
+TASK_MAT_MM = (-17.1036, -3.8492)
+PAN_AXIS_X = 0.0388 # m, the vertical pan axis in the world (kin.PAN_AXIS_XY)
+# A --table-plane c0,c1,c2 other than "calib": live refuses it if it is more than this below the calibrated mat plane
+# anywhere on r TASK_R_M, +-PLANE_CHECK_DEG (the floor would be in the mat; m)
+PLANE_CHECK_DEG, PLANE_LOW_TOL_M = 90.0, 0.001
+
+
+def eval_guard(mode):
+ """The eval session's guard overrides (``GuardConfig`` dict) of floor mode ``mode``."""
+ if mode not in FLOOR_MODES:
+ raise ValueError(f"floor mode {mode!r}: one of {FLOOR_MODES}")
+ return {**EVAL_FLOOR_GUARD[mode], **EVAL_I_GUARD}
+
+
+def student_floor_mode(meta):
+ """Checkpoint keys of a student (``StudentPolicy.meta``: everything but the weights) -> (floor mode, why): "plane"
+ if it was trained with the v8 table randomisation (``v8_online.table_bias`` on, ``table_bias.is_on``, with a
+ probability ``p`` > 0 of a lower / tilted table) under the v8 floor rule (``v8_online.student_floor`` absent or
+ "true"); "flat" for the round v12 students (``student_floor`` "observed": the flat arm-frame floor in training)
+ and for students trained on the sim table. An unknown ``student_floor`` raises ValueError (no guess)."""
+ from nedm.so101_policy import table_bias as TBI
+ v8 = dict((meta or {}).get("v8_online") or {})
+ tb = dict(v8.get("table_bias") or {})
+ sf = v8.get("student_floor", "true")
+ if sf not in STUDENT_FLOORS:
+ raise ValueError(f"checkpoint v8_online.student_floor {sf!r}: one of {STUDENT_FLOORS}")
+ p = float(tb.get("p", TBI.TableBiasConfig.p))
+ if TBI.is_on(tb) and p > 0.0 and sf == "observed":
+ return "flat", ("trained in the table frame of {what} 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").format(what=f"the fixed plane {tb.get('plane')} (c0, c1, c2 m)" if tb.get("plane")
+ else f"table planes (p {tb.get('p')}, drop {tb.get('drop_mm')} mm)")
+ if TBI.is_on(tb) and p > 0.0:
+ return "plane", ("trained with the v8 table randomisation (checkpoint v8_online.table_bias: p {p}, drop {d} mm "
+ "at x {x} m, slope x {sx} / y {sy} mm per m)").format(
+ 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"))
+ if TBI.is_on(tb):
+ return "flat", f"trained on the sim table (checkpoint v8_online.table_bias with p {p:g}: never a lower table)"
+ return "flat", "trained on the sim table (no v8_online.table_bias in the checkpoint)"
+
+
+def plane_depth_below(plane, ref, r=TASK_R_M, deg=PLANE_CHECK_DEG):
+ """How far (m, >= 0) the plane ``plane`` (c0, c1, c2) lies below ``ref`` at most on r ``r`` about the pan axis,
+ angle +-``deg`` (0 = nowhere below)."""
+ rr, aa = np.meshgrid(np.linspace(r[0], r[1], 13), np.radians(np.linspace(-deg, deg, 181)))
+ x, y = PAN_AXIS_X + rr * np.cos(aa), rr * np.sin(aa)
+ d = np.asarray(plane, np.float64) - np.asarray(ref, np.float64)
+ return float(max(0.0, -(d[0] + d[1] * x + d[2] * y).min()))
+
+
+def floor_problems(mode, student_mode, gcfg, plane_spec="calib", plane=None, calib_plane=None):
+ """Floor settings that do not fit the student -> list of strings (empty = ok): a floor mode other than the
+ student's (``student_floor_mode``), plane-mode floor stops deeper than ``PLANE_STOP_MIN_M`` (double lowering), or a
+ plane mode ``plane_spec`` other than "calib" whose ``plane`` lies more than ``PLANE_LOW_TOL_M`` below the
+ calibrated mat plane ``calib_plane`` (None: not known, also a problem) on the task area (``plane_depth_below``).
+ run_student_real.py: live refuses them (unless --allow-floor-mismatch), dry / replay warn. The joint-map offset
+ rule is ``floor_frame_problems`` (no override)."""
+ bad = []
+ if mode != student_mode:
+ bad.append(f"floor mode {mode} but the student needs {student_mode}")
+ if mode == "plane":
+ for k, lim in PLANE_STOP_MIN_M.items():
+ v = float(getattr(gcfg, k))
+ if v < lim:
+ bad.append(f"guard {k} {v * 1e3:g} mm below the mat plane (plane mode allows down to {lim * 1e3:g} "
+ f"mm: deeper stops = double lowering, the gripper may press the table)")
+ if plane is not None and (plane_spec or "calib") != "calib":
+ if calib_plane is None:
+ bad.append(f"--table-plane {plane_spec}: the calibration has no scene.table_plane to check it against")
+ else:
+ dz = plane_depth_below(plane, calib_plane)
+ if dz > PLANE_LOW_TOL_M:
+ bad.append(f"--table-plane {plane_spec} is up to {dz * 1e3:.1f} mm below the calibrated mat plane "
+ f"(r {TASK_R_M[0]}-{TASK_R_M[1]} m, +-{PLANE_CHECK_DEG:g} deg; allowed "
+ f"{PLANE_LOW_TOL_M * 1e3:g} mm): the floor would be in the mat")
+ return bad
+
+
+def student_table_frame(meta) -> bool:
+ """True if the student was trained in a table frame (``v8_online.table_bias`` on with p > 0: v8 plane students and
+ the round v12 flat-floor table students): it already corrects for the real table."""
+ from nedm.so101_policy import table_bias as TBI
+ tb = dict(((meta or {}).get("v8_online") or {}).get("table_bias") or {})
+ return bool(TBI.is_on(tb) and float(tb.get("p", TBI.TableBiasConfig.p)) > 0.0)
+
+
+def student_floor_observed(meta) -> bool:
+ """True for the round v12 students trained under the flat arm-frame floor (checkpoint ``v8_online.student_floor``
+ "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."""
+ return ((meta or {}).get("v8_online") or {}).get("student_floor", "true") == "observed"
+
+
+def floor_frame_problems(mode, q_offset_deg=None, table_frame=False, observed=False, table_z=0.0):
+ """Plane mode with an extra joint-map offset (run_student_real.py --q-offset-deg, e.g. live-tilt's table-tilt
+ correction 0,-2.086,0,0,0) -> list of strings (empty = ok). The calibrated mat plane is measured in the plain
+ calib_v1 joint frame; an offset turns the arm frame against it, and the floor and the floor checks then see the
+ 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
+ in the mat). The tilt correction is for flat students only (the plane floor already follows the real table).
+ ``table_frame`` (``student_table_frame``: also the round v12 flat-floor table students): any offset is refused as
+ well (the student corrects for the real table itself). ``observed`` (``student_floor_observed``: the round v12
+ students trained under the flat floor 1.5 mm above z 0 of the arm frame) with a ``table_z`` (--table-z) other than
+ 0: the floor would move by table_z from the floor the student was trained with (e.g. -0.0126 = 12.6 mm lower),
+ refused as well. run_student_real.py: live refuses these with no override, dry / replay warn."""
+ bad = []
+ if observed and float(table_z) != 0.0: # round v12 flat-floor students (``student_floor_observed``)
+ bad.append(f"--table-z {float(table_z):g} with a student trained under the flat arm-frame floor (checkpoint "
+ "v8_online.student_floor observed): its floor was 1.5 mm above z 0 of the arm frame in training; "
+ f"--table-z moves it {abs(float(table_z)) * 1e3:.1f} mm {'lower' if table_z < 0 else 'higher'} "
+ "(leave --table-z at 0)")
+ qo = np.zeros(ARM) if q_offset_deg is None else np.asarray(q_offset_deg, np.float64)
+ if mode == "plane" and np.any(qo != 0.0):
+ return bad + [f"--q-offset-deg {','.join(f'{v:g}' for v in qo)} in floor mode plane: the mat plane is in the "
+ "calib_v1 joint frame, an offset moves the floor into the mat (live-tilt / --q-offset-deg are "
+ "for flat students only)"]
+ if table_frame and np.any(qo != 0.0): # round v12 flat-floor table students (``student_table_frame``)
+ return bad + [f"--q-offset-deg {','.join(f'{v:g}' for v in qo)} with a student trained in the table frame: "
+ "it already corrects for the real table (the offset would correct twice; live-tilt / "
+ "--q-offset-deg are for students trained on the sim table only)"]
+ return bad
+
+
+def floor_lines(mode, why, table_z, plane, gcfg):
+ """The banner's floor lines (mm, relative to the real mat at the observed cube / plate positions)."""
+ from nedm.so101_policy import joint_env as JE
+ f = JE.FLOOR * 1e3
+ cmd, hard = gcfg.cmd_floor_m * 1e3, gcfg.hard_floor_m * 1e3
+ if mode == "plane":
+ c0, c1, c2 = plane
+ return [f"FLOOR MODE plane: student {why}",
+ f" floor {f:.1f} mm above the mat plane z = {c0 * 1e3:.1f} mm {c1 * 1e3:+.1f} x {c2 * 1e3:+.1f} y "
+ f"(mm per m; calib_v1 scene.table_plane); stops: command {-cmd:.1f} mm, measured {-hard:.1f} mm below "
+ f"the plane. Relative to the real mat (everywhere, +-3 mm calibration): floor {f:+.1f} mm, command "
+ f"stop {cmd:+.1f} mm, measured stop {hard:+.1f} mm"]
+ z = table_z * 1e3
+
+ def rng(v, mat): # a height relative to sim z = 0 -> relative to the mat (mat range vs sim z 0, mm)
+ a, b = v - mat[1], v - mat[0]
+ return f"{a:+.1f} .. {b:+.1f} mm"
+ (lo, hi), (tlo, thi) = OBSERVED_MAT_MM, TASK_MAT_MM
+ return [f"FLOOR MODE flat: student {why}",
+ f" floor {f:.1f} mm above sim z = table_z {z:+.1f} mm; stops: command {cmd:+.1f} mm, measured {hard:+.1f} "
+ f"mm (+ table_z). Relative to the real mat at the observed cube / plate positions ({lo:.1f} .. {hi:.1f} mm "
+ f"vs sim z 0): floor {rng(z + f, OBSERVED_MAT_MM)}, command stop {rng(z + cmd, OBSERVED_MAT_MM)}, measured "
+ f"stop {rng(z + hard, OBSERVED_MAT_MM)}",
+ 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 "
+ f"0): floor {rng(z + f, TASK_MAT_MM)}, command stop {rng(z + cmd, TASK_MAT_MM)}, measured stop "
+ f"{rng(z + hard, TASK_MAT_MM)}"]
+
+
+def load_calib(path):
+ """calib_v1.json (the study's calibration contract) -> dict, or None if the path is empty / missing."""
+ if not path:
+ return None
+ p = Path(path).expanduser()
+ if not p.exists():
+ return None
+ return json.loads(p.read_text())
+
+
+@dataclass
+class JointMap:
+ """real (LeRobot units) <-> sim (rad), module docstring."""
+ sign: np.ndarray
+ offset_rad: np.ndarray
+ grip_a: float
+ grip_b: float
+ placeholder: bool = False
+ source: str = ""
+
+ def __post_init__(self):
+ self.sign = np.asarray(self.sign, np.float64).reshape(ARM)
+ self.offset_rad = np.asarray(self.offset_rad, np.float64).reshape(ARM)
+ if not np.all(np.isin(self.sign, (-1.0, 1.0))):
+ raise ValueError(f"joint_map sign must be +1 / -1, got {self.sign.tolist()}")
+ if not np.all(np.isfinite(self.offset_rad)):
+ raise ValueError("joint_map offset_rad must be finite")
+ self.grip_a, self.grip_b = float(self.grip_a), float(self.grip_b)
+ if not (math.isfinite(self.grip_a) and math.isfinite(self.grip_b)) or abs(self.grip_a) < 1e-9:
+ raise ValueError(f"joint_map gripper_lin invalid: {[self.grip_a, self.grip_b]}")
+
+ @staticmethod
+ def placeholder_identity():
+ return JointMap(np.ones(ARM), np.zeros(ARM), math.pi / 180.0, 0.0, placeholder=True,
+ source="placeholder identity (no calib_v1.json joint_map; signs / offsets NOT verified)")
+
+ @staticmethod
+ def from_dict(d, source="calib"):
+ names = d.get("names")
+ if names is not None and tuple(names)[:ARM] != JOINTS[:ARM]:
+ raise ValueError(f"joint_map names {names} differ from {JOINTS}")
+ lin = d["gripper_lin"]
+ return JointMap(d["sign"][:ARM], d["offset_rad"][:ARM], lin[0], lin[1],
+ placeholder=bool(d.get("placeholder", False)), source=source)
+
+ @staticmethod
+ def from_calib(calib, source="calib"):
+ if calib is None or "joint_map" not in calib:
+ return JointMap.placeholder_identity()
+ return JointMap.from_dict(calib["joint_map"], source)
+
+ def real_to_sim(self, real):
+ r = np.asarray(real, np.float64)
+ out = np.empty_like(r)
+ out[..., :ARM] = self.sign * np.radians(r[..., :ARM]) + self.offset_rad
+ out[..., ARM] = self.grip_a * r[..., ARM] + self.grip_b
+ return out
+
+ def sim_to_real(self, sim):
+ s = np.asarray(sim, np.float64)
+ out = np.empty_like(s)
+ out[..., :ARM] = np.degrees(self.sign * (s[..., :ARM] - self.offset_rad))
+ out[..., ARM] = (s[..., ARM] - self.grip_b) / self.grip_a
+ return out
+
+ def describe(self):
+ return dict(sign=self.sign.tolist(), offset_rad=self.offset_rad.tolist(), gripper_lin=[self.grip_a, self.grip_b],
+ placeholder=self.placeholder, source=self.source)
+
+
+@dataclass
+class RealLimits:
+ """Allowed real targets (LeRobot units) from the LeRobot calibration file: the calibrated range of every motor
+ minus ``margin`` (arm deg / gripper units)."""
+ lo: np.ndarray
+ hi: np.ndarray
+ source: str = ""
+
+ @staticmethod
+ def from_lerobot_calibration(cal, margin_deg=3.0, margin_grip=0.0, source=""):
+ if isinstance(cal, (str, Path)):
+ source = source or str(cal)
+ cal = json.loads(Path(cal).expanduser().read_text())
+ lo, hi = np.zeros(6), np.zeros(6)
+ for i, m in enumerate(JOINTS):
+ c = cal[m]
+ mn, mx = float(c["range_min"]), float(c["range_max"])
+ if int(c.get("drive_mode", 0)) != 0:
+ raise ValueError(f"{m}: drive_mode {c['drive_mode']} not handled (expected 0)")
+ if i < ARM:
+ mid = (mn + mx) / 2
+ lo[i] = (mn - mid) * 360.0 / (STS_RES - 1) + margin_deg
+ hi[i] = (mx - mid) * 360.0 / (STS_RES - 1) - margin_deg
+ else:
+ lo[i], hi[i] = 0.0 + margin_grip, 100.0 - margin_grip
+ return RealLimits(lo, hi, source)
+
+ def clip(self, real):
+ r = np.asarray(real, np.float64)
+ c = np.minimum(np.maximum(r, self.lo), self.hi)
+ return c, np.abs(c - r) > 1e-9
+
+ def outside(self, real, tol=0.0):
+ r = np.asarray(real, np.float64)
+ return (r < self.lo - tol) | (r > self.hi + tol)
+
+
+# ---- images ---------------------------------------------------------------------------------------------------------
+# ONE crop + resize for sim and real: src/nedm/render/student_view.py (numpy + cv2 only), also used by the renderer
+# (nedm.render.so101.RealScene). Loaded by file path, so no nedm.render package import (no torch / newton / warp).
+def _load_student_view():
+ import importlib.util
+ import os
+ import sys
+ mod = sys.modules.get("nedm.render.student_view")
+ if mod is not None:
+ return mod
+ roots = [os.environ.get("NEDM_SRC"), str(Path(__file__).resolve().parents[4] / "src")]
+ for root in roots:
+ if not root:
+ continue
+ path = Path(root) / "nedm/render/student_view.py"
+ if path.exists():
+ spec = importlib.util.spec_from_file_location("_nedm_student_view", path)
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = mod # dataclasses need the module registered
+ spec.loader.exec_module(mod)
+ return mod
+ raise ImportError("src/nedm/render/student_view.py not found (NEDM_SRC or the repo / bundle layout): the robot "
+ "bundle must contain it (make_orin_bundle.sh)")
+
+
+_SV = _load_student_view()
+ViewSpec = _SV.ViewSpec
+centre_square = _SV.centre_square
+view_specs = _SV.view_specs # (calib, real_cams, out_res, width=640, height=480, interp="area")
+preprocess = _SV.crop_resize # (img, spec, bgr): crop box, then cv2 resize -> RGB uint8 [out_h, out_w, 3]
+_INTERP = _SV._INTERP
+
+
+def thumb(img, res):
+ import cv2
+ return cv2.resize(img, (res, res), interpolation=cv2.INTER_AREA) if res and img.shape[0] != res else img
+
+
+# ---- qdot ---------------------------------------------------------------------------------------------------------
+class QdotEstimator:
+ """Joint velocity (rad/s) from the measured q of the last ``window`` control steps: least-squares slope over the
+ window (window 3 = 40 ms span, about 20 ms lag). Restarts after a gap > ``max_gap`` s. The sim student saw the exact
+ joint velocity (training noise 0.3 x its std); the STS3215 position resolution is 1.5 mrad."""
+
+ def __init__(self, window=3, max_gap=0.1):
+ self.window, self.max_gap = int(window), float(max_gap)
+ self.reset()
+
+ def reset(self):
+ self.t, self.q = [], []
+
+ def update(self, t, q):
+ q = np.asarray(q, np.float64)
+ if self.t and (t - self.t[-1] > self.max_gap or t <= self.t[-1]):
+ self.reset()
+ self.t.append(float(t))
+ self.q.append(q)
+ if len(self.t) > self.window:
+ self.t.pop(0)
+ self.q.pop(0)
+ if len(self.t) < 2:
+ return np.zeros_like(q)
+ tt = np.asarray(self.t)
+ qq = np.stack(self.q)
+ tc = tt - tt.mean()
+ return (tc[:, None] * (qq - qq.mean(0))).sum(0) / (tc ** 2).sum()
+
+
+# ---- the action layer (sim) and the hardware guard ---------------------------------------------------------------
+def default_kin_points():
+ """The SO101 gripper / moving-jaw collision points (.npz, ``kin.save_points``): first that exists of
+ $SO101_HW_ASSETS/kin_points_v1.npz, /assets/kin_points_v1.npz,
+ /artifacts/so101_pick_place/rl_inputs/geometry/kin_points_v1.npz (the downloaded file)."""
+ import os
+ here = Path(__file__).resolve()
+ cands = []
+ if os.environ.get("SO101_HW_ASSETS"):
+ cands.append(Path(os.environ["SO101_HW_ASSETS"]) / "kin_points_v1.npz")
+ if len(here.parents) > 4:
+ cands.append(here.parents[4] / "assets" / "kin_points_v1.npz")
+ if len(here.parents) > 4:
+ cands.append(here.parents[4] / "artifacts" / "so101_pick_place" / "rl_inputs" / "geometry" / "kin_points_v1.npz")
+ for c in cands:
+ if c.exists():
+ return c
+ return None
+
+
+class ActionLayer:
+ """``joint_env.safety`` for one robot (the action layer of teacher and student): arm targets within ``joint_env.LEAD``
+ of the measured q, all targets within the collector's range (kin.TLO .. THI), the table floor (``floor_guard``:
+ lowest gripper / moving-jaw point >= ``joint_env.FLOOR`` + table_z unless the measured pose is lower). The kinematics
+ use the saved collision points (no mujoco).
+
+ ``table_plane`` (c0, c1, c2) (real2sim v8; None = off, the old flat floor bit for bit): the floor follows a tilted
+ table instead: the lowest point's height ABOVE the plane z = c0 + c1 x + c2 y (``kin.lowest_point(plane=)``) >=
+ FLOOR, and the guard's floor checks (``Guard``, ``check_path``) measure above the plane too (``floor_height``). A
+ student trained with the v8 table randomisation (the floor 1.5 mm above the TRUE table in training) deploys with
+ the calibrated plane (``run_student_real.py --table-plane calib``), never with the flat ``table_z`` 0 (~13 mm above
+ the real table at the cubes). Exclusive with ``table_z``."""
+
+ def __init__(self, kin_points, table_z=0.0, lead=True, floor=True, table_plane=None):
+ import torch
+
+ from nedm.so101_policy import joint_env as JE
+ from nedm.so101_policy.kin import SO101Kin
+ if kin_points is None or not Path(kin_points).expanduser().exists():
+ raise FileNotFoundError(f"kin points file {kin_points} missing (needed for the table floor without mujoco)")
+ self.torch, self.JE = torch, JE
+ self.kin = SO101Kin("cpu", points=str(Path(kin_points).expanduser()))
+ self.tlo, self.thi = self.kin.tlo.clone(), self.kin.thi.clone()
+ self.lead = torch.tensor(JE.LEAD, dtype=torch.float64) if lead else None
+ self.table_z = float(table_z)
+ self.plane = None
+ if table_plane is not None:
+ self.plane = tuple(float(c) for c in table_plane)
+ if len(self.plane) != 3 or not all(math.isfinite(c) for c in self.plane):
+ raise ValueError(f"table_plane {table_plane}: (c0, c1, c2), z = c0 + c1 x + c2 y (m)")
+ if self.table_z != 0.0:
+ raise ValueError("table_plane and table_z: give one of them")
+ self.floor = JE.FLOOR + self.table_z if floor else None
+ self.lowest(np.zeros(6)) # builds the reduced point set now (0.4 s on luffy), not in the first step
+
+ def __call__(self, u, q):
+ """u, q: sim rad [6] -> (u' [6], dict lead / range / floor: which rule changed the target)."""
+ t = self.torch
+ u0 = t.as_tensor(np.asarray(u, np.float64))[None]
+ q0 = t.as_tensor(np.asarray(q, np.float64))[None]
+ if self.plane is None:
+ out = self.JE.safety(u0, q0, self.tlo, self.thi, self.lead, self.kin, self.floor)[0].numpy()
+ else:
+ out = self.JE.safety(u0, q0, self.tlo, self.thi, self.lead, self.kin, self.floor,
+ floor_plane=self.plane)[0].numpy()
+ # attribution of the change (diagnostics only)
+ u1 = u0.clone()
+ if self.lead is not None:
+ u1[:, :ARM] = t.minimum(t.maximum(u1[:, :ARM], q0[:, :ARM] - self.lead), q0[:, :ARM] + self.lead)
+ lead_on = bool((u1 - u0).abs().max() > 1e-12)
+ u2 = t.minimum(t.maximum(u1, self.tlo), self.thi)
+ range_on = bool((u2 - u1).abs().max() > 1e-12)
+ floor_on = bool(np.abs(out - u2[0].numpy()).max() > 1e-12)
+ return out, dict(lead=lead_on, range=range_on, floor=floor_on)
+
+ def lowest(self, q):
+ """Lowest gripper / moving-jaw point (m, world z) of sim poses q [..., 6] (fast point set, as the floor rule)."""
+ t = self.torch
+ qq = t.as_tensor(np.asarray(q, np.float64)).reshape(-1, 6)
+ return self.kin.lowest_point(qq, exact=False).numpy().reshape(np.shape(q)[:-1])
+
+ def floor_height(self, q):
+ """(lowest gripper / moving-jaw point, the floor checks' reference): (``lowest(q)`` world z, ``table_z``) with
+ the flat floor (the old checks unchanged), (height above ``table_plane``, 0.0) with a plane floor."""
+ if self.plane is None:
+ return self.lowest(q), self.table_z
+ t = self.torch
+ qq = t.as_tensor(np.asarray(q, np.float64)).reshape(-1, 6)
+ return self.kin.lowest_point(qq, exact=False, plane=self.plane).numpy().reshape(np.shape(q)[:-1]), 0.0
+
+ def tcp(self, q):
+ """Grasp point (m, world) of sim poses q [..., 6]."""
+ t = self.torch
+ qq = t.as_tensor(np.asarray(q, np.float64)).reshape(-1, 6)
+ p, _ = self.kin.fk(qq)
+ return p.numpy().reshape(*np.shape(q)[:-1], 3)
+
+
+@dataclass
+class GuardConfig:
+ """Hardware limits on top of the action layer (module docstring). Sim teacher labels for scale (build9 d1 r0,
+ 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
+ 0.18 rad between decisions; jaw up to 1.4 rad between decisions."""
+ max_step_rad: tuple = (0.06, 0.06, 0.06, 0.06, 0.08, 0.5) # command change per 20 ms step (sim rad)
+ max_rel_real: tuple = (10.0, 10.0, 10.0, 10.0, 10.0, 60.0) # |command - measured| (LeRobot units)
+ range_margin_deg: float = 3.0 # inside the LeRobot calibrated range
+ measured_range_tol: float = 5.0 # measured q may be this far outside (deg) before a stop
+ hard_floor_m: float = -0.005 # stop if the MEASURED lowest gripper point is below table_z + this (or this
+ # above the layer's table_plane)
+ cmd_floor_m: float = -0.002 # stop if the COMMANDED lowest point is below table_z + this (after the layer)
+ tcp_x: tuple = (-0.10, 0.45) # grasp point box (m, world)
+ tcp_y: tuple = (-0.42, 0.42)
+ tcp_z: tuple = (-0.01, 0.40)
+ tcp_r_max: float = 0.45 # grasp point distance from the pan axis (m)
+ stall_frac: float = 0.9 # live only: an arm joint that stays >= stall_frac x its lead band (joint_env.LEAD)
+ stall_steps: int = 25 # from the previous command for stall_steps steps (0.5 s) is blocked: stop
+ i_time_s: float = 0.0 # integral correction of the real servos' static error (0 = off; arm joints):
+ i_max_deg: float = 3.0 # each step adds (command - measured q) * DT / i_time_s, the sum <= i_max_deg,
+ i_v_min: float = 0.02 # only while the joint does not move to its command faster than this (rad/s)
+ i_e_max_deg: float = 1.0 # and only while |command - measured q| < this (not for a blocked joint)
+ i_antiwindup: bool = True # not on a joint at its LeRobot-unit range (Guard.apply; False = the rule
+ # of the robot days 2026-10-22 .. 23)
+
+ @staticmethod
+ def from_dict(d):
+ d = dict(d or {})
+ known = set(GuardConfig.__dataclass_fields__)
+ bad = sorted(set(d) - known)
+ if bad:
+ raise ValueError(f"unknown guard keys {bad}")
+ return GuardConfig(**{k: (tuple(v) if isinstance(v, list) else v) for k, v in d.items()})
+
+
+class Guard:
+ """Hardware guard (``GuardConfig``). ``check_measured`` -> stop reasons of the measured state; ``apply`` -> the
+ command (sim and real units) after: step limit vs the previous command, the action layer, LeRobot-unit range and
+ max relative target vs the measured q, then the final checks (finite, workspace box, commanded floor).
+
+ ``u_layer`` (sim rad [6], None before the first ``apply`` or after a non-finite target): the target of the last
+ ``apply`` right after the step limit and the action layer, BEFORE the integral correction and the LeRobot-unit
+ clamps = the sim's executed target (``joint_env`` ``u_exe``). The command input of a ``cmd_in`` student reads it,
+ never the sent command (``u_sim``: + the integral correction) or ``prev`` (+ the LeRobot clamps).
+
+ Anti-windup of the integral correction (``GuardConfig.i_antiwindup``, on by default; real2sim 2026-10-24): a joint
+ at its LeRobot-unit range (``real_range_sim``) cannot follow a correction. Without the rule the integral grew there
+ (robot 2026-10-23, eval_20261023_141614 ep 6 and eval_20261023_144431 ep 1: measured wrist roll 100.69 sim deg,
+ 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
+ command stayed clipped at 101.21, ``prev`` = 101.21 - 3 = 98.2 deg, 2.5 deg >= 0.9 x LEAD from the measured roll:
+ "stall: wrist_roll blocked" after 25 steps). With the rule, on a joint whose action-layer target or student target
+ is at / beyond its range, or whose corrected command would be clipped there, the error is not integrated; the
+ correction is 0 on a joint whose action-layer target is at / beyond its range (either sign: the sent command is
+ the clipped target and ``prev`` = that command, as without the integral), else limited to [lo - target,
+ hi - target] (it never pushes the command past the range; ``prev`` = the target). Joints inside their range are
+ not changed. ``i_aw`` [5] bool: the arm joints the rule held in the last ``apply`` (at /
+ beyond the range; logged per step as ``i_aw``)."""
+
+ def __init__(self, cfg: GuardConfig, layer: ActionLayer, jmap: JointMap, limits: RealLimits):
+ self.cfg, self.layer, self.jmap, self.limits = cfg, layer, jmap, limits
+ self.max_step = np.asarray(cfg.max_step_rad, np.float64)
+ self.max_rel = np.asarray(cfg.max_rel_real, np.float64)
+ self.prev = None
+ self.err_run = 0
+ self.integ = np.zeros(ARM)
+ self.i_aw = np.zeros(ARM, bool)
+ self.u_layer = None
+
+ def reset(self, q_sim):
+ self.prev = np.asarray(q_sim, np.float64).copy()
+ self.err_run = 0
+ self.integ = np.zeros(ARM)
+ self.i_aw = np.zeros(ARM, bool)
+ self.u_layer = None
+
+ def real_range_sim(self):
+ """The LeRobot-unit range (``limits``: calibrated range - margin) of the 5 arm joints in sim rad -> (lo, hi)."""
+ a = self.jmap.real_to_sim(self.limits.lo)[:ARM]
+ b = self.jmap.real_to_sim(self.limits.hi)[:ARM]
+ return np.minimum(a, b), np.maximum(a, b)
+
+ def _box(self, p):
+ c = self.cfg
+ r = math.hypot(p[0] - 0.0388, p[1])
+ bad = []
+ 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]):
+ bad.append(f"workspace box: grasp point {np.round(p, 3).tolist()} outside")
+ if r > c.tcp_r_max:
+ bad.append(f"reach: grasp point {r:.3f} m from the pan axis > {c.tcp_r_max}")
+ return bad
+
+ def check_measured(self, q_sim, q_real):
+ c, stop = self.cfg, []
+ if not (np.all(np.isfinite(q_sim)) and np.all(np.isfinite(q_real))):
+ return ["measured q: not finite"]
+ out = self.limits.outside(q_real, c.measured_range_tol)
+ if out.any():
+ stop.append("measured range: outside the calibrated range: " + ", ".join(
+ f"{JOINTS[i]} {q_real[i]:.1f}" for i in np.flatnonzero(out)))
+ low, ref = self.layer.floor_height(q_sim) # (flat floor: lowest(q), table_z as before)
+ low = float(low)
+ if low < ref + c.hard_floor_m:
+ stop.append(f"measured floor: lowest gripper point {low * 1e3:.1f} mm"
+ + (" above the table plane" if self.layer.plane is not None else "") + ", below the hard floor")
+ stop += ["measured " + s for s in self._box(self.layer.tcp(q_sim))]
+ return stop
+
+ def apply(self, u_sim, q_sim, q_real, qd_sim=None):
+ """-> (command sim [6], command real [6], events dict, stop reasons). ``qd_sim``: the measured joint speed for
+ the integral correction (None: the joints count as not moving)."""
+ c = self.cfg
+ ev = dict(step=False, lead=False, range=False, floor=False, real_range=False, max_rel=False)
+ u = np.asarray(u_sim, np.float64)
+ self.u_layer, self.i_aw = None, np.zeros(ARM, bool)
+ if not np.all(np.isfinite(u)):
+ return None, None, ev, ["student target: not finite"]
+ if self.prev is None:
+ self.reset(q_sim)
+ d = np.clip(u - self.prev, -self.max_step, self.max_step)
+ ev["step"] = bool(np.any(np.abs(d - (u - self.prev)) > 1e-12))
+ u = self.prev + d
+ u, info = self.layer(u, q_sim)
+ self.u_layer = np.array(u, np.float64) # the sim's executed target (class docstring): before the integral
+ ev.update(info)
+ if c.i_time_s > 0: # the real servos stop short of a small command under load (sim: they follow)
+ imax = math.radians(c.i_max_deg)
+ e = u[:ARM] - np.asarray(q_sim)[:ARM]
+ if qd_sim is not None: # a joint that follows its command needs no correction (no wind-up in motion)
+ e = np.where(np.asarray(qd_sim)[:ARM] * np.sign(e) > c.i_v_min, 0.0, e)
+ e = np.where(np.abs(e) < math.radians(c.i_e_max_deg), e, 0.0) # blocked joint / new target: no more push
+ if c.i_antiwindup: # a joint at its real range: no integration (class docstring)
+ rlo, rhi = self.real_range_sim()
+ t5, s5, c5 = u[:ARM], np.asarray(u_sim, np.float64)[:ARM], u[:ARM] + self.integ
+ tol = 1e-9
+ self.i_aw = ((t5 >= rhi - tol) | (t5 <= rlo + tol) | (s5 > rhi) | (s5 < rlo) | (c5 >= rhi - tol)
+ | (c5 <= rlo + tol))
+ e = np.where(self.i_aw, 0.0, e)
+ self.integ = np.clip(self.integ + e * (DT / c.i_time_s), -imax, imax)
+ if c.i_antiwindup: # bleed off: 0 for a target at / beyond the range, else never past it
+ at = (t5 >= rhi - tol) | (t5 <= rlo + tol)
+ self.integ = np.where(at, 0.0, np.clip(self.integ, rlo - t5, rhi - t5))
+ u = u.copy()
+ u[:ARM] += self.integ
+ ur = self.jmap.sim_to_real(u)
+ ur, m1 = self.limits.clip(ur)
+ lo, hi = np.asarray(q_real) - self.max_rel, np.asarray(q_real) + self.max_rel
+ ur2 = np.minimum(np.maximum(ur, lo), hi)
+ ev["real_range"], ev["max_rel"] = bool(m1.any()), bool(np.any(np.abs(ur2 - ur) > 1e-9))
+ ur = ur2
+ u = self.jmap.real_to_sim(ur)
+ stop = []
+ if not np.all(np.isfinite(ur)):
+ stop.append("command: not finite")
+ low, ref = self.layer.floor_height(u)
+ low = float(low)
+ if low < ref + c.cmd_floor_m and low < float(self.layer.floor_height(q_sim)[0]) - 1e-4:
+ stop.append(f"command floor: lowest gripper point {low * 1e3:.1f} mm"
+ + (" above the table plane" if self.layer.plane is not None else "") + ", below the floor")
+ stop += ["command " + s for s in self._box(self.layer.tcp(u))]
+ self.prev = u.copy() # the step limit and the stall check: the command without the correction
+ self.prev[:ARM] -= self.integ
+ return u, ur, ev, stop
+
+ def stall(self, q_sim, cmd_prev_sim):
+ """Live only: the lead band keeps every arm command within LEAD of the measured q, so a blocked joint shows as a
+ command error that stays near its lead band. -> stop reason after stall_steps such steps in a row."""
+ if cmd_prev_sim is None or self.layer.lead is None:
+ return []
+ lead = self.layer.lead.numpy()
+ e = np.abs(np.asarray(q_sim)[:ARM] - np.asarray(cmd_prev_sim)[:ARM])
+ sat = e >= self.cfg.stall_frac * lead
+ self.err_run = self.err_run + 1 if sat.any() else 0
+ if self.err_run >= self.cfg.stall_steps:
+ j = int(np.argmax(e / lead))
+ return [f"stall: {JOINTS[j]} blocked, command error {e[j]:.3f} rad (lead band {lead[j]:.3f}) for {self.err_run} steps"]
+ return []
+
+
+# ---- joint-space moves (HOME, return) --------------------------------------------------------------------------
+def plan_joint_path(q_from, q_to, max_speed, dt=DT, min_time=1.0):
+ """Joint-space straight line q_from -> q_to (sim rad [6]) with a cosine time law whose peak joint speed stays
+ within max_speed (rad/s, scalar or [6]). -> waypoints [N, 6] (excludes q_from, ends at q_to), duration s."""
+ a, b = np.asarray(q_from, np.float64), np.asarray(q_to, np.float64)
+ v = np.broadcast_to(np.asarray(max_speed, np.float64), a.shape)
+ T = max(float(min_time), float(np.max(np.abs(b - a) / v)) * math.pi / 2)
+ n = max(1, int(math.ceil(T / dt)))
+ s = 0.5 - 0.5 * np.cos(math.pi * np.arange(1, n + 1) / n)
+ return a + s[:, None] * (b - a), n * dt
+
+
+def check_path(path, layer: ActionLayer, jmap: JointMap, limits: RealLimits, clearance=0.02, start=None,
+ goal_measured=False):
+ """Problems of a joint path (sim rad [N, 6]): a waypoint outside the collector's range or the LeRobot calibrated
+ range, or with its lowest gripper point below min(table_z + clearance, the lowest point of either end) - 1 mm, or
+ its grasp point outside the guard box (checked by the caller's Guard). A measured end pose (``start``; the last
+ waypoint if ``goal_measured``) may lie outside the collector's range (the real gripper closed: LeRobot gripper
+ < 2.9 = sim jaw < kin.TLO); a straight path stays between its ends, so waypoints between that end and the range
+ are accepted. -> list of strings (empty = ok)."""
+ p = np.asarray(path, np.float64)
+ ends = p[[0, -1]] if start is None else np.stack((np.asarray(start, np.float64), p[-1]))
+ bad = []
+ tlo, thi = layer.tlo.numpy(), layer.thi.numpy()
+ for m in ([] if start is None else [np.asarray(start, np.float64)]) + ([p[-1]] if goal_measured else []):
+ tlo, thi = np.minimum(tlo, m), np.maximum(thi, m)
+ if np.any(p < tlo - 1e-9) or np.any(p > thi + 1e-9):
+ bad.append("path leaves the sim joint range (kin.TLO .. THI)")
+ if limits.outside(jmap.sim_to_real(p)).any():
+ bad.append("path leaves the LeRobot calibrated range (minus margin)")
+ low, z0 = layer.floor_height(p) # (flat floor: lowest(p), table_z as before; plane: above it)
+ ref = min(z0 + clearance, float(layer.floor_height(ends)[0].min()))
+ if float(low.min()) < ref - 1e-3:
+ k = int(low.argmin())
+ bad.append(f"path waypoint {k} lowest gripper point {low[k] * 1e3:.1f} mm < {ref * 1e3:.1f} mm")
+ return bad
+
+
+# ---- the student ----------------------------------------------------------------------------------------------------
+def resolve_cam_map(student_cams, spec=None):
+ """{student camera: real camera}: ``spec`` "top=external,wrist=wrist" or a dict; default DEFAULT_CAM_MAP."""
+ m = dict(DEFAULT_CAM_MAP)
+ if isinstance(spec, str) and spec:
+ for kv in spec.split(","):
+ k, v = kv.split("=")
+ m[k.strip()] = v.strip()
+ elif isinstance(spec, dict):
+ m.update(spec)
+ out = {}
+ for c in student_cams:
+ if c not in m:
+ raise ValueError(f"student camera {c!r} has no real camera (use --cam-map {c}=external)")
+ if m[c] not in REAL_CAMERAS:
+ raise ValueError(f"real camera {m[c]!r} unknown (expected one of {REAL_CAMERAS})")
+ out[c] = m[c]
+ if len(set(out.values())) != len(out):
+ raise ValueError(f"two student cameras read the same real camera: {out}")
+ return out
+
+
+class StudentPolicy:
+ """The build9 camera student (``vision.viral.ViralNet``) as a real-robot policy: images of its cameras (the student's
+ RGB uint8 [res, res, 3], ``preprocess``), q and qdot (sim units) -> absolute chunk [K, 6] (sim rad), the executed
+ part [n_exec, 6] (jaw ``jaw_lead`` steps ahead, as ``viral.Actor``), the auxiliary predictions (block = plate
+ x, y, yaw mod 90 deg; cube x, y, z). Same normalisation and bf16 autocast as ``viral.Actor``.
+
+ Input options (as ``viral.OnlineDAgger`` / ``viral.Actor``; ``reset`` at every episode start; independent of each
+ other; robot vector order [q, qd, history, cmd, last command]):
+ - ``cfg.hist``: [q, qd] of the previous ``hist`` queries, newest first (the current values repeated at the first
+ query).
+ - ``cfg.cmd_in``: the previous decision's 5 executed targets - q now, raw rad [5, 6] flattened after the history
+ (the net divides by ``cmd_scale``); 0 at the first query. ``query(..., u_prev=)`` = ``Guard.u_layer`` of the 5
+ loop steps since the last query (``Controller`` passes them); a missing ``u_prev`` after the first query is
+ refused.
+ - ``cfg.lastcmd`` (``lastcmd``): ``query(..., last_cmd=(u_last, u_prev))`` = the commands sent in the last two
+ 20 ms steps before the query (sim rad [6]; ``Guard.prev``: without the integral correction), None at an episode
+ start (input 0; ``start=True``, else refused) -> ``viral.lastcmd_raw``, as the sim's ``u_exe[:, -1]`` /
+ ``[:, -2]``; 12 values after the cmd input.
+ - ``cfg.img_hist``: the previous query's image features (cached, no second encoder pass; the current ones at the
+ first query) appended to the head input.
+ A student whose head input is not exactly [features, robot vector above without the last command, (previous
+ features)] (an input option this class does not know) is refused. ``query`` returns the robot vector it fed
+ (``robot``)."""
+
+ def __init__(self, ckpt, device="cuda", cam_map=None, jaw_lead=None, amp=None):
+ import torch
+
+ from nedm.so101_policy.vision import viral as VI
+ self.torch, self.VI = torch, VI
+ self.dev = torch.device(device)
+ self.st, ck = VI.load_student(ckpt, device)
+ self.ckpt = str(Path(ckpt).expanduser())
+ self.meta = {k: v for k, v in ck.items() if k not in ("state_dict", "stats")}
+ self.cfg = self.st.cfg
+ self.cams = tuple(self.cfg.cameras)
+ self.cam_map = resolve_cam_map(self.cams, cam_map)
+ self.res = int(self.cfg.res)
+ self.n_exec, self.chunk = int(self.cfg.n_exec), int(self.cfg.chunk)
+ self.jaw_lead = int(self.cfg.jaw_lead if jaw_lead is None else jaw_lead)
+ self.amp = bool(self.cfg.amp if amp is None else amp) and self.dev.type == "cuda"
+ self.H = int(self.cfg.hist)
+ self.cmd_in = bool(getattr(self.cfg, "cmd_in", False))
+ self.img_hist = bool(getattr(self.cfg, "img_hist", False))
+ fd = int(self.st.fd)
+ want = fd + 12 * (1 + self.H) + (6 * self.n_exec if self.cmd_in else 0) + (fd if self.img_hist else 0)
+ got = int(self.st.head[0].in_features)
+ if got != want:
+ raise ValueError(f"student {self.ckpt}: head input {got} != {want} = features {fd} + [q, qd] x (1 + hist "
+ f"{self.H}) + cmd_in {self.cmd_in} + img_hist {self.img_hist}: an input option that the "
+ f"robot code does not implement")
+ self.rhist = None
+ self.lastcmd = bool(getattr(self.cfg, "lastcmd", False)) # own input layer: not in the head input
+ self.prev_feat = None # img_hist: the previous query's image features
+ self.n_query = 0 # queries since ``reset``
+
+ def reset(self):
+ self.rhist = None
+ self.prev_feat = None
+ self.n_query = 0
+
+ def warmup(self, n=3):
+ """``n`` (>= 2) queries on black images (the history / image-history / cmd / last-command paths included), then
+ ``reset``."""
+ z = {self.cam_map[c]: np.zeros((self.res, self.res, 3), np.uint8) for c in self.cams}
+ for i in range(max(2, int(n))):
+ self.query(z, np.zeros(6), np.zeros(6), u_prev=np.zeros((self.n_exec, 6)) if i else None,
+ last_cmd=(np.zeros(6), np.zeros(6)) if i else None, start=i == 0)
+ self.reset()
+
+ def query(self, images, q_sim, qd_sim, u_prev=None, last_cmd=None, start=False):
+ """``u_prev`` (``cmd_in`` students; others ignore it): the previous decision's executed targets [n_exec, 6]
+ (sim rad, ``Guard.u_layer`` of the loop steps since the last query); ignored at the first query (input 0).
+ ``last_cmd`` / ``start`` (``lastcmd`` students; others ignore them): class docstring."""
+ torch, VI = self.torch, self.VI
+ t0 = time.perf_counter()
+ with torch.no_grad():
+ rgb = np.stack([images[self.cam_map[c]] for c in self.cams])[None] # [1, C, H, W, 3]
+ if rgb.shape[2:4] != (self.res, self.res):
+ raise ValueError(f"student images must be {self.res} px, got {rgb.shape[2:4]}")
+ img = VI.to_input(torch.from_numpy(rgb).to(self.dev))
+ q = torch.as_tensor(np.asarray(q_sim, np.float32), device=self.dev)[None]
+ qd = torch.as_tensor(np.nan_to_num(np.asarray(qd_sim, np.float32)), device=self.dev)[None]
+ robot = torch.cat((q, qd), -1)
+ if self.H:
+ if self.rhist is None:
+ self.rhist = robot[:, None, :].expand(-1, self.H, -1).clone()
+ now = robot
+ robot = torch.cat((now, self.rhist.reshape(1, -1)), -1)
+ self.rhist = torch.cat((now[:, None, :], self.rhist[:, :-1]), 1)
+ if self.cmd_in: # the previous decision's executed targets - q now (0 at the first query)
+ if self.n_query == 0:
+ cmd = torch.zeros(1, 6 * self.n_exec, device=self.dev)
+ else:
+ if u_prev is None:
+ raise ValueError("cmd_in student: pass u_prev (Guard.u_layer of the loop steps since the last "
+ "query) after the first query of an episode")
+ up = np.asarray(u_prev, np.float32)
+ if up.shape != (self.n_exec, 6):
+ raise ValueError(f"u_prev shape {up.shape}, expected ({self.n_exec}, 6)")
+ cmd = (torch.as_tensor(up, device=self.dev) - q[:, None, :]).nan_to_num().reshape(1, -1)
+ robot = torch.cat((robot, cmd), -1)
+ lc = None
+ if self.lastcmd: # the last commands sent (None: the episode start, input 0)
+ if last_cmd is None:
+ if not start: # a caller that does not know the option would feed 0 at every query
+ raise ValueError("lastcmd student: pass last_cmd=(u_last, u_prev), or start=True at the "
+ "episode start")
+ lc = VI.lastcmd_zeros(1, self.dev)
+ else:
+ f64 = dict(dtype=torch.float64, device=self.dev)
+ lc = VI.lastcmd_raw(torch.as_tensor(np.asarray(last_cmd[0], np.float64), **f64)[None],
+ torch.as_tensor(np.asarray(last_cmd[1], np.float64), **f64)[None],
+ torch.as_tensor(np.asarray(q_sim, np.float64), **f64)[None])
+ robot = torch.cat((robot, lc.to(robot)), -1)
+ with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=self.amp):
+ if self.img_hist: # the previous query's features (the first query: the current ones)
+ f = self.st.features(img)
+ p = self.st.head_from_features(f, robot, self.prev_feat)
+ self.prev_feat = f
+ else:
+ p, f = self.st(img, robot)
+ aux = self.st.aux(f)
+ delta = VI.denormalise(self.st, p.float())
+ aux = aux.float() * self.st.aux_std + self.st.aux_mean
+ u = (q[:, None, :] + delta)[0] # [K, 6]
+ jj = torch.arange(self.n_exec, device=self.dev)
+ kk = (jj + self.jaw_lead).clamp_max(u.shape[0] - 1)
+ ex = torch.cat((u[jj, :ARM], u[kk, ARM:]), -1)
+ out = dict(chunk=u.double().cpu().numpy(), exec=ex.double().cpu().numpy(),
+ aux=aux[0].double().cpu().numpy(), robot=robot[0].double().cpu().numpy())
+ if lc is not None:
+ out["lastcmd"] = lc[0].cpu().numpy()
+ self.n_query += 1
+ a = out["aux"]
+ out["plate_xy"] = a[:2]
+ out["plate_yaw4_deg"] = math.degrees(math.atan2(a[2], a[3]) / 4)
+ out["cube_xyz"] = a[4:7]
+ out["t_model_ms"] = (time.perf_counter() - t0) * 1e3
+ return out
+
+
+# ---- one control step (replay, dry, live) ---------------------------------------------------------------------------
+@dataclass
+class StepOut:
+ u_sim: np.ndarray | None
+ u_real: np.ndarray | None
+ query: bool
+ stop: list = field(default_factory=list) # stop reasons (enforced in live)
+ events: dict = field(default_factory=dict)
+ timing: dict = field(default_factory=dict)
+
+
+class Controller:
+ """The student's control step, identical for a replayed recording and the robot: measured q (real units) at time
+ t -> qdot estimate, every n_exec steps a query (``get_frames()`` -> {real camera: (image uint8 [480, 640, 3],
+ age ms)}; ``bgr``: images are BGR), the executed target of this step through ``Guard.apply`` (step limit, action
+ layer, LeRobot-unit limits). Keeps a per-step and per-query log (``arrays``: per-query keys start with "qry_").
+ Per step ``u_layer`` (``Guard.u_layer``: the action-layer target, before the integral correction and the LeRobot
+ clamps); a ``cmd_in`` student gets the ``u_layer`` of the 5 loop steps since the last query (by loop step: a query
+ every ``n_exec`` steps); a student with history / new inputs logs the robot vector it was fed (``qry_robot``).
+ A student with the last-command input (``StudentPolicy.lastcmd``) gets ``Guard.prev`` after the last two steps
+ (``cmd``; none since ``reset``: 0), logged as ``qry_lastcmd`` (raw, ``viral.lastcmd_raw``). Offline from a log:
+ 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],
+ prev[k - 2]) (k - 2 < 0: prev[k - 1] twice)."""
+
+ def __init__(self, policy: StudentPolicy, jmap: JointMap, guard: Guard, views: dict, qdot: QdotEstimator,
+ bgr: bool, max_frame_age_ms=150.0, thumb_res=112, qd_gain=1.0):
+ self.p, self.jm, self.g, self.views, self.qdot = policy, jmap, guard, views, qdot
+ # real2sim (2026-10-22): the student's qdot INPUT x qd_gain (1 = off). The student's step size follows the
+ # measured speed; the real arm is ~5x slower than the sim arm, so its steps shrink until the arm holds still
+ # above the plate (robot-like sim, today's student: 50 % at gain 1, 88 % at 2, 94 % at 3; nominal sim 98 / 90 /
+ # 75 %). The guard and the log keep the measured qdot.
+ self.qd_gain = float(qd_gain)
+ self.bgr, self.max_age, self.thumb_res = bool(bgr), float(max_frame_age_ms), int(thumb_res)
+ self.k = 0
+ self.ex = None
+ self.cmd = [] # Guard.prev after the last two steps (oldest first): the last-command input
+ self.u_layer = [] # Guard.u_layer of the last n_exec loop steps (NaN: no command that step)
+ self.S = {k: [] for k in ("t", "q_real", "q_sim", "qd_sim", "u_target", "u_layer", "u_sim", "u_real", "i_corr",
+ "i_aw", "query", "ev_step", "ev_lead", "ev_range", "ev_floor", "ev_real_range",
+ "ev_max_rel", "n_stop", "ms_qdot", "ms_frames", "ms_pre", "ms_model", "ms_guard",
+ "ms_ctrl")}
+ self.Q = {k: [] for k in ("t", "step", "chunk", "exec", "aux", "plate_xy", "plate_yaw4_deg", "cube_xyz",
+ "frame_age_ms", "thumbs", "robot", "lastcmd")} # robot / lastcmd: empty (no
+ # key) when not used
+ self.events = {}
+
+ def reset(self, q_real=None):
+ self.k = 0
+ self.ex = None
+ self.cmd = []
+ self.u_layer = []
+ self.qdot.reset()
+ self.p.reset()
+ if q_real is not None:
+ self.g.reset(self.jm.real_to_sim(q_real))
+
+ def step(self, t, q_real, get_frames):
+ T = {}
+ t0 = time.perf_counter()
+ q_real = np.asarray(q_real, np.float64)
+ q_sim = self.jm.real_to_sim(q_real)
+ qd = self.qdot.update(t, q_sim)
+ T["ms_qdot"] = (time.perf_counter() - t0) * 1e3
+ stop = self.g.check_measured(q_sim, q_real)
+ query = self.k % self.p.n_exec == 0
+ T["ms_frames"] = T["ms_pre"] = T["ms_model"] = float("nan") # query steps only
+ if query:
+ t1 = time.perf_counter()
+ fr = get_frames()
+ T["ms_frames"] = (time.perf_counter() - t1) * 1e3
+ t2 = time.perf_counter()
+ imgs, ages = {}, []
+ for c in self.p.cams:
+ rc = self.p.cam_map[c]
+ im, age = fr[rc]
+ ages.append(float(age))
+ if np.isfinite(age) and age > self.max_age:
+ stop.append(f"camera age: {rc} frame {age:.0f} ms old")
+ imgs[rc] = preprocess(im, self.views[rc], self.bgr)
+ T["ms_pre"] = (time.perf_counter() - t2) * 1e3
+ qd_in = qd if self.qd_gain == 1.0 else qd * self.qd_gain
+ kw = {} # input options (a plain student: the old 3-argument call)
+ if getattr(self.p, "cmd_in", False): # the action-layer targets of the last n_exec loop steps
+ n = self.p.n_exec
+ kw["u_prev"] = np.stack(self.u_layer[-n:]) if len(self.u_layer) >= n else None
+ lc_on = bool(getattr(self.p, "lastcmd", False))
+ if lc_on: # the commands of the last two steps (none yet: 0)
+ lc = (self.cmd[-1], self.cmd[-2] if len(self.cmd) > 1 else self.cmd[-1]) if self.cmd else None
+ kw.update(last_cmd=lc, start=lc is None)
+ r = self.p.query(imgs, q_sim, qd_in, **kw)
+ if lc_on:
+ self.Q["lastcmd"].append(np.asarray(r["lastcmd"]))
+ T["ms_model"] = r["t_model_ms"]
+ self.ex = r["exec"]
+ Q = self.Q
+ if "robot" in r and (getattr(self.p, "H", 0) or getattr(self.p, "cmd_in", False)
+ or getattr(self.p, "img_hist", False)):
+ Q["robot"].append(np.asarray(r["robot"]))
+ Q["t"].append(t)
+ Q["step"].append(self.k)
+ for kk in ("chunk", "exec", "aux", "plate_xy", "plate_yaw4_deg", "cube_xyz"):
+ Q[kk].append(np.asarray(r[kk]))
+ Q["frame_age_ms"].append(np.asarray(ages))
+ Q["thumbs"].append(np.stack([thumb(imgs[self.p.cam_map[c]], self.thumb_res) for c in self.p.cams]))
+ t3 = time.perf_counter()
+ target = self.ex[self.k % self.p.n_exec]
+ u_sim, u_real, ev, stop2 = self.g.apply(target, q_sim, q_real, qd)
+ if u_sim is not None: # the command without the integral correction (the last-command input)
+ self.cmd = (self.cmd + [self.g.prev.copy()])[-2:]
+ nan6 = np.full(6, np.nan)
+ ul = nan6 if self.g.u_layer is None else self.g.u_layer.copy()
+ self.u_layer = (self.u_layer + [ul])[-self.p.n_exec:]
+ stop += stop2
+ T["ms_guard"] = (time.perf_counter() - t3) * 1e3
+ T["ms_ctrl"] = (time.perf_counter() - t0) * 1e3
+ S = self.S
+ for kk, v in (("t", t), ("q_real", q_real), ("q_sim", q_sim), ("qd_sim", qd), ("u_target", target),
+ ("u_layer", ul), ("u_sim", nan6 if u_sim is None else u_sim),
+ ("u_real", nan6 if u_real is None else u_real),
+ ("i_corr", self.g.integ.copy()), ("i_aw", self.g.i_aw.copy()), ("query", query),
+ ("n_stop", len(stop))):
+ S[kk].append(v)
+ for kk in ("step", "lead", "range", "floor", "real_range", "max_rel"):
+ S["ev_" + kk].append(bool(ev.get(kk, False)))
+ for kk, v in T.items():
+ S[kk].append(v)
+ for s in stop:
+ key = s.split(":")[0] # one entry per kind of reason: first time, count
+ e = self.events.setdefault(key, dict(first_t=float(t), first=s, count=0))
+ e["count"] += 1
+ self.k += 1
+ return StepOut(u_sim, u_real, query, stop, ev, T)
+
+ def arrays(self):
+ out = {}
+ for pre, D in (("", self.S), ("qry_", self.Q)):
+ for k, v in D.items():
+ if len(v):
+ out[pre + k] = np.asarray(np.stack(v) if isinstance(v[0], np.ndarray) else v)
+ return out
+
+
+# ---- logs and latency ----------------------------------------------------------------------------------------------
+def latency_summary(cols):
+ """{name: list of ms} -> {name: {n, p50, p95, p99, max}}."""
+ out = {}
+ for k, v in cols.items():
+ a = np.asarray([x for x in v if x is not None and np.isfinite(x)], np.float64)
+ if len(a):
+ out[k] = dict(n=int(len(a)), p50=float(np.percentile(a, 50)), p95=float(np.percentile(a, 95)),
+ p99=float(np.percentile(a, 99)), max=float(a.max()))
+ return out
+
+
+def save_log(path, arrays, meta):
+ p = Path(path)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ np.savez_compressed(p, **arrays, meta=np.asarray(json.dumps(meta, default=str)))
+ p.with_suffix(".json").write_text(json.dumps(meta, indent=1, default=str))
+
+
+def precise_wait(deadline):
+ """Sleep until time.perf_counter() >= deadline (sleep, then spin the last 2 ms)."""
+ while True:
+ r = deadline - time.perf_counter()
+ if r <= 0:
+ return
+ if r > 0.003:
+ time.sleep(r - 0.002)
+
+
+# ---- a fake robot (tests of the dry / live loop without hardware) -------------------------------------------------
+class FakeRobotIO:
+ """Stand-in for the LeRobot robot in tests: 6 servos that move toward the goal with a first-order lag (``tau`` s)
+ and a speed limit (deg/s), torque flag, a write counter, constant camera images. Same methods as
+ ``run_student_real.LeRobotIO``."""
+
+ def __init__(self, q0_real, writes=True, tau=0.04, vmax=200.0, image=None):
+ self.q = np.asarray(q0_real, np.float64).copy()
+ self.goal = self.q.copy()
+ self.writes, self.tau, self.vmax = bool(writes), float(tau), float(vmax)
+ self.torque = False
+ self.n_writes = 0
+ self.t_last = None
+ self.img = np.full((480, 640, 3), 90, np.uint8) if image is None else image
+ self.bgr = False
+ self.connected = False
+
+ def connect(self):
+ self.connected = True
+
+ def _advance(self):
+ now = time.perf_counter()
+ if self.t_last is not None and self.torque:
+ dt = now - self.t_last
+ d = (self.goal - self.q) * (1 - math.exp(-dt / self.tau))
+ self.q += np.clip(d, -self.vmax * dt, self.vmax * dt)
+ self.t_last = now
+
+ def read_q(self):
+ self._advance()
+ return self.q.copy()
+
+ def frames(self, max_age_ms=500):
+ return {c: (self.img, 5.0) for c in REAL_CAMERAS}
+
+ def write_goal(self, q_real):
+ if not self.writes:
+ raise RuntimeError("fake robot: writes are blocked (dry mode)")
+ self._advance()
+ self.goal = np.asarray(q_real, np.float64).copy()
+ self.n_writes += 1
+
+ def torque_on_at_present(self):
+ if not self.writes:
+ raise RuntimeError("fake robot: writes are blocked (dry mode)")
+ self.goal = self.q.copy()
+ self.torque = True
+
+ def disable_torque(self):
+ if not self.writes:
+ raise RuntimeError("fake robot: writes are blocked (dry mode)")
+ self.torque = False
+
+ def configure(self, mode):
+ return "fake: nothing to configure"
+
+ def close(self, disable_torque=False):
+ if disable_torque:
+ self.disable_torque()
+ self.connected = False
diff --git a/so101_pick_place/code/scripts/so101_policy/real2sim/hw/make_orin_bundle.sh b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/make_orin_bundle.sh
new file mode 100644
index 0000000000000000000000000000000000000000..284bf5278b654bc677c504d07217583ecec4188c
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/make_orin_bundle.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# Build the folder (and .tar.gz) that run_student_real.py needs on the robot's Jetson AGX Orin: the nedm.so101_policy
+# Python sources, this folder's scripts, the SO101 collision points (table floor without mujoco), the student
+# checkpoint, calib_v1.json and assets/deploy.json (the floor mode of the student, read from its checkpoint, the table
+# plane source, HOME and the eval guard: robot_test.sh passes them to every run). It writes locally only; copying it to
+# the Orin is the user's step (README.md).
+#
+# scripts/so101_policy/real2sim/hw/make_orin_bundle.sh [out_dir] [calib_v1.json]
+# HOME_SIM_DEG=a,b,c,d,e,f ... another HOME (sim deg; default hw_lib.ROBOT_HOME_SIM_DEG = 0,-5,-15,92,0,30)
+# PYTHON= ... the Python that reads the checkpoint (default python3)
+set -euo pipefail
+HW="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$HW/../../../.." && pwd)"
+CKPT="${1:?usage: make_orin_bundle.sh [out_dir] [calib_v1.json]}"
+OUT="${2:-$ROOT/artifacts/so101_pick_place_repro/bundle/so101_hw}"
+CALIB="${3:-$ROOT/configs/so101_pick_place/calib_v1.json}"
+POINTS="${SO101_KIN_POINTS:-$ROOT/artifacts/so101_pick_place/rl_inputs/geometry/kin_points_v1.npz}"
+PY="${PYTHON:-python3}"
+
+[ -f "$CKPT" ] || { echo "student checkpoint $CKPT missing"; exit 1; }
+[ -f "$POINTS" ] || { echo "kin points $POINTS missing"; exit 1; }
+rm -rf "$OUT"
+mkdir -p "$OUT/src/nedm/so101_policy/vision" "$OUT/src/nedm/render" "$OUT/scripts/so101_policy/real2sim/hw" "$OUT/assets"
+cp "$ROOT/src/nedm/__init__.py" "$OUT/src/nedm/"
+cp "$ROOT/src/nedm/render/student_view.py" "$OUT/src/nedm/render/" # the crop code shared with the renderer
+cp "$ROOT"/src/nedm/so101_policy/*.py "$OUT/src/nedm/so101_policy/"
+cp "$ROOT"/src/nedm/so101_policy/vision/*.py "$OUT/src/nedm/so101_policy/vision/"
+cp "$HW/hw_lib.py" "$HW/run_student_real.py" "$HW/README.md" "$OUT/scripts/so101_policy/real2sim/hw/"
+cp "$HW/robot_test.sh" "$HW/QDGAIN_TEST.md" "$OUT/" # the launcher + the qd-gain test plan (bundle root)
+cp "$POINTS" "$OUT/assets/kin_points_v1.npz"
+cp "$CKPT" "$OUT/assets/student.pt"
+if [ -f "$CALIB" ]; then cp "$CALIB" "$OUT/assets/calib_v1.json"; else echo "NOTE: no $CALIB (live mode will refuse)"; fi
+# the deploy settings, from the bundle's own copies (the bundle's sources: the same rules as on the robot)
+HOME_ARG=(); [ -n "${HOME_SIM_DEG:-}" ] && HOME_ARG=(--home "$HOME_SIM_DEG")
+NEDM_SRC="$OUT/src" PYTHONDONTWRITEBYTECODE=1 CUDA_VISIBLE_DEVICES="" "$PY" \
+ "$OUT/scripts/so101_policy/real2sim/hw/run_student_real.py" deploy-json --student "$OUT/assets/student.pt" \
+ --calib "$OUT/assets/calib_v1.json" --out "$OUT/assets/deploy.json" "${HOME_ARG[@]}"
+find "$OUT" -name __pycache__ -prune -exec rm -rf {} + # only the built files in the manifest
+FLOOR_MODE="$("$PY" -c 'import json, sys; print(json.load(open(sys.argv[1]))["floor_mode"])' "$OUT/assets/deploy.json")"
+{
+ echo "built $(date -Iseconds) from $ROOT (git $(git -C "$ROOT" rev-parse --short HEAD 2>/dev/null || echo ?)"\
+ "$(git -C "$ROOT" status --porcelain -- src/nedm/so101_policy scripts/so101_policy/real2sim/hw 2>/dev/null | wc -l)"\
+ "changed files under the copied paths)"
+ echo "student $CKPT (floor mode $FLOOR_MODE, assets/deploy.json)" # header: 3 lines (robot_test.sh: lines 4-)
+ echo "calib $CALIB"
+ (cd "$OUT" && find . -type f ! -name MANIFEST.txt -print0 | sort -z | xargs -0 sha256sum)
+} > "$OUT/MANIFEST.txt"
+tar -C "$(dirname "$OUT")" -czf "$OUT.tar.gz" "$(basename "$OUT")"
+du -sh "$OUT" "$OUT.tar.gz"
+echo "bundle: $OUT.tar.gz floor mode $FLOOR_MODE (copy it to the Orin yourself, e.g. scp $OUT.tar.gz sbel@proxy:~/ ;"\
+ "README.md)"
diff --git a/so101_pick_place/code/scripts/so101_policy/real2sim/hw/robot_test.sh b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/robot_test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a6743b71621dc7387ed981186a9ab719aee0752a
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_policy/real2sim/hw/robot_test.sh
@@ -0,0 +1,217 @@
+#!/usr/bin/env bash
+# One command for each robot test on the Orin (make_orin_bundle.sh copies it to the bundle root; README.md).
+#
+# ./robot_test.sh check files, Python env, robot port, cameras, calibration (opens no device)
+# ./robot_test.sh replay 3 recordings, no robot (model time on this computer)
+# ./robot_test.sh dry [s] [args] robot + cameras, reads only, no motor writes (default 30 s)
+# ./robot_test.sh live [s] [args] MOVES THE ROBOT (default 15 s)
+# ./robot_test.sh live-tilt [s] [args] live + the table-tilt correction --q-offset-deg 0,-2.086,0,0,0 (README;
+# flat students only: refused for a floor mode plane bundle)
+# ./robot_test.sh eval [n] [s] [args] MOVES THE ROBOT: n episodes in a row (default 10 x 40 s), servo correction
+#
+# [args] go to run_student_real.py as they are. Outputs: ~/so101_hw_runs/_/ (RUNS overrides).
+# Every mode takes the floor mode, the table plane source and HOME from assets/deploy.json (make_orin_bundle.sh).
+set -eo pipefail
+SELF="$(readlink -f "${BASH_SOURCE[0]}")"
+cd "$(dirname "$SELF")"
+MODE="${1:-}"
+[ $# -gt 0 ] && shift
+RUN=scripts/so101_policy/real2sim/hw/run_student_real.py
+S=(--student assets/student.pt --calib assets/calib_v1.json)
+DEPLOY=assets/deploy.json
+RUNS="${RUNS:-$HOME/so101_hw_runs}"
+DATA_ROOT="${DATA_ROOT:-$HOME/lerobot/data}"
+TILT=(--q-offset-deg 0,-2.086,0,0,0)
+export HF_HUB_OFFLINE=1
+
+usage() { sed -n '2,13p' "$SELF" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }
+
+# assets/deploy.json (run_student_real.py deploy-json, written by make_orin_bundle.sh from the student checkpoint):
+# floor_mode flat = students trained on the sim table (C1, s28, roll-cap students): floor 1.5 mm above sim z 0,
+# eval floor stops -15 / -20 mm (the real mat is 8-18 mm below the sim table)
+# plane = students trained with the v8 table randomisation: floor 1.5 mm above the calibrated mat plane
+# (--table-plane calib), eval floor stops 2 / 5 mm below that plane (no double lowering)
+# home_sim_deg HOME (sim deg; wrist roll 0), eval_guard = eval's --guard (+ --amp 0)
+deploy_get() {
+ python -c 'import json, sys
+v = json.load(open(sys.argv[1]))[sys.argv[2]]
+print(v if isinstance(v, str) else json.dumps(v, separators=(",", ":")))' "$DEPLOY" "$1"
+}
+load_deploy() {
+ [ -f "$DEPLOY" ] || { echo "no $DEPLOY in this bundle: rebuild it with make_orin_bundle.sh (2026-10-24 or later)"; exit 1; }
+ FLOOR_MODE="$(deploy_get floor_mode)" && HOME_DEG="$(deploy_get home_sim_deg)" && EVAL_GUARD="$(deploy_get eval_guard)" \
+ || { echo "cannot read $DEPLOY"; exit 1; }
+ case "$FLOOR_MODE" in
+ flat) FLOOR=(--floor-mode flat --table-z 0) ;;
+ plane) FLOOR=(--floor-mode plane --table-plane "$(deploy_get table_plane)") ;;
+ *) echo "$DEPLOY: unknown floor_mode $FLOOR_MODE"; exit 1 ;;
+ esac
+ FLOOR+=(--home "$HOME_DEG")
+ EVAL=(--amp 0 --guard "$EVAL_GUARD")
+}
+
+activate() {
+ if [ "${CONDA_DEFAULT_ENV:-}" != lerobot ]; then
+ # shellcheck disable=SC1091
+ source "${CONDA_SH:-$HOME/miniforge3/etc/profile.d/conda.sh}" && conda activate lerobot \
+ || { echo "cannot activate the conda env lerobot"; exit 1; }
+ fi
+}
+
+# the bundle files are the ones that were built (MANIFEST.txt lines 4-)
+files_ok() { sed -n '4,$p' MANIFEST.txt | sha256sum -c --quiet; }
+
+need_tty() {
+ [ -t 0 ] && [ -t 1 ] || { echo "run this in an interactive terminal (desktop or ssh -t): the stop keys need a TTY"; exit 1; }
+}
+
+# the launcher sets these itself (the banner must tell what the run does): refuse them in [args]
+no_floor_overrides() {
+ local a
+ for a in "$@"; do
+ case "$a" in
+ --floor-mode|--floor-mode=*|--table-z|--table-z=*|--table-plane|--table-plane=*|--home|--home=*|\
+ --allow-floor-mismatch)
+ echo "do not give $a here: the floor and HOME come from $DEPLOY (the banner shows them); use" \
+ "run_student_real.py directly for other values"
+ exit 1 ;;
+ esac
+ done
+}
+no_overrides() {
+ local a
+ no_floor_overrides "$@"
+ for a in "$@"; do
+ case "$a" in
+ --time-limit|--time-limit=*|--q-offset-deg|--q-offset-deg=*|--out|--out=*|--backend|--backend=*|--auto-confirm|\
+ --episodes-n|--episodes-n=*)
+ echo "do not give $a here: use [n] [s] for the episodes and the time, the mode live-tilt for the correction"
+ exit 1 ;;
+ esac
+ done
+}
+
+secs() { [[ "${1:-}" =~ ^[0-9]+([.][0-9]+)?$ ]]; }
+
+out_dir() { echo "$RUNS/${1}_$(date +%Y%m%d_%H%M%S)"; }
+
+case "$MODE" in
+ check)
+ activate
+ st=0
+ echo "== bundle files"
+ if files_ok; then echo "ok ($(head -1 MANIFEST.txt))"; else echo "CHANGED OR MISSING (above)"; st=1; fi
+ echo "== deploy settings ($DEPLOY)"
+ if [ -f "$DEPLOY" ]; then
+ echo "floor mode $(deploy_get floor_mode): $(deploy_get floor_why)"
+ echo "HOME sim deg $(deploy_get home_sim_deg); eval guard $(deploy_get eval_guard)"
+ else echo "MISSING $DEPLOY (rebuild the bundle)"; st=1; fi
+ echo "== Python env ($CONDA_DEFAULT_ENV)"
+ python - <<'EOF' || st=1
+import importlib.metadata as m
+import cv2, numpy, pyarrow, torch
+import lerobot.robots.so_follower, lerobot.cameras.opencv # import only, opens nothing
+print(f"lerobot {m.version('lerobot')}, torch {torch.__version__}, cuda {torch.cuda.is_available()}, "
+ f"cv2 {cv2.__version__}, numpy {numpy.__version__}, pyarrow {pyarrow.__version__}")
+assert torch.cuda.is_available(), "no CUDA: the student would run on the CPU"
+EOF
+ echo "== robot port, external camera, wrist camera (the defaults of run_student_real.py)"
+ python - <<'EOF' || st=1
+import os, sys
+sys.path.insert(0, "scripts/so101_policy/real2sim/hw")
+import run_student_real as R # opens no device
+paths = [R.FOLLOWER_PORT, R.CAM_PATHS["external"], R.CAM_PATHS["wrist"]]
+bad = 0
+for p in paths:
+ if os.path.exists(p):
+ print(f"ok {p} -> {os.path.realpath(p)}")
+ else:
+ print(f"MISSING {p} (unplugged? another USB port? README)"); bad = 1
+for b in R.device_users(paths):
+ print("IN USE (dry / live will refuse):", b); bad = 1
+sys.exit(bad)
+EOF
+ echo "== LeRobot calibration of the follower"
+ c="$HOME/.cache/huggingface/lerobot/calibration/robots/so_follower/so101_follower.json"
+ if [ -f "$c" ]; then echo "ok $c"; else echo "MISSING $c"; st=1; fi
+ echo "== power mode"
+ nvpmodel -q 2>/dev/null | head -1 || true
+ [ $st -eq 0 ] && echo "CHECK OK" || echo "CHECK FOUND PROBLEMS (above)"
+ exit $st
+ ;;
+ replay)
+ activate
+ load_deploy
+ no_floor_overrides "$@"
+ O="$(out_dir replay)"
+ echo "replay (no robot) -> $O; floor mode $FLOOR_MODE"
+ exec python "$RUN" replay "${S[@]}" "${FLOOR[@]}" --data-root "$DATA_ROOT" \
+ --episodes green_cube_red_plate:0,green_cube_red_plate:2,green_cube_red_plate_1:5 --out "$O" "$@"
+ ;;
+ dry|live|live-tilt|eval)
+ need_tty
+ activate
+ files_ok || { echo "bundle files changed or missing (MANIFEST.txt): refusing"; exit 1; }
+ load_deploy
+ if [ "$MODE" = live-tilt ] && [ "$FLOOR_MODE" = plane ]; then # (run_student_real.py refuses it as well)
+ echo "live-tilt is for flat students only: this bundle's floor mode is plane, the floor already follows the" \
+ "calibrated table (the tilt correction would lower it again, into the mat). Use live."
+ exit 1
+ fi
+ if [ "$MODE" = live-tilt ] && [ "$(deploy_get table_frame 2>/dev/null)" = true ]; then # (v12; the runner too)
+ echo "live-tilt is for students trained on the sim table only: this bundle's student was trained in the table" \
+ "frame (it corrects for the real table itself; the tilt correction would correct twice). Use live."
+ exit 1
+ fi
+ T=30; [ "$MODE" != dry ] && T=15
+ N=1
+ if [ "$MODE" = eval ]; then
+ N=10; T=40
+ if [[ "${1:-}" =~ ^[0-9]+$ ]]; then N="$1"; shift; fi
+ [ "$N" -ge 1 ] || { echo "eval needs 1 or more episodes"; exit 1; }
+ fi
+ if secs "${1:-}"; then T="$1"; shift; fi
+ no_overrides "$@"
+ if [ "$MODE" = eval ]; then # the banner shows the eval settings: they must be the ones used
+ for a in "$@"; do
+ case "$a" in --guard|--guard=*|--amp|--amp=*) echo "do not give $a with eval (it sets ${EVAL[*]}); use live"
+ exit 1 ;; esac
+ done
+ fi
+ EXTRA=(); [ "$MODE" = live-tilt ] && EXTRA=("${TILT[@]}")
+ [ "$MODE" = eval ] && EXTRA=("${EVAL[@]}" --episodes-n "$N")
+ O="$(out_dir "$MODE")"
+ # run_student_real.py refuses dry / live while another program can use the port or a camera (device_users)
+ if [ "$MODE" = dry ]; then
+ echo "DRY run, $T s: the robot and the cameras are read only; no motor writes. -> $O"
+ echo "Floor mode: $FLOOR_MODE ($DEPLOY)"
+ exec python "$RUN" dry "${S[@]}" "${FLOOR[@]}" --out "$O" --time-limit "$T" "$@"
+ fi
+ echo "Floor mode: $FLOOR_MODE HOME sim deg: $HOME_DEG ($DEPLOY: $(deploy_get floor_why))"
+ if [ "$MODE" = eval ]; then
+ echo "EVAL session, $N episodes of up to $T s: THIS MOVES THE ROBOT. -> $O"
+ echo "Settings: ${FLOOR[*]} ${EVAL[*]}"
+ cat < $O"
+ echo "Settings: ${FLOOR[*]}"
+ if [ "$MODE" = live-tilt ]; then echo "Table-tilt correction ON: ${TILT[*]}"; fi
+ cat < names blocked."""
+ def blocked(name):
+ def f(*a, **k):
+ raise RuntimeError(f"dry mode: {name} is blocked (no motor writes)")
+ return f
+ done = []
+ for obj, names, tag in ((bus, BUS_WRITERS, "bus"), (robot, ROBOT_WRITERS, "robot")):
+ if obj is None:
+ continue
+ for n in names:
+ if hasattr(obj, n):
+ setattr(obj, n, blocked(f"{tag}.{n}"))
+ done.append(f"{tag}.{n}")
+ return done
+
+
+# LeRobot 0.6.2 tools that open the robot bus or the cameras
+DEVICE_TOOLS = ("lerobot-teleoperate", "lerobot-record", "lerobot-replay", "lerobot-rollout", "lerobot-calibrate",
+ "lerobot-setup-motors", "lerobot-find-port", "lerobot-find-cameras", "lerobot-find-joint-limits")
+
+
+def device_users(paths, skip=()):
+ """Processes that can use the robot bus or a camera at the same time as this run: own processes that have one of
+ ``paths`` open (/proc//fd), and a LeRobot robot tool or a dry / live run of this script of ANY user (all
+ users can read the command lines; only root can read the open files of other users' processes).
+ -> ["pid user: why: command", ...]"""
+ import pwd
+ skip = {os.getpid(), *skip}
+ want = {os.path.realpath(os.path.expanduser(str(p))) for p in paths}
+ out = []
+ for d in Path("/proc").iterdir():
+ if not d.name.isdigit() or int(d.name) in skip:
+ continue
+ try:
+ argv = [a.decode(errors="replace") for a in (d / "cmdline").read_bytes().split(b"\0") if a]
+ uid = d.stat().st_uid
+ except OSError:
+ continue
+ if not argv:
+ continue
+ why = []
+ try:
+ fds = list((d / "fd").iterdir())
+ except OSError: # another user's process: its open files are not readable
+ fds = []
+ held = set()
+ for f in fds:
+ try:
+ t = os.readlink(f)
+ except OSError:
+ continue
+ if t in want:
+ held.add(t)
+ if held:
+ why.append("has " + ", ".join(sorted(held)) + " open")
+ names = [a.rsplit("/", 1)[-1].replace("_", "-") for a in argv[:3]]
+ if any(n == t or n.endswith("." + t) for n in names for t in DEVICE_TOOLS):
+ why.append("LeRobot robot tool")
+ if any(a.endswith("run_student_real.py") for a in argv[:3]) and {"dry", "live"} & set(argv):
+ why.append("dry / live run of this script")
+ if why:
+ try:
+ user = pwd.getpwuid(uid).pw_name
+ except KeyError:
+ user = str(uid)
+ out.append(f"{d.name} {user}: {'; '.join(why)}: {' '.join(argv)[:150]}")
+ return out
+
+
+class LeRobotIO:
+ """LeRobot 0.6.2 SO follower + its two OpenCV cameras, used below the ``Robot`` API so that nothing is written
+ unless asked: ``connect`` = bus handshake (reads model numbers and firmware) + calibration check (reads) + cameras;
+ ``writes=False`` replaces every writing method of the bus and of the robot by one that raises."""
+
+ def __init__(self, port, robot_id, cam_paths, writes, calibration_dir=None, fps=30):
+ from lerobot.cameras.opencv.configuration_opencv import ColorMode, Cv2Backends, OpenCVCameraConfig
+ from lerobot.robots.so_follower import SOFollower, SOFollowerRobotConfig
+ cams = {n: OpenCVCameraConfig(index_or_path=Path(p), fps=fps, width=640, height=480, fourcc="MJPG",
+ backend=Cv2Backends(CAM_BACKEND), color_mode=ColorMode.RGB)
+ for n, p in cam_paths.items()}
+ cfg = SOFollowerRobotConfig(port=port, id=robot_id, cameras=cams, disable_torque_on_disconnect=False,
+ use_degrees=True, max_relative_target=None,
+ calibration_dir=Path(calibration_dir) if calibration_dir else None)
+ self.robot = SOFollower(cfg)
+ self.bus = self.robot.bus
+ self.writes = bool(writes)
+ self.bgr = False # LeRobot cameras deliver RGB (color_mode rgb)
+ if not self.writes:
+ block_writes(self.bus, self.robot)
+
+ def calibration_dict(self):
+ return {m: dict(id=c.id, drive_mode=c.drive_mode, homing_offset=c.homing_offset, range_min=c.range_min,
+ range_max=c.range_max) for m, c in self.robot.calibration.items()}
+
+ def connect(self):
+ if not self.robot.calibration:
+ raise RuntimeError(f"no LeRobot calibration file {self.robot.calibration_fpath}: refusing (do not "
+ f"calibrate from this script)")
+ self.bus.connect() # handshake: reads only
+ try:
+ if not self.bus.is_calibrated:
+ raise RuntimeError("the motors' calibration registers differ from the calibration file: refusing "
+ "(LeRobot would ask to recalibrate; investigate first)")
+ for cam in self.robot.cameras.values():
+ cam.connect()
+ except BaseException:
+ self.close(False)
+ raise
+
+ def read_q(self):
+ d = self.bus.sync_read("Present_Position", num_retry=2)
+ return np.asarray([d[m] for m in H.JOINTS], np.float64)
+
+ def frames(self, max_age_ms=1000):
+ out = {}
+ for n, cam in self.robot.cameras.items():
+ img = cam.read_latest(max_age_ms=int(max_age_ms))
+ ts = getattr(cam, "latest_timestamp", None)
+ out[n] = (img, (time.perf_counter() - ts) * 1e3 if ts else float("nan"))
+ return out
+
+ def write_goal(self, q_real):
+ if not self.writes:
+ raise RuntimeError("dry mode: write_goal blocked")
+ self.bus.sync_write("Goal_Position", {m: float(v) for m, v in zip(H.JOINTS, q_real)})
+
+ def torque_on_at_present(self):
+ """Goal = present position (raw ticks), then torque on: no jump to an old goal register."""
+ raw = self.bus.sync_read("Present_Position", normalize=False, num_retry=2)
+ self.bus.sync_write("Goal_Position", raw, normalize=False)
+ self.bus.enable_torque(num_retry=2)
+
+ def disable_torque(self):
+ self.bus.disable_torque(num_retry=5)
+
+ def config_diffs(self):
+ """Registers that LeRobot's ``SOFollower.configure`` would change -> list of strings (reads only)."""
+ cfg = self.robot.config
+ want = {"P_Coefficient": cfg.position_p_coefficient, "I_Coefficient": cfg.position_i_coefficient,
+ "D_Coefficient": cfg.position_d_coefficient, "Return_Delay_Time": 0}
+ diffs = []
+ for m in self.bus.motors:
+ w = dict(want)
+ has = getattr(self.bus, "_has_register", None) # private; not in every LeRobot release
+ for r in ("Maximum_Acceleration", "Acceleration"):
+ try:
+ if has is not None and has(m, r):
+ w[r] = 254
+ except Exception: # noqa: BLE001 (skip this register check)
+ pass
+ try:
+ w["Operating_Mode"] = self.bus._definition(m).operating_modes["position"]
+ except Exception: # noqa: BLE001 (private API; skip the check)
+ pass
+ if m == "gripper":
+ w.update(Max_Torque_Limit=500, Protection_Current=250, Overload_Torque=25)
+ for r, v in w.items():
+ try:
+ got = self.bus.read(r, m, normalize=False, num_retry=1)
+ except Exception as e: # noqa: BLE001
+ diffs.append(f"{m}.{r}: read failed ({e})")
+ continue
+ if int(got) != int(v):
+ diffs.append(f"{m}.{r} = {got} (LeRobot writes {v})")
+ return diffs
+
+ def configure(self):
+ """LeRobot's configure (torque off, register writes, torque on) after goal = present position."""
+ raw = self.bus.sync_read("Present_Position", normalize=False, num_retry=2)
+ self.bus.sync_write("Goal_Position", raw, normalize=False)
+ self.robot.configure()
+
+ def close(self, disable_torque=False):
+ try:
+ if self.bus.is_connected:
+ self.bus.disconnect(disable_torque=bool(disable_torque) and self.writes)
+ finally:
+ for cam in self.robot.cameras.values():
+ try:
+ if cam.is_connected:
+ cam.disconnect()
+ except Exception as e: # noqa: BLE001
+ log(f"camera disconnect: {e}")
+
+
+# ---- keyboard / Ctrl+C stop ----------------------------------------------------------------------------------------
+class Stopper:
+ """Stop request from Ctrl+C (SIGINT) or the keys q, Q, space, Esc in this terminal (cbreak mode while active, no
+ Enter needed). poll() is non-blocking."""
+
+ def __init__(self):
+ self.flag = False
+ self.why = ""
+ self.fd = None
+ self.old_tty = None
+ self.old_sig = None
+
+ def __enter__(self):
+ self.flag = False
+ self.old_sig = signal.signal(signal.SIGINT, self._sig)
+ if sys.stdin.isatty():
+ import termios
+ import tty
+ self.fd = sys.stdin.fileno()
+ self.old_tty = termios.tcgetattr(self.fd)
+ tty.setcbreak(self.fd)
+ return self
+
+ def _sig(self, *_):
+ self.flag, self.why = True, "Ctrl+C"
+
+ def poll(self):
+ if self.fd is not None:
+ while select.select([self.fd], [], [], 0)[0]:
+ ch = os.read(self.fd, 1)
+ if ch in (b"q", b"Q", b" ", b"\x1b"):
+ self.flag, self.why = True, f"key {ch!r}"
+ return self.flag
+
+ def __exit__(self, *exc):
+ if self.old_tty is not None:
+ import termios
+ termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_tty)
+ signal.signal(signal.SIGINT, self.old_sig or signal.default_int_handler)
+ self.fd = self.old_tty = None
+ return False
+
+
+def confirm(word, text, auto=False):
+ print(text, flush=True)
+ if auto:
+ print(f"(fake backend: auto-confirmed {word})")
+ return True
+ try:
+ return input(f"Type {word} to continue, anything else aborts: ").strip() == word
+ except (EOFError, KeyboardInterrupt):
+ return False
+
+
+# ---- shared set-up ------------------------------------------------------------------------------------------------
+def lerobot_calib_path(args):
+ if args.lerobot_calib:
+ return Path(args.lerobot_calib).expanduser()
+ p = (Path(args.calibration_dir).expanduser() if args.calibration_dir else HF_CALIB) / f"{args.robot_id}.json"
+ return p if p.exists() else LOCAL_CALIB_COPY
+
+
+def build_common(args):
+ calib = H.load_calib(args.calib)
+ jm = H.JointMap.from_calib(calib, str(args.calib))
+ qo = parse_q_offset(args.q_offset_deg)
+ if qo is not None: # extra joint-map offset (sim deg; e.g. the table-tilt fix)
+ jm.offset_rad = jm.offset_rad + np.radians(qo)
+ jm.source = f"{jm.source} + --q-offset-deg {args.q_offset_deg}"
+ kp = Path(args.kin_points).expanduser() if args.kin_points else H.default_kin_points()
+ gcfg = H.GuardConfig.from_dict(json.loads(args.guard) if args.guard else {})
+ import torch
+ dev = args.device or ("cuda" if torch.cuda.is_available() else "cpu")
+ policy = H.StudentPolicy(args.student, dev, args.cam_map or None, args.jaw_lead, None if args.amp is None else
+ bool(args.amp))
+ floor = floor_setup(args, calib, policy.meta, gcfg)
+ plane = floor["plane"]
+ layer = H.ActionLayer(kp, table_z=args.table_z) if plane is None else H.ActionLayer(kp, table_z=args.table_z,
+ table_plane=plane)
+ views = H.view_specs(calib, H.REAL_CAMERAS, policy.res, interp=args.interp)
+ # a real2sim student pins the crops it was trained with (cfg.crops, keyed by the student's camera names): use them;
+ # a --crop that differs from them is refused unless --allow-crop-change (the images would differ from training)
+ want = getattr(policy.cfg, "calib_sha256", "") or ""
+ if want and args.calib: # the joint map must be the one the student was trained with
+ import hashlib
+ got = hashlib.sha256(Path(args.calib).expanduser().read_bytes()).hexdigest()
+ if got != want:
+ msg = f"--calib {args.calib} sha256 {got[:12]} != the student's calibration {want[:12]}"
+ if getattr(args, "mode", "") == "live" and not args.allow_calib_change:
+ raise SystemExit(msg + " (live refused; --allow-calib-change to override)")
+ log("WARNING: " + msg)
+ pinned = {policy.cam_map[c]: tuple(int(v) for v in b) for c, b in (getattr(policy.cfg, "crops", None) or {}).items()
+ if c in policy.cam_map}
+ for cam, box in pinned.items():
+ views[cam] = H.ViewSpec(box, (policy.res, policy.res), args.interp, "student checkpoint (cfg.crops)")
+ if args.crop: # override: "external=x,y,w,h;wrist=x,y,w,h"
+ for part in args.crop.split(";"):
+ cam, box = part.split("=")
+ cam, box = cam.strip(), tuple(int(v) for v in box.split(","))
+ if cam in pinned and box != pinned[cam] and not args.allow_crop_change:
+ raise SystemExit(f"--crop {cam}={box} differs from the student's training crop {pinned[cam]} "
+ "(add --allow-crop-change to use it anyway)")
+ views[cam] = H.ViewSpec(box, (policy.res, policy.res), args.interp, "--crop")
+ if not pinned:
+ log("NOTE: the student has no pinned crops (cfg.crops); the views come from --calib / --crop")
+ info = dict(student=policy.ckpt, student_cfg=dict(cameras=policy.cams, res=policy.res, chunk=policy.chunk,
+ n_exec=policy.n_exec, hist=policy.H, cmd_in=policy.cmd_in,
+ img_hist=policy.img_hist, lastcmd=policy.lastcmd,
+ jaw_lead=policy.jaw_lead,
+ amp=policy.amp), device=dev, cam_map=policy.cam_map,
+ calib=str(args.calib) if calib is not None else None, joint_map=jm.describe(), kin_points=str(kp),
+ table_z=args.table_z, guard=gcfg.__dict__, qdot_window=args.qdot_window, qd_gain=args.qd_gain,
+ views={k: dict(crop_xywh=v.crop_xywh, out_wh=v.out_wh, interp=v.interp, source=v.source)
+ for k, v in views.items()})
+ if plane is not None:
+ info["table_plane"] = list(plane)
+ info["floor"] = {k: v for k, v in floor.items() if k != "plane"}
+ return calib, jm, layer, gcfg, policy, views, info
+
+
+def parse_q_offset(spec):
+ """--q-offset-deg "a,b,c,d,e" (sim deg) -> array [5] (deg) or None (empty)."""
+ if not (spec or "").strip():
+ return None
+ try:
+ qo = np.asarray([float(v) for v in str(spec).split(",")], np.float64)
+ except ValueError:
+ qo = np.zeros(0)
+ if qo.shape != (5,) or not np.all(np.isfinite(qo)):
+ raise SystemExit("--q-offset-deg needs 5 values (pan, lift, elbow, wrist_flex, wrist_roll; sim deg)")
+ return qo
+
+
+def floor_setup(args, calib, meta, gcfg):
+ """--floor-mode (hw_lib "floor mode"): auto = the student's mode (``H.student_floor_mode``: plane for a v8
+ table-trained student, else flat; an explicit --table-plane = plane). plane: the floor above --table-plane (default
+ "calib", the calibrated mat plane), --table-z must stay 0; flat: --table-z, no --table-plane. A mode other than the
+ student's, plane-mode floor stops deeper than ``H.PLANE_STOP_MIN_M`` (double lowering) or a --table-plane c0,c1,c2
+ below the calibrated mat plane (``H.floor_problems``): live refuses (unless --allow-floor-mismatch), dry / replay
+ warn. Plane mode with --q-offset-deg (``H.floor_frame_problems``: the floor in the mat), or any --q-offset-deg for
+ a student trained in a table frame (``H.student_table_frame``, also the v12 flat-floor students), or a --table-z
+ other than 0 for a v12 flat-floor student (``H.student_floor_observed``: its training floor was 1.5 mm above arm z
+ 0): live refuses with no override, dry / replay warn. -> dict(mode, student_mode, why, plane, table_plane_spec, problems, lines)."""
+ st_mode, why = H.student_floor_mode(meta)
+ mode = args.floor_mode
+ if mode == "auto":
+ mode = "plane" if args.table_plane else st_mode
+ spec = ""
+ if mode == "plane":
+ if args.table_z != 0.0:
+ raise SystemExit("--floor-mode plane: the floor follows --table-plane; leave --table-z at 0")
+ spec = args.table_plane or "calib"
+ try:
+ plane = H.parse_table_plane(spec, calib)
+ except ValueError as e:
+ raise SystemExit(f"floor mode plane: {e} (--calib {args.calib})") from None
+ else:
+ if args.table_plane:
+ raise SystemExit("--floor-mode flat with --table-plane: give one of them")
+ plane = None
+ calib_plane = None
+ if mode == "plane" and spec != "calib": # a custom plane: checked against the calibrated mat
+ try:
+ calib_plane = H.parse_table_plane("calib", calib)
+ except ValueError:
+ calib_plane = None
+ live = getattr(args, "mode", "") == "live"
+ hard = H.floor_frame_problems(mode, parse_q_offset(getattr(args, "q_offset_deg", "")),
+ table_frame=H.student_table_frame(meta), observed=H.student_floor_observed(meta),
+ table_z=args.table_z)
+ if hard:
+ msg = "floor settings: " + "; ".join(hard)
+ if live:
+ raise SystemExit(msg + " (live refused; no override)")
+ log("WARNING: " + msg)
+ probs = H.floor_problems(mode, st_mode, gcfg, spec, plane, calib_plane)
+ if probs:
+ msg = "floor settings: " + "; ".join(probs)
+ if live and not args.allow_floor_mismatch:
+ raise SystemExit(msg + " (live refused; --allow-floor-mismatch to override)")
+ log("WARNING: " + msg)
+ return dict(mode=mode, student_mode=st_mode, why=why, plane=plane, table_plane_spec=spec, problems=hard + probs,
+ lines=H.floor_lines(mode, why, args.table_z, plane, gcfg))
+
+
+def print_setup(info):
+ jm = info["joint_map"]
+ log(f"student {info['student']} cameras {info['student_cfg']['cameras']} <- {info['cam_map']} res "
+ f"{info['student_cfg']['res']} device {info['device']}")
+ log(f"joint map: {'PLACEHOLDER ' if jm['placeholder'] else ''}{jm['source']} sign {jm['sign']} offset_rad "
+ f"{np.round(jm['offset_rad'], 4).tolist()} gripper_lin {np.round(jm['gripper_lin'], 5).tolist()}")
+ for s in info["floor"]["lines"]:
+ log(s)
+ g = info["guard"]
+ if g.get("i_time_s", 0) > 0:
+ log(f"servo-error integral correction: i_time_s {g['i_time_s']:g}, at most {g['i_max_deg']:g} deg, anti-windup "
+ f"at the real joint range {'ON' if g.get('i_antiwindup') else 'OFF'}")
+ if info.get("home_sim_deg") is not None:
+ log(f"HOME sim deg {info['home_sim_deg']} (--home)")
+ for k, v in info["views"].items():
+ log(f"view {k}: crop {v['crop_xywh']} -> {v['out_wh']} ({v['interp']}, {v['source']})")
+ if info.get("qd_gain", 1.0) != 1.0:
+ log(f"qdot input gain {info['qd_gain']} (the student's qdot input x {info['qd_gain']}; guard and log: measured)")
+
+
+def parse_home(spec):
+ """--home "a,b,c,d,e,f" (sim deg) -> sim rad [6]."""
+ try:
+ h = np.radians(np.asarray([float(v) for v in str(spec).split(",")], np.float64))
+ except ValueError:
+ h = np.zeros(0)
+ if h.shape != (6,) or not np.all(np.isfinite(h)):
+ raise SystemExit("--home needs 6 values (sim degrees)")
+ return h
+
+
+def run_deploy_json(args):
+ """make_orin_bundle.sh: the bundle's assets/deploy.json = what robot_test.sh passes to every run of this bundle:
+ the floor mode of the student (``H.student_floor_mode``, read from the checkpoint), the table plane source, HOME,
+ the eval session's guard (``H.eval_guard``), and the banner's floor lines. Reads the checkpoint only (no model)."""
+ import hashlib
+
+ import torch
+ ck_path = Path(args.student).expanduser()
+ ck = torch.load(ck_path, map_location="cpu", weights_only=False)
+ meta = {k: v for k, v in ck.items() if k not in ("state_dict", "stats")}
+ mode, why = H.student_floor_mode(meta)
+ calib = H.load_calib(args.calib)
+ plane = None
+ if mode == "plane":
+ try:
+ plane = H.parse_table_plane("calib", calib)
+ except ValueError as e:
+ raise SystemExit(f"deploy-json: the student needs the plane floor: {e} (--calib {args.calib})") from None
+ home = np.degrees(parse_home(args.home))
+ eg = H.eval_guard(mode)
+ rec = dict(version=1, built=time.strftime("%Y-%m-%d %H:%M:%S"),
+ 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",
+ student_sha256=hashlib.sha256(ck_path.read_bytes()).hexdigest(), floor_mode=mode, floor_why=why,
+ table_plane="calib" if mode == "plane" else "", table_plane_coef=None if plane is None else list(plane),
+ table_frame=H.student_table_frame(meta),
+ table_z=0.0, home_sim_deg=",".join(f"{v:g}" for v in np.round(home, 6)), eval_guard=eg,
+ eval_floor_lines=H.floor_lines(mode, why, 0.0, plane, H.GuardConfig.from_dict(eg)))
+ out = Path(args.out).expanduser()
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(json.dumps(rec, indent=1) + "\n")
+ log(f"deploy settings -> {out}: floor mode {mode}, HOME sim deg {rec['home_sim_deg']}, eval guard {eg}")
+ for s in rec["eval_floor_lines"]:
+ log(s)
+ return rec
+
+
+# ---- replay -------------------------------------------------------------------------------------------------------
+class LeRobotEpisode:
+ """One episode of a LeRobot v3 recording (read only; the files are data, nothing in them is executed): joints at
+ 30 Hz and the two camera videos (one mp4 per camera with every episode, ``meta/episodes`` from / to timestamps)."""
+
+ def __init__(self, root, episode, cams=H.REAL_CAMERAS):
+ import cv2
+ import pyarrow.parquet as pq
+ self.root, self.episode = Path(root).expanduser(), int(episode)
+ info = json.loads((self.root / "meta" / "info.json").read_text())
+ self.fps = float(info["fps"])
+ t = pq.read_table(self.root / "data" / "chunk-000" / "file-000.parquet").to_pydict()
+ e = pq.read_table(self.root / "meta" / "episodes" / "chunk-000" / "file-000.parquet").to_pydict()
+ ep = np.asarray(t["episode_index"])
+ m = ep == self.episode
+ if not m.any():
+ raise ValueError(f"episode {episode} not in {root}")
+ order = np.argsort(np.asarray(t["frame_index"])[m])
+ self.state = np.asarray(t["observation.state"], np.float64)[m][order]
+ self.action = np.asarray(t["action"], np.float64)[m][order]
+ self.n = len(self.state)
+ self.t = np.arange(self.n) / self.fps
+ self.duration = (self.n - 1) / self.fps
+ k = list(e["episode_index"]).index(self.episode)
+ self.caps, self.next_idx, self.cur, self.first = {}, {}, {}, {}
+ for c in cams:
+ key = f"videos/observation.images.{c}"
+ ci, fi = int(e[f"{key}/chunk_index"][k]), int(e[f"{key}/file_index"][k])
+ path = self.root / "videos" / f"observation.images.{c}" / f"chunk-{ci:03d}" / f"file-{fi:03d}.mp4"
+ cap = cv2.VideoCapture(str(path))
+ if not cap.isOpened():
+ raise RuntimeError(f"cannot open {path}")
+ self.first[c] = int(round(float(e[f"{key}/from_timestamp"][k]) * self.fps))
+ for _ in range(self.first[c]): # sequential skip (exact; h264 seeks can be off)
+ if not cap.grab():
+ raise RuntimeError(f"{path}: video ended before episode {episode}")
+ self.caps[c], self.next_idx[c], self.cur[c] = cap, 0, None
+
+ def _interp(self, a, t):
+ x = min(max(t * self.fps, 0.0), self.n - 1.0)
+ i = min(int(x), self.n - 2) if self.n > 1 else 0
+ w = x - i
+ return a[i] * (1 - w) + a[min(i + 1, self.n - 1)] * w
+
+ def q_at(self, t):
+ return self._interp(self.state, t)
+
+ def action_at(self, t):
+ return self._interp(self.action, t)
+
+ def frames_at(self, t):
+ """{camera: (BGR frame of the newest recorded frame at or before t, nan)}."""
+ i = min(int(math.floor(t * self.fps + 1e-6)), self.n - 1)
+ out = {}
+ for c, cap in self.caps.items():
+ while self.next_idx[c] <= i:
+ ok, f = cap.read()
+ if not ok:
+ raise RuntimeError(f"video {c} ended at episode frame {self.next_idx[c]}")
+ self.cur[c] = f
+ self.next_idx[c] += 1
+ out[c] = (self.cur[c], float("nan"))
+ return out
+
+ def close(self):
+ for cap in self.caps.values():
+ cap.release()
+
+
+def episode_labels(calib, dataset, episode):
+ for e in (calib or {}).get("episodes") or []:
+ if str(e.get("dataset")) == dataset and int(e.get("episode", -1)) == int(episode):
+ return e
+ return None
+
+
+def wrap45(d):
+ return (np.asarray(d) + 45.0) % 90.0 - 45.0
+
+
+def run_replay(args):
+ calib, jm, layer, gcfg, policy, views, info = build_common(args)
+ print_setup(info)
+ limits = H.RealLimits.from_lerobot_calibration(lerobot_calib_path(args), gcfg.range_margin_deg)
+ out_dir = Path(args.out).expanduser()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ policy.warmup()
+ summaries = []
+ for spec in args.episodes.split(","):
+ ds, e = spec.split(":")
+ ep = LeRobotEpisode(Path(args.data_root).expanduser() / ds, int(e))
+ guard = H.Guard(gcfg, layer, jm, limits)
+ ctrl = H.Controller(policy, jm, guard, views, H.QdotEstimator(args.qdot_window), bgr=True,
+ max_frame_age_ms=float("inf"), thumb_res=args.thumb_res, qd_gain=args.qd_gain)
+ ctrl.reset(ep.q_at(0.0))
+ T = ep.duration if args.max_seconds <= 0 else min(ep.duration, args.max_seconds)
+ n = int(math.floor(T / H.DT)) + 1
+ rec_act, t0 = [], time.time()
+ for s in range(n):
+ t = s * H.DT
+ ctrl.step(t, ep.q_at(t), lambda t=t: ep.frames_at(t))
+ rec_act.append(ep.action_at(t))
+ wall = time.time() - t0
+ ep.close()
+ A = ctrl.arrays()
+ rec_act = np.asarray(rec_act)
+ A["rec_action_real"] = rec_act
+ A["rec_action_sim"] = jm.real_to_sim(rec_act)
+ # the chunk against the recorded leader action at the step each target is meant for (target j of a query at
+ # step k drives step k + j)
+ qs = A["qry_step"]
+ K = A["qry_chunk"].shape[1]
+ err = np.full((len(qs), K, 6), np.nan)
+ for i, k in enumerate(qs):
+ for j in range(K):
+ if k + j < n:
+ err[i, j] = A["qry_chunk"][i, j] - A["rec_action_sim"][k + j]
+ lab = episode_labels(calib, ds, e)
+ aux = dict(labels=lab is not None)
+ if lab is not None:
+ tq = A["qry_t"]
+ pre = tq < float(lab.get("grasp_frame", 1e9)) / ep.fps if lab.get("grasp_frame") is not None else \
+ np.ones(len(tq), bool)
+ cxyz = np.asarray(lab["cube_start_xyz"], np.float64)
+ pxy = np.asarray(lab["plate_xy"], np.float64)
+ ce = np.linalg.norm(A["qry_cube_xyz"] - cxyz, axis=-1)
+ pe = np.linalg.norm(A["qry_plate_xy"] - pxy, axis=-1)
+ ye = np.abs(wrap45(A["qry_plate_yaw4_deg"] - float(lab["plate_yaw_deg"])))
+ aux.update(cube_err_mm_before_grasp_p50=float(np.median(ce[pre]) * 1e3) if pre.any() else None,
+ n_before_grasp=int(pre.sum()), plate_xy_err_mm_p50=float(np.median(pe) * 1e3),
+ plate_yaw_err_deg_p50=float(np.median(ye)), n_queries=int(len(tq)))
+ A["lab_cube_start_xyz"], A["lab_plate_xy"] = cxyz, pxy
+ A["lab_plate_yaw_deg"] = np.float64(lab["plate_yaw_deg"])
+ lat = H.latency_summary({k: A[k] for k in ("ms_qdot", "ms_frames", "ms_pre", "ms_model", "ms_guard",
+ "ms_ctrl")})
+ evc = {k: int(A["ev_" + k].sum()) for k in ("step", "lead", "range", "floor", "real_range", "max_rel")}
+ summ = dict(dataset=ds, episode=int(e), seconds=T, steps=n, queries=int(len(qs)), wall_s=wall,
+ chunk_vs_rec_action_mae_deg=np.degrees(np.nanmean(np.abs(err), axis=(0, 1))).round(3).tolist(),
+ chunk_vs_rec_action_mae_deg_by_j=np.degrees(np.nanmean(np.abs(err[..., :5]), axis=(0, 2))).round(
+ 3).tolist(),
+ exec_vs_rec_action_mae_deg=np.degrees(np.nanmean(np.abs(err[:, :policy.n_exec]), axis=(0, 1))).round(
+ 3).tolist(),
+ aux=aux, rule_active_steps=evc, guard_reasons=ctrl.events, latency_ms=lat,
+ pred_cube_xyz_p50=np.median(A["qry_cube_xyz"], 0).round(4).tolist(),
+ pred_plate_xy_p50=np.median(A["qry_plate_xy"], 0).round(4).tolist(),
+ pred_plate_yaw4_deg_p50=float(np.median(A["qry_plate_yaw4_deg"])))
+ meta = dict(mode="replay", setup=info, summary=summ, note="student outputs on real images; the student was "
+ "trained on sim images of other cameras unless the setup says otherwise")
+ H.save_log(out_dir / f"{ds}_ep{int(e):02d}.npz", A, meta)
+ summaries.append(summ)
+ log(f"{ds} ep {e}: {n} steps, {len(qs)} queries in {wall:.1f} s; chunk vs recorded action MAE deg "
+ f"{summ['chunk_vs_rec_action_mae_deg']}; model ms p50 {lat['ms_model']['p50']:.1f} p95 "
+ f"{lat['ms_model']['p95']:.1f}; guard reasons {list(ctrl.events)}")
+ (out_dir / "replay_summary.json").write_text(json.dumps(dict(setup=info, episodes=summaries), indent=1,
+ default=str))
+ log(f"wrote {out_dir}")
+ return summaries
+
+
+# ---- robot loop (dry / live) ------------------------------------------------------------------------------------------
+def hold(io, jm, limits, q_real, grip_cmd_real):
+ """Hold: arm at the measured q, gripper at its last command (keeps the grip), inside the calibrated range."""
+ h = np.asarray(q_real, np.float64).copy()
+ if grip_cmd_real is not None and np.isfinite(grip_cmd_real):
+ h[H.ARM] = grip_cmd_real
+ h, _ = limits.clip(h)
+ io.write_goal(h)
+ return h
+
+
+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,
+ settle_s=3.0, label="move"):
+ """Execute a checked joint path at 50 Hz: each command clamped to the calibrated range and to max_rel (LeRobot units)
+ around the measured q; the path does not advance while an arm joint is more than track_tol (rad) from the previous
+ waypoint (stop after pause_max_s); afterwards wait until every arm joint is within settle_tol of the end.
+ -> (stop reason or None, last command real)."""
+ i, paused, last = 0, 0.0, None
+ n = len(path_sim)
+ t_next = time.perf_counter()
+ t_settle = None
+ while True:
+ if stopper.poll():
+ return f"user stop ({stopper.why})", last
+ q_real = io.read_q()
+ q_sim = jm.real_to_sim(q_real)
+ bad = guard.check_measured(q_sim, q_real)
+ if bad:
+ return f"{label}: " + bad[0], last
+ ref = path_sim[max(i - 1, 0)]
+ err = float(np.abs(q_sim[:H.ARM] - ref[:H.ARM]).max())
+ if err > track_tol and i > 0:
+ paused += H.DT
+ if paused > pause_max_s:
+ return f"{label}: arm not following (error {err:.2f} rad for {paused:.1f} s)", last
+ else:
+ paused = 0.0
+ i = min(i + 1, n)
+ cmd = jm.sim_to_real(path_sim[i - 1] if i > 0 else path_sim[0])
+ cmd, _ = limits.clip(cmd)
+ cmd = np.minimum(np.maximum(cmd, q_real - max_rel), q_real + max_rel)
+ io.write_goal(cmd)
+ last = cmd
+ if i >= n:
+ e_end = float(np.abs(q_sim[:H.ARM] - path_sim[-1][:H.ARM]).max())
+ t_settle = t_settle or time.perf_counter()
+ if e_end < settle_tol:
+ return None, last
+ if time.perf_counter() - t_settle > settle_s:
+ log(f"{label}: end error {e_end:.3f} rad after {settle_s} s (continuing)")
+ return None, last
+ t_next += H.DT
+ if time.perf_counter() > t_next + H.DT:
+ t_next = time.perf_counter()
+ H.precise_wait(t_next)
+
+
+def control_loop(io, ctrl, guard, jm, limits, stopper, live, time_limit, status_every=1.0):
+ """The student at 50 Hz on the robot. -> (end reason, last command real, timing columns)."""
+ W = {k: [] for k in ("ms_read", "ms_write", "ms_step", "late_ms")}
+ q0 = io.read_q()
+ ctrl.reset(q0)
+ t_start = time.perf_counter()
+ t_next = t_start
+ overruns, last_cmd, prev_sim = 0, None, None
+ reason = "time limit"
+ t_status = t_start
+ while True:
+ now = time.perf_counter()
+ W["late_ms"].append((now - t_next) * 1e3)
+ t = now - t_start
+ if t >= time_limit:
+ break
+ if stopper.poll():
+ reason = f"user stop ({stopper.why})"
+ break
+ t0 = time.perf_counter()
+ try:
+ q_real = io.read_q()
+ except Exception as e: # noqa: BLE001
+ reason = f"joint read failed: {e}"
+ break
+ W["ms_read"].append((time.perf_counter() - t0) * 1e3)
+ try:
+ out = ctrl.step(t, q_real, lambda: io.frames(1000))
+ except Exception as e: # noqa: BLE001
+ reason = f"step failed: {type(e).__name__}: {e}"
+ break
+ stop = list(out.stop)
+ if live:
+ stop += guard.stall(jm.real_to_sim(q_real), prev_sim)
+ if stop:
+ reason = "guard: " + stop[0]
+ break
+ t1 = time.perf_counter()
+ try:
+ io.write_goal(out.u_real)
+ except Exception as e: # noqa: BLE001
+ reason = f"goal write failed: {e}"
+ break
+ W["ms_write"].append((time.perf_counter() - t1) * 1e3)
+ last_cmd = out.u_real
+ prev_sim = None if out.u_sim is None else guard.prev.copy() # stall check: without the integral correction
+ W["ms_step"].append((time.perf_counter() - t0) * 1e3)
+ if time.perf_counter() - t_status >= status_every:
+ t_status = time.perf_counter()
+ r = ctrl.S
+ k = len(r["t"])
+ rate = (k - 1) / max(r["t"][-1] - r["t"][0], 1e-9) if k > 1 else 0.0
+ log(f"t {t:5.1f} s {rate:5.1f} Hz step ms max {max(W['ms_step'][-50:]):.1f} q_real "
+ f"{np.round(q_real, 1).tolist()} overruns {overruns}" + (f" WOULD STOP: {stop[0]}" if stop else ""))
+ t_next += H.DT
+ if time.perf_counter() > t_next + H.DT: # more than a period behind: no burst, resync
+ overruns += 1
+ t_next = time.perf_counter()
+ H.precise_wait(t_next)
+ W["overruns"] = overruns
+ return reason, last_cmd, W
+
+
+def preflight(io, jm, limits, guard, layer, reads=3):
+ """Reads only: q (finite, consistent between reads, inside the calibrated range), camera frames (fresh, 480 x
+ 640). -> (q_real, report lines, problems)."""
+ qs = [io.read_q() for _ in range(reads)]
+ q = qs[-1]
+ rep, bad = [], []
+ if not all(np.all(np.isfinite(x)) for x in qs):
+ bad.append("joint read not finite")
+ spread = np.max(np.ptp(np.stack(qs), axis=0))
+ rep.append(f"q real {np.round(q, 2).tolist()} (spread over {reads} reads {spread:.2f})")
+ qs_ = jm.real_to_sim(q)
+ rep.append(f"q sim deg {np.round(np.degrees(qs_), 1).tolist()} grasp point {np.round(layer.tcp(qs_), 3).tolist()} "
+ f"lowest gripper point {float(layer.lowest(qs_)) * 1e3:.1f} mm")
+ out = limits.outside(q, guard.cfg.measured_range_tol)
+ if out.any():
+ bad.append("measured q outside the calibrated range: " + str([H.JOINTS[i] for i in np.flatnonzero(out)]))
+ fr = io.frames(1000)
+ for c in H.REAL_CAMERAS:
+ if c not in fr:
+ bad.append(f"camera {c} missing")
+ continue
+ img, age = fr[c]
+ rep.append(f"camera {c}: {img.shape} {img.dtype} age {age:.0f} ms mean {img.mean():.0f}")
+ if img.shape != (480, 640, 3):
+ bad.append(f"camera {c} shape {img.shape}")
+ if np.isfinite(age) and age > 200:
+ bad.append(f"camera {c} frame {age:.0f} ms old")
+ return q, rep, bad, fr
+
+
+def run_robot(args, live):
+ mode = "live" if live else "dry"
+ fake = args.backend == "fake"
+ if args.auto_confirm and not fake:
+ raise SystemExit("--auto-confirm is only for --backend fake")
+ calib, jm, layer, gcfg, policy, views, info = build_common(args)
+ home_sim = parse_home(args.home)
+ info["home_sim_deg"] = [round(float(v), 6) for v in np.degrees(home_sim)]
+ print_setup(info)
+ if live and not args.i_am_supervising:
+ raise SystemExit("live mode moves the robot: pass --i-am-supervising and stay at the robot")
+ if live and jm.placeholder and not fake:
+ raise SystemExit(f"live mode needs a real joint map in {args.calib} (calib_v1.json joint_map); the placeholder "
+ f"identity map is not verified")
+ out_dir = Path(args.out).expanduser()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ policy.warmup()
+ if fake:
+ q_rest = np.asarray([0.0, -88.0, 84.0, 65.0, 0.0, 20.0]) # folded rest pose of the recordings
+ io = H.FakeRobotIO(q_rest, writes=live)
+ limits = H.RealLimits.from_lerobot_calibration(lerobot_calib_path(args), gcfg.range_margin_deg)
+ else:
+ cam_paths = CAM_PATHS if not args.cam_paths else json.loads(args.cam_paths)
+ busy = device_users([args.port, *cam_paths.values()])
+ if busy: # two writers on the motor bus = two programs move the arm
+ raise SystemExit(f"{mode} refused: another process can use the robot bus or a camera. Stop it first:\n "
+ + "\n ".join(busy))
+ io = LeRobotIO(args.port, args.robot_id, cam_paths, writes=live, calibration_dir=args.calibration_dir)
+ limits = H.RealLimits.from_lerobot_calibration(io.calibration_dict(), gcfg.range_margin_deg,
+ source=str(io.robot.calibration_fpath))
+ guard = H.Guard(gcfg, layer, jm, limits)
+ log(f"{mode}: connecting ({'fake robot' if fake else args.port}) ...")
+ io.connect()
+ meta = dict(mode=mode, setup=info, limits=dict(lo=limits.lo.tolist(), hi=limits.hi.tolist(), source=limits.source),
+ home_sim_deg=np.degrees(home_sim).tolist(), start=time.strftime("%Y-%m-%d %H:%M:%S"))
+ disable_torque, last_cmd, torque_on = False, None, False
+ st_ = dict(ctrl=None, W=None, saved=False, dir=out_dir)
+ sess = live and args.episodes_n > 0 # eval session (even with 1 episode); 0 = plain live run
+ n_ep = args.episodes_n if sess else 1
+
+ def save(reason):
+ """Episode log (npz + json); also called from ``finally`` after an error (partial log)."""
+ meta["end_reason"] = reason
+ ctrl_, W_ = st_["ctrl"], st_["W"]
+ A = ctrl_.arrays() if ctrl_ is not None else {}
+ if W_ is not None:
+ for k, v in W_.items():
+ A["robot_" + k] = np.asarray(v)
+ lat = H.latency_summary({**{k: A[k] for k in ("ms_qdot", "ms_frames", "ms_pre", "ms_model", "ms_guard",
+ "ms_ctrl") if k in A},
+ **{k: W_[k] for k in ("ms_read", "ms_write", "ms_step", "late_ms")}})
+ meta.update(latency_ms=lat, overruns=W_["overruns"])
+ if ctrl_ is not None:
+ meta.update(guard_reasons=ctrl_.events, rule_active_steps={
+ k: int(A["ev_" + k].sum()) for k in ("step", "lead", "range", "floor", "real_range", "max_rel")
+ if "ev_" + k in A})
+ H.save_log(st_["dir"] / f"episode_{mode}.npz", A, meta)
+ st_["saved"] = True
+ return meta.get("latency_ms", {})
+
+ def finish(reason):
+ """Save the episode log, print the timing lines."""
+ lat = save(reason)
+ for k in ("ms_read", "ms_model", "ms_ctrl", "ms_write", "ms_step"):
+ if k in lat:
+ v = lat[k]
+ log(f"latency {k}: p50 {v['p50']:.1f} p95 {v['p95']:.1f} max {v['max']:.1f} ms (n {v['n']})")
+ if st_["W"] is not None:
+ log(f"overruns (> one period behind): {st_['W']['overruns']}; log {st_['dir'] / f'episode_{mode}.npz'}")
+
+ def new_ctrl():
+ return H.Controller(policy, jm, guard, views, H.QdotEstimator(args.qdot_window), bgr=io.bgr,
+ max_frame_age_ms=args.max_frame_age_ms, thumb_res=args.thumb_res, qd_gain=args.qd_gain)
+
+ reason = "not started"
+ try:
+ q_start, rep, bad, fr = preflight(io, jm, limits, guard, layer)
+ for r in rep:
+ log("preflight: " + r)
+ meta.update(preflight=rep, preflight_problems=bad, q_start_real=q_start.tolist())
+ for c, (img, _) in fr.items():
+ meta.setdefault("first_frame_mean", {})[c] = float(img.mean())
+ np.savez_compressed(out_dir / "first_frames.npz", **{c: img for c, (img, _) in fr.items()})
+ if bad:
+ raise SystemExit("preflight failed: " + "; ".join(bad))
+ ctrl = new_ctrl()
+ st_["ctrl"] = ctrl
+ if not live:
+ log("dry: NO motor writes; torque untouched. q / space / Esc / Ctrl+C stops.")
+ with Stopper() as st:
+ reason, _, W = control_loop(io, ctrl, guard, jm, limits, st, False, args.time_limit)
+ st_["W"] = W
+ log(f"dry ended: {reason}")
+ else:
+ # 1. LeRobot motor configuration (only if needed / asked)
+ if not fake:
+ diffs = io.config_diffs()
+ meta["config_diffs"] = diffs
+ do = args.configure == "always" or (args.configure == "auto" and diffs)
+ if diffs:
+ log("registers that LeRobot's configure would change: " + "; ".join(diffs))
+ if do:
+ if not confirm("CONFIGURE", "LeRobot's configure turns the torque OFF for a moment and writes motor "
+ "registers (some in EEPROM). The arm must rest on its stops (folded rest pose)."):
+ raise SystemExit("aborted before configure")
+ io.configure()
+ torque_on = True
+ log("configured (torque on, goal = present position)")
+ # 2. HOME (checked first), 3. the student; eval (--episodes-n >= 1): back to HOME between the episodes
+ results, session = [], out_dir / "session.json"
+
+ def record(ep, reason, outcome):
+ meta["outcome"] = outcome
+ finish(reason)
+ results.append(dict(episode=ep + 1, end_reason=reason, dir=str(st_["dir"]),
+ start=meta.get("episode_start"), **outcome))
+ session.write_text(json.dumps(dict(start=meta["start"], args=vars(args), episodes=results), indent=1,
+ default=str))
+ for ep in range(n_ep):
+ if ep > 0:
+ st_.update(ctrl=new_ctrl(), W=None, saved=False)
+ ctrl = st_["ctrl"]
+ for k in ("outcome", "latency_ms", "overruns", "guard_reasons", "rule_active_steps",
+ "home_path_steps", "home_path_s", "home_problems"):
+ meta.pop(k, None)
+ if sess:
+ st_["dir"] = out_dir / f"ep_{ep + 1:02d}"
+ st_["dir"].mkdir(parents=True, exist_ok=True)
+ meta.update(episode=ep + 1, episode_start=time.strftime("%Y-%m-%d %H:%M:%S"))
+ log(f"==== episode {ep + 1} / {n_ep}")
+ q_now = jm.real_to_sim(io.read_q())
+ path, dur = H.plan_joint_path(q_now, home_sim, math.radians(args.home_speed_deg_s))
+ probs = H.check_path(path, layer, jm, limits, clearance=args.home_clearance, start=q_now)
+ for k in range(0, len(path), 5):
+ probs += [f"waypoint {k}: {s}" for s in guard._box(layer.tcp(path[k]))][:1]
+ home_real = jm.sim_to_real(home_sim)
+ log(f"HOME sim deg {np.round(np.degrees(home_sim), 1).tolist()} = real {np.round(home_real, 1).tolist()}; "
+ f"grasp point {np.round(layer.tcp(home_sim), 3).tolist()} lowest {float(layer.lowest(home_sim)) * 1e3:.0f}"
+ f" mm; {len(path)} steps = {dur:.1f} s at <= {args.home_speed_deg_s} deg/s")
+ meta.update(home_path_steps=len(path), home_path_s=dur, home_problems=probs)
+ if probs:
+ if not torque_on:
+ raise SystemExit("HOME path refused: " + "; ".join(probs[:5]))
+ reason = "HOME path refused: " + "; ".join(probs[:5])
+ log(reason + " (holding; menu below)")
+ break
+ if ep == 0 and not confirm("MOVE", f"Torque ON at the present position, then a {dur:.1f} s joint move to "
+ f"HOME. Keep a hand near the arm; q / space / Esc / Ctrl+C holds.",
+ args.auto_confirm):
+ if not torque_on:
+ raise SystemExit("aborted before HOME")
+ reason = "aborted before HOME"
+ break
+ if not torque_on:
+ io.torque_on_at_present()
+ torque_on = True
+ with Stopper() as st:
+ why, last_cmd = move_path(io, path, jm, limits, guard, st, np.asarray(gcfg.max_rel_real),
+ label="home")
+ if why:
+ q = io.read_q()
+ last_cmd = hold(io, jm, limits, q, None if last_cmd is None else last_cmd[H.ARM])
+ reason = f"HOME move stopped: {why}"
+ log(reason + " (holding; menu below)")
+ break
+ log(f"at HOME: q real {np.round(io.read_q(), 1).tolist()}")
+ if not confirm("RUN", f"Student loop for up to {args.time_limit:.0f} s at 50 Hz (query every 0.1 s). "
+ f"{'Reset the scene: p' if ep else 'P'}lace the cube and the plate now. q / space / Esc / "
+ f"Ctrl+C stops and holds.", args.auto_confirm):
+ reason = "aborted before the student loop (holding at HOME)"
+ log(reason + "; menu below")
+ break
+ with Stopper() as st:
+ reason, lc, W = control_loop(io, ctrl, guard, jm, limits, st, True, args.time_limit)
+ st_["W"] = W
+ last_cmd = lc if lc is not None else last_cmd
+ try:
+ q = io.read_q()
+ last_cmd = hold(io, jm, limits, q, None if last_cmd is None else last_cmd[H.ARM])
+ log(f"student loop ended: {reason}; HOLDING at q real {np.round(q, 1).tolist()}")
+ except Exception as e: # noqa: BLE001
+ log(f"student loop ended: {reason}; HOLD FAILED: {e}")
+ reason += f"; hold failed: {e}"
+ if sess:
+ record(ep, reason, UNKNOWN)
+ break
+ if not sess:
+ break
+ record(ep, reason, ask_outcome(ep + 1, n_ep, args.auto_confirm))
+ if ep + 1 < n_ep and not ask_next(ep + 2, n_ep, args.auto_confirm):
+ break
+ if results:
+ print_session(results, session)
+ if not st_["saved"]:
+ finish(reason)
+ if live:
+ disable_torque, last_cmd = end_menu(io, jm, limits, layer, guard, q_start, args, last_cmd)
+ except BaseException as e:
+ reason = f"{type(e).__name__}: {e}"
+ raise
+ finally:
+ if not st_["saved"]:
+ try:
+ save(reason)
+ log(f"partial log {st_['dir'] / f'episode_{mode}.npz'} ({reason})")
+ except Exception as e: # noqa: BLE001
+ log(f"saving the log failed: {e}")
+ if live and torque_on and not disable_torque:
+ try:
+ q = io.read_q()
+ hold(io, jm, limits, q, None if last_cmd is None else last_cmd[H.ARM])
+ except Exception as e: # noqa: BLE001
+ log(f"final hold failed: {e}")
+ io.close(disable_torque=disable_torque)
+ log(f"closed ({'torque OFF' if disable_torque else 'torque unchanged / ON, holding' if live else 'no writes'})")
+ return meta
+
+
+UNKNOWN = dict(grasp=None, lift=None, place=None, note="no result typed")
+
+
+def ask_outcome(ep, n, auto=False):
+ """Eval: the result of an episode, typed by the person at the robot (None = not known)."""
+ if auto:
+ return dict(grasp=False, lift=False, place=False, note="auto")
+ while True:
+ try:
+ a = input(f"Episode {ep} / {n} result: letters for each stage reached, g = grasp, l = lift, p = placed on "
+ f"the plate (for example glp, or - for none); a note after a space: ").strip()
+ except (EOFError, KeyboardInterrupt):
+ return dict(UNKNOWN)
+ code, _, note = a.partition(" ")
+ if code and set(code.lower()) <= set("glp-"):
+ c = code.lower()
+ return dict(grasp="g" in c, lift="l" in c, place="p" in c, note=note.strip(), typed=a)
+
+
+def ask_next(ep, n, auto=False):
+ """Eval: True = return to HOME for episode ep, False = stop (menu)."""
+ if auto:
+ return True
+ while True:
+ try:
+ a = input(f"[r] return to HOME for episode {ep} / {n} (the gripper opens to its HOME value) "
+ f"[s] stop the session (menu) > ").strip().lower()
+ except (EOFError, KeyboardInterrupt):
+ return False
+ if a in ("r", "s"):
+ return a == "r"
+
+
+def print_session(results, path):
+ n = len(results)
+ def c(k):
+ return sum(r[k] is True for r in results)
+
+ def f(r, k, ch):
+ return "?" if r[k] is None else ch if r[k] else "-"
+ log(f"session: {n} episodes; grasp {c('grasp')}, lift {c('lift')}, placed {c('place')} "
+ f"(not known: {sum(r['grasp'] is None for r in results)}); {path}")
+ for r in results:
+ log(f" episode {r['episode']:2d}: {f(r, 'grasp', 'g')}{f(r, 'lift', 'l')}{f(r, 'place', 'p')} "
+ f"{r['end_reason']} {r.get('note', '')}")
+
+
+def end_menu(io, jm, limits, layer, guard, q_start_real, args, last_cmd):
+ """-> (disable torque at close?, the last command: the final hold keeps its gripper). Default: keep holding."""
+ if args.auto_confirm:
+ return False, last_cmd
+ while True:
+ try:
+ c = input("[h] hold and exit (torque stays ON) [r] slow return to the start pose [t] torque OFF "
+ "(support the arm first) > ").strip().lower() or "h"
+ except (EOFError, KeyboardInterrupt):
+ return False, last_cmd
+ if c == "h":
+ return False, last_cmd
+ if c == "t":
+ try:
+ ok = input("Type TORQUE OFF: ").strip() == "TORQUE OFF"
+ except (EOFError, KeyboardInterrupt):
+ ok = False
+ if ok:
+ return True, last_cmd
+ continue
+ if c == "r":
+ q_now = jm.real_to_sim(io.read_q())
+ goal = jm.real_to_sim(q_start_real)
+ path, dur = H.plan_joint_path(q_now, goal, math.radians(args.home_speed_deg_s))
+ probs = H.check_path(path, layer, jm, limits, clearance=args.home_clearance, start=q_now, goal_measured=True)
+ if probs:
+ log("return path refused: " + "; ".join(probs[:3]))
+ continue
+ if not confirm("MOVE", f"{dur:.1f} s joint move back to the start pose."):
+ continue
+ with Stopper() as st:
+ why, lc = move_path(io, path, jm, limits, guard, st, np.asarray(guard.cfg.max_rel_real), label="return")
+ q = io.read_q()
+ last_cmd = hold(io, jm, limits, q, None if lc is None else lc[H.ARM])
+ log(f"return: {why or 'done'}; q real {np.round(q, 1).tolist()}")
+
+
+# ---- CLI --------------------------------------------------------------------------------------------------------------
+def main(argv=None):
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawTextHelpFormatter,
+ allow_abbrev=False) # robot_test.sh checks the full flag names
+ ap.add_argument("mode", choices=("replay", "dry", "live", "deploy-json"),
+ help="deploy-json: write the bundle's assets/deploy.json (--out) for --student (make_orin_bundle.sh)")
+ ap.add_argument("--student", required=True, help="ViralNet checkpoint (vision.viral.save_student)")
+ ap.add_argument("--calib", default=str(DEFAULT_CALIB_V1), help="calib_v1.json (joint_map, student_view, episodes)")
+ ap.add_argument("--kin-points", default="", help="kin_points_v1.npz (default: hw_lib.default_kin_points)")
+ ap.add_argument("--device", default="", help="cuda / cpu (default cuda if available)")
+ ap.add_argument("--cam-map", default="", help="student camera=real camera, e.g. top=external,wrist=wrist")
+ ap.add_argument("--crop", default="", help="override crops: external=x,y,w,h;wrist=x,y,w,h")
+ ap.add_argument("--q-offset-deg", default="", help="extra joint-map offset, 5 sim deg (pan, lift, elbow, wrist_flex, "
+ "roll), added to calib offset_rad; e.g. 0,-2.086,0,0,0 = the table-tilt correction (README); flat "
+ "floor mode only (live refuses it in plane mode: the floor would move into the mat)")
+ ap.add_argument("--allow-calib-change", action="store_true",
+ help="live: accept a --calib whose sha256 differs from the student's pinned calibration")
+ ap.add_argument("--allow-crop-change", action="store_true",
+ help="accept a --crop that differs from the crops pinned in the student checkpoint")
+ ap.add_argument("--interp", default="area", choices=("area", "linear", "nearest", "cubic"))
+ ap.add_argument("--jaw-lead", type=int, default=None, help="default: the checkpoint's cfg.jaw_lead")
+ ap.add_argument("--amp", type=int, default=None, help="bf16 autocast 1 / 0 (default: cfg.amp on cuda)")
+ ap.add_argument("--qdot-window", type=int, default=3)
+ ap.add_argument("--qd-gain", type=float, default=1.0, help="the student's qdot INPUT x this gain (1 = off; real2sim "
+ "2026-10-22: the slow real arm makes the student's steps shrink; robot-like sim 50 %% at 1, 88 %% at 2)")
+ ap.add_argument("--floor-mode", default="auto", choices=("auto", "flat", "plane"),
+ help="table floor: flat = above sim z = --table-z (students trained on the sim table: C1, s28, "
+ "roll-cap students); plane = above --table-plane (default calib: the calibrated real mat), for "
+ "students trained with the v8 table randomisation (checkpoint v8_online.table_bias, p > 0); "
+ "auto = the student's (an explicit --table-plane = plane). Live refuses a mode other than the "
+ "student's, plane-mode floor stops deeper than 5 mm (command) / 8 mm (measured) below the plane, "
+ "a --table-plane c0,c1,c2 more than 1 mm below the calibrated plane, and --q-offset-deg in plane "
+ "mode")
+ ap.add_argument("--allow-floor-mismatch", action="store_true",
+ help="live: accept a floor mode other than the student's, deep plane-mode floor stops or a "
+ "--table-plane below the calibrated plane (not --q-offset-deg in plane mode)")
+ ap.add_argument("--table-z", type=float, default=0.0, help="flat floor: real table top z in the arm base frame (m)")
+ ap.add_argument("--table-plane", default="", help="plane floor: 'calib' (calib_v1 scene.table_plane, the measured "
+ "real table) or c0,c1,c2 (m; z = c0 + c1 x + c2 y; a value that starts with '-' needs the = form: "
+ "--table-plane=-0.0047,-0.0364,0.0184); the action-layer floor and the guard's floor checks then "
+ "measure above that plane (--floor-mode)")
+ ap.add_argument("--guard", default="", help="GuardConfig overrides as JSON")
+ ap.add_argument("--thumb-res", type=int, default=112, help="logged student input images (px; 0 = full)")
+ ap.add_argument("--out", default="", help="output folder (default ~/so101_hw_runs/_, as robot_test.sh)")
+ ap.add_argument("--lerobot-calib", default="", help="LeRobot calibration json for the joint limits (replay/fake)")
+ # replay
+ ap.add_argument("--data-root", default=str(DEFAULT_DATA_ROOT))
+ ap.add_argument("--episodes", default="green_cube_red_plate_1:0", help="dataset:episode,...")
+ ap.add_argument("--max-seconds", type=float, default=0.0, help="replay at most this long per episode (0 = all)")
+ # robot
+ ap.add_argument("--backend", default="lerobot", choices=("lerobot", "fake"))
+ ap.add_argument("--port", default=FOLLOWER_PORT)
+ ap.add_argument("--robot-id", default=ROBOT_ID)
+ ap.add_argument("--calibration-dir", default="", help="LeRobot calibration dir (default the HF cache)")
+ ap.add_argument("--cam-paths", default="", help='JSON {"wrist": path, "external": path} (default: the notes)')
+ ap.add_argument("--max-frame-age-ms", type=float, default=150.0)
+ ap.add_argument("--time-limit", type=float, default=15.0, help="student loop seconds")
+ ap.add_argument("--episodes-n", type=int, default=0, help="live: eval session of n episodes (result prompt, return "
+ "to HOME and scene reset between them; logs /ep_NN, summary /session.json); 0 = one run")
+ ap.add_argument("--home", default=",".join(f"{v:g}" for v in H.ROBOT_HOME_SIM_DEG),
+ help="HOME pose, 6 SIM degrees (default hw_lib.ROBOT_HOME_SIM_DEG: wrist roll 0)")
+ ap.add_argument("--home-speed-deg-s", type=float, default=15.0, help="peak joint speed of HOME / return moves")
+ ap.add_argument("--home-clearance", type=float, default=0.02, help="m above the table for HOME / return paths")
+ ap.add_argument("--configure", default="auto", choices=("auto", "always", "never"))
+ ap.add_argument("--i-am-supervising", action="store_true")
+ ap.add_argument("--auto-confirm", action="store_true", help="fake backend only: skip the typed confirmations")
+ args = ap.parse_args(argv)
+ if args.mode == "deploy-json":
+ if not args.out:
+ raise SystemExit("deploy-json needs --out /assets/deploy.json")
+ return run_deploy_json(args)
+ if not args.out:
+ args.out = str(Path("~/so101_hw_runs").expanduser() / f"{args.mode}_{time.strftime('%Y%m%d_%H%M%S')}")
+ if args.mode == "replay":
+ return run_replay(args)
+ return run_robot(args, live=args.mode == "live")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_policy/train_ppo.py b/so101_pick_place/code/scripts/so101_policy/train_ppo.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccc011c386c402eaa7d39bc9b650ce68092b56f5
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_policy/train_ppo.py
@@ -0,0 +1,366 @@
+"""PPO for the SO101 + cube goal pick-and-place policy in the grasp NRD (``--world nrd``; the study's kinematic and
+MuJoCo Warp worlds are not part of this release). Env: ``nedm.so101_policy.vec_env`` (decoder v2, task rules,
+observation, reward); algorithm: ``nedm.so101_policy.ppo`` (G1 PPO adapted).
+
+ PYTHONPATH=src python -P scripts/so101_policy/train_ppo.py train --world nrd --ckpt ~/so101_policy/ckpt/nrd_r1_s61.pt \
+ --out RUN [--env-cfg configs/so101_policy/ppo/env_v1.json] [--train-cfg configs/so101_policy/ppo/train_v1.json] \
+ [--curriculum configs/so101_policy/ppo/curriculum_tol_v1.json] [--num-envs 4096] [--seed 1] [--members split] \
+ [--max-world-steps 3e8] [--max-iterations N] [--max-hours 3.6] [--save-every 25] [--val-every 25] [--val-n 512] \
+ [--set key=json ...] [--resume] [--init-from CKPT]
+ PYTHONPATH=src python -P scripts/so101_policy/train_ppo.py bank --data ~/so101_nrd_fix/data/production_plus --split 0 \
+ --out bank_pp_s0.npz # the data start bank as a small .npz (AMD, other machines)
+ PYTHONPATH=src python -P scripts/so101_policy/train_ppo.py starts --out starts_fresh.npz --seed0 200000 --n 4096
+ # fresh collector starts (CPU MuJoCo sample_starts), a start bank
+
+--set: "env.=json" changes the env config (vec_env.EnvConfig; e.g. env.task='{"tol_xy": 0.03}'), anything else the
+train config (ppo.train_cfg_default layout; e.g. num_steps_per_env=24 algorithm.entropy_coef=0.003). PPO's gamma is
+also the env's gamma (the task's failure charge discount).
+
+Checkpoints (spec_v2 B4: MuJoCo is not in the training loop of an NRD arm): every ``--save-every`` iterations
+``ckpt/model_.pt`` is kept (all of them), plus the final one at the budget = the primary checkpoint ("last at
+budget"); ``last.pt`` (+ ``state.json``) is the resume point. Validation in the TRAINING world (deterministic policy,
+``--val-n`` fixed tasks drawn from the start bank with ``--val-seed``, decoder seeds 10,000,000 + i) every
+``--val-every`` iterations -> ``val_history.json``: the curriculum's promotion signal and the "training-world
+validation selected" second row. Budget: ``--max-world-steps`` (20 ms world steps of the training envs), else
+iterations / hours (this job's wall clock); a resumed run continues the counters.
+
+Curriculum JSON (tolerance ladder, review P1-13; optional): {"stages": [{"name", "task": {tol_xy, tol_yaw (m, rad;
+a key left out = the env config's value)}, "grasp_assist": bool (vec_env docstring), "grasp_assist_cost",
+"val_assist": bool (validation with the assist; default = grasp_assist, so an assisted stage is promoted on assisted
+validations; val_history.json marks them "assisted": a training-world-selected checkpoint must come from an
+unassisted validation), "promote": validation success to move on (absent = last stage), "min_iters", "max_iters",
+"std_reset": bool (raise the std to at least train_cfg std_reset at the promotion, default true)}, ...]}.
+
+Outputs in --out: env_cfg.json, train_cfg.json, curriculum.json, env_resolved.json (the env config with the resolved
+TaskConfig and DecoderV2Config, every field; review R1 / R6), manifest.json (argv, git HEAD, the dirty files with their
+sha256, sha256 of every so101_policy source / script / config file, of the NRD checkpoints and the start bank, the
+resolved configs, torch, GPU), learning_curve.csv (one row per iteration; world_steps = 20 ms steps of
+all training envs, gt_transitions = MuJoCo Warp steps incl. validation (0 in the NRD and kinematic worlds), wall_s =
+training wall clock summed over jobs), val_history.json, ckpt/model_.pt, last.pt, state.json, done.json /
+paused.json, train.log (stdout copy when run with tee).
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import socket
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from nedm.so101_policy import task as T
+from nedm.so101_policy.ppo import (PPO, CurveWriter, Policy, action_bias_for, group_values, merge, sha256,
+ train_cfg_default, write_json)
+from nedm.so101_policy.vec_env import (EnvConfig, PickPlaceVecEnv, policy_act_fn, reserved_seed_hits, run_episodes,
+ start_rows)
+
+ROOT = Path(__file__).resolve().parents[2]
+VAL_SEED0 = 10_000_000 # decoder macro seeds of the validation tasks
+FRESH_SEED0 = 200_000 # default first seed of fresh training starts (never 1000-2023 or >= 900000)
+
+
+def apply_set(tc, ec, items):
+ """--set key=json: "env." into the env config, anything else into the train config."""
+ for kv in items or []:
+ k, v = kv.split("=", 1)
+ node, ks = tc, k.split(".")
+ if ks[0] == "env":
+ node, ks = ec, ks[1:]
+ for kk in ks[:-1]:
+ node = node.setdefault(kk, {})
+ node[ks[-1]] = json.loads(v)
+
+
+CODE_GLOBS = ("src/nedm/so101_policy/*.py", "scripts/so101_policy/*.py", "configs/so101_policy/ppo/*.json")
+
+
+def code_hashes() -> dict:
+ """sha256 (first 16 hex) of every so101_policy source, script and PPO config file (review R6)."""
+ return {str(f.relative_to(ROOT)): sha256(f)[:16] for g in CODE_GLOBS for f in sorted(ROOT.glob(g))}
+
+
+def git_state():
+ try:
+ head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
+ dirty = subprocess.run(["git", "status", "--porcelain"], cwd=ROOT, capture_output=True, text=True).stdout
+ files = [ln[3:] for ln in dirty.splitlines()][:200]
+ return dict(head=head, dirty_files=files,
+ dirty_sha256={f: sha256(ROOT / f) for f in files if (ROOT / f).is_file()})
+ except OSError:
+ return {}
+
+
+def val_tasks(env: PickPlaceVecEnv, n, seed):
+ """n fixed validation tasks from the env's start bank (CPU generator seeded ``seed``): (starts WorldState,
+ goal_xy, goal_yaw, decoder seeds)."""
+ bank = {k: v.cpu() for k, v in env.bank.items()}
+ gen = torch.Generator().manual_seed(int(seed))
+ i, gxy, gyaw = T.make_tasks(bank, n, gen)
+ return start_rows(bank, i), gxy, gyaw, torch.arange(VAL_SEED0, VAL_SEED0 + n, dtype=torch.long)
+
+
+def summarise(r, tol_xy, tol_yaw):
+ """Per-episode dict of run_episodes -> summary (success at the env's tolerance and at 15 / 10)."""
+ s, n = r["success"], len(r["success"])
+ ok15 = s & (r["end_xy"] <= 0.015 + 1e-12) & (r["end_yaw"] <= math.radians(15) + 1e-12)
+ ends = {T.ENDS[k]: int(v) for k, v in zip(*np.unique(r["end"], return_counts=True))}
+ return dict(n=n, success=float(s.mean()), success15=float(ok15.mean()), success10=float(r["success10"].mean()),
+ lifted=float(r["lifted"].mean()), tol_xy=tol_xy, tol_yaw=tol_yaw, ends=ends,
+ ep_return=float(r["ret"].mean()), ep_length=float(r["length"].mean()),
+ end_xy_mm_success=dict(p50=float(np.median(r["end_xy"][s]) * 1e3), p95=float(np.percentile(r["end_xy"][s], 95) * 1e3))
+ if s.any() else None)
+
+
+def cmd_train(a):
+ out = Path(a.out).expanduser()
+ resume = a.resume and (out / "state.json").exists()
+ if resume:
+ ec = json.loads((out / "env_cfg.json").read_text())
+ tc = json.loads((out / "train_cfg.json").read_text())
+ cur = json.loads((out / "curriculum.json").read_text())
+ state = json.loads((out / "state.json").read_text())
+ else:
+ ec = EnvConfig().to_dict()
+ if a.env_cfg:
+ merge(ec, {k: v for k, v in json.loads(Path(a.env_cfg).read_text()).items() if k not in ("note", "notes")})
+ tc = train_cfg_default(a.seed)
+ if a.train_cfg:
+ merge(tc, {k: v for k, v in json.loads(Path(a.train_cfg).read_text()).items() if k not in ("note", "notes")})
+ ec.update(world=a.world, num_envs=a.num_envs, device=a.device, seed=a.seed)
+ if a.ckpt:
+ ec["ckpts"] = [str(Path(p).expanduser()) for p in a.ckpt]
+ if a.members:
+ ec["members"] = a.members if len(a.members) > 1 else a.members[0]
+ if a.starts:
+ ec["starts"] = str(Path(a.starts).expanduser())
+ tc["seed"] = a.seed
+ apply_set(tc, ec, a.set)
+ ec["gamma"] = tc["algorithm"]["gamma"]
+ cur = json.loads(Path(a.curriculum).read_text()) if a.curriculum else {"stages": [{"name": "single"}]}
+ state = dict(stage=0, stage_start=0, history=[], val_world_steps=0, jobs=[])
+ EnvConfig.from_dict(ec) # unknown keys raise before anything runs
+ stages = cur["stages"]
+ if a.init_from and not resume and not Path(a.init_from).is_file():
+ raise FileNotFoundError(a.init_from)
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "ckpt").mkdir(exist_ok=True)
+ if not resume:
+ if (out / "state.json").exists():
+ raise FileExistsError(f"{out} holds a run; use --resume or a new --out")
+ write_json(out / "env_cfg.json", ec)
+ write_json(out / "train_cfg.json", tc)
+ write_json(out / "curriculum.json", cur)
+ torch.manual_seed(int(tc["seed"]))
+ np.random.seed(int(tc["seed"]))
+ t_job = time.time()
+ env = PickPlaceVecEnv(EnvConfig.from_dict(ec))
+ val_env = PickPlaceVecEnv(EnvConfig.from_dict(dict(ec, num_envs=a.val_n, auto_reset=False, obs_rate_noise=(0.0, 0.0))),
+ share=env)
+ code = code_hashes()
+ if not resume:
+ sp = Path(ec["starts"]).expanduser()
+ write_json(out / "env_resolved.json", env.resolved())
+ man = dict(argv=sys.argv, git=git_state(), code_sha256=code, host=socket.gethostname(), torch=torch.__version__,
+ gpu=torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,
+ ckpts={p: sha256(p) for p in ec["ckpts"]} if ec["world"] == "nrd" else {},
+ starts=dict(path=str(sp), sha256=sha256(sp) if sp.is_file() else
+ (sha256(sp / "manifest.json") if (sp / "manifest.json").exists() else None),
+ split=ec["start_split"]),
+ resolved=env.resolved(),
+ method="PPO (ppo.py) on vec_env.PickPlaceVecEnv: decoder v2 actions, task.PickPlaceTask rules / reward",
+ init_from=dict(path=a.init_from, sha256=sha256(a.init_from)) if a.init_from else None)
+ write_json(out / "manifest.json", man)
+ elif (out / "env_resolved.json").exists(): # a resumed run must rebuild the same env
+ old = json.loads((out / "env_resolved.json").read_text())
+ new = json.loads(json.dumps(env.resolved(), default=lambda o: o.tolist() if hasattr(o, "tolist") else str(o)))
+ if {k: old[k] for k in ("task", "decoder")} != {k: new[k] for k in ("task", "decoder")}:
+ raise RuntimeError("resume: the resolved task / decoder config differs from env_resolved.json (code changed)")
+ vt = val_tasks(env, a.val_n, a.val_seed)
+ pk = dict(tc["policy"])
+ groups = env.action_groups
+ pk["action_bias"] = action_bias_for(pk.get("action_bias"), env.num_actions)
+ if tc.get("hold_std"): # second std vector in decoder mode hold (ppo module docstring)
+ pk.update(ctx_index=env.hold_obs_index, ctx_init_std=group_values(tc["hold_std"]["init"], groups, "init_std"))
+ pol = Policy(env.num_obs, env.num_actions, groups, init_std=group_values(tc["init_std"], groups, "init_std"),
+ **pk).to(env.dev)
+ ppo = PPO(env, pol, tc)
+ gt_world = ec["world"] in ("mjwarp", "mujoco")
+ if resume:
+ ppo.load(out / "last.pt")
+ print(f"[resume] {out / 'last.pt'} at iteration {ppo.iteration}, stage {state['stage']}, "
+ f"{ppo.world_steps / 1e6:.1f} M world steps", flush=True)
+ elif a.init_from:
+ d = torch.load(a.init_from, map_location=env.dev, weights_only=False)
+ pol.load_state_dict(d["policy"])
+ ppo.clamp_std()
+ print(f"[init] weights from {a.init_from}", flush=True)
+ state["jobs"].append(dict(start=time.strftime("%Y-%m-%d %H:%M:%S"), argv=sys.argv, iteration=ppo.iteration,
+ host=socket.gethostname()))
+
+ base_tol = (ec["task"].get("tol_xy", T.TaskConfig().tol_xy), ec["task"].get("tol_yaw", T.TaskConfig().tol_yaw))
+
+ def apply_stage(k):
+ over = stages[k].get("task", {})
+ bad = sorted(set(over) - {"tol_xy", "tol_yaw"})
+ if bad:
+ raise ValueError(f"curriculum stage {k}: only tol_xy / tol_yaw can change during a run ({bad})")
+ for e in (env, val_env):
+ e.set_tolerance(over.get("tol_xy", base_tol[0]), over.get("tol_yaw", base_tol[1]))
+ # the grasp assist (vec_env docstring) is a training aid; validation uses it only where the stage says so
+ # ("val_assist", default = the stage's grasp_assist: the promotion signal of an assisted stage)
+ on = bool(stages[k].get("grasp_assist", ec.get("grasp_assist", False)))
+ env.set_grasp_assist(on, stages[k].get("grasp_assist_cost"))
+ val_env.set_grasp_assist(bool(stages[k].get("val_assist", on)), stages[k].get("grasp_assist_cost"))
+
+ apply_stage(state["stage"])
+ curve = CurveWriter(out / "learning_curve.csv")
+ print(f"[env] world {ec['world']}, {env.num_envs} envs, obs {env.num_obs}, actions {env.num_actions}, starts "
+ f"{env.bank['q'].shape[0]} ({ec['starts']}), tol {env.tcfg.tol_xy * 1e3:.0f} mm / "
+ f"{math.degrees(env.tcfg.tol_yaw):.0f} deg, setup {time.time() - t_job:.1f} s", flush=True)
+
+ def validate():
+ t0 = time.time()
+ r = run_episodes(val_env, policy_act_fn(pol), *vt)
+ val_env.world_steps = 0
+ steps = int(r["steps"].sum())
+ state["val_world_steps"] += steps
+ sm = summarise(r, env.tcfg.tol_xy, env.tcfg.tol_yaw)
+ sm.update(iteration=ppo.iteration, stage=state["stage"], stage_name=stages[state["stage"]].get("name"),
+ assisted=bool(val_env.cfg.grasp_assist), world_steps=ppo.world_steps, val_s=time.time() - t0,
+ val_world_steps=steps,
+ std=[float(x) for x in pol.std.detach().cpu()])
+ state["history"].append(sm)
+ write_json(out / "val_history.json", state["history"])
+ print(f"[val] it {ppo.iteration} stage {state['stage']} success {sm['success']:.3f} (15/15 {sm['success15']:.3f},"
+ f" 10/10 {sm['success10']:.3f}) lifted {sm['lifted']:.3f} return {sm['ep_return']:.2f} ends {sm['ends']} "
+ f"| {sm['val_s']:.1f} s", flush=True)
+ return sm
+
+ def save_state():
+ ppo.save(out / "last.pt", extra=dict(stage=state["stage"], code_sha256=code))
+ write_json(out / "state.json", state)
+
+ def budget_left():
+ if a.max_world_steps and ppo.world_steps >= a.max_world_steps:
+ return False
+ if a.max_iterations and ppo.iteration - it0 >= a.max_iterations:
+ return False
+ return time.time() - t_job < a.max_hours * 3600
+
+ it0 = ppo.iteration
+ if not resume and not a.no_initial_val:
+ validate()
+ while budget_left():
+ row = ppo.iterate()
+ k = state["stage"]
+ row.update(stage=k, tol_xy_mm=env.tcfg.tol_xy * 1e3, tol_yaw_deg=math.degrees(env.tcfg.tol_yaw),
+ gt_transitions=(ppo.world_steps + state["val_world_steps"]) if gt_world else 0,
+ val_world_steps=state["val_world_steps"])
+ curve.write(row)
+ if ppo.iteration % a.print_every == 0 or ppo.iteration == it0 + 1:
+ print(f"[train] it {ppo.iteration} {ppo.world_steps / 1e6:.1f} M steps, {row['world_steps_per_s']:.0f} "
+ f"steps/s (collect), {row['world_steps_per_s_total']:.0f} with update | reward/dec "
+ f"{row['reward_per_decision']:.4f} return {row['ep_return']:.2f} success {row['success']:.3f} lifted "
+ f"{row['lifted']:.3f} len {row['ep_length']:.1f} grasps/ep {row['grasp_starts_per_episode']:.2f} | kl "
+ f"{row['kl']:.4f} lr {row['lr']:.1e} std {row['std_move']:.2f}/{row['std_trigger']:.2f}/"
+ f"{row['std_lift']:.2f}{' hold ' + format(row['std_hold_move'], '.2f') if 'std_hold_move' in row else ''} | mem "
+ f"{row.get('gpu_mem_gb', 0):.1f} GB", flush=True)
+ if a.pool_refresh and ppo.iteration % a.pool_refresh == 0:
+ env.refresh_pool()
+ if ppo.iteration % a.save_every == 0:
+ ppo.save(out / "ckpt" / f"model_{ppo.iteration:05d}.pt", extra=dict(stage=k, world_steps=ppo.world_steps,
+ code_sha256=code))
+ if ppo.iteration % a.val_every == 0:
+ sm = validate()
+ s = stages[k]
+ in_stage = ppo.iteration - state["stage_start"]
+ ok = "promote" in s and sm["success"] >= s["promote"]
+ if k + 1 < len(stages) and ((ok and in_stage >= s.get("min_iters", 0)) or in_stage >= s.get("max_iters", 10 ** 9)):
+ reason = "promoted" if ok else "max_iters"
+ ppo.save(out / "ckpt" / f"stage{k}_end_{ppo.iteration:05d}.pt", extra=dict(stage=k, code_sha256=code))
+ state.setdefault("stage_ends", []).append(dict(stage=k, iteration=ppo.iteration, reason=reason,
+ success=sm["success"], world_steps=ppo.world_steps))
+ state["stage"], state["stage_start"] = k + 1, ppo.iteration
+ apply_stage(k + 1)
+ if stages[k + 1].get("std_reset", True):
+ ppo.set_std(tc["std_reset"], at_least=True)
+ print(f"[curriculum] stage {k} -> {k + 1} ({stages[k + 1].get('name')}) at it {ppo.iteration}: {reason}; "
+ f"tol {env.tcfg.tol_xy * 1e3:.0f} mm / {math.degrees(env.tcfg.tol_yaw):.0f} deg", flush=True)
+ save_state()
+ final = out / "ckpt" / f"model_{ppo.iteration:05d}.pt"
+ if not final.exists():
+ ppo.save(final, extra=dict(stage=state["stage"], world_steps=ppo.world_steps, code_sha256=code))
+ save_state()
+ budget_done = bool(a.max_world_steps) and ppo.world_steps >= a.max_world_steps
+ summary = dict(iteration=ppo.iteration, world_steps=ppo.world_steps, decisions=ppo.decisions,
+ gt_transitions=(ppo.world_steps + state["val_world_steps"]) if gt_world else 0,
+ wall_s=ppo.wall, job_s=time.time() - t_job, final_checkpoint=str(final), stage=state["stage"],
+ last_val=state["history"][-1] if state["history"] else None)
+ write_json(out / ("done.json" if budget_done or not a.max_world_steps else "paused.json"), summary)
+ print(f"[done] {json.dumps({k: v for k, v in summary.items() if k != 'last_val'})}", flush=True)
+ env.close()
+ val_env.close()
+
+
+def cmd_bank(a):
+ b = T.load_start_bank(Path(a.data).expanduser(), split=a.split)
+ out = {k: v.numpy() for k, v in b.items()}
+ np.savez(a.out, source=np.array(str(a.data)), split=np.int64(a.split), **out)
+ print(f"{len(out['q'])} starts (task families, split {a.split}) of {a.data} -> {a.out}")
+
+
+def cmd_starts(a):
+ from nedm.so101_policy.mujoco_env import sample_starts
+ seeds = np.arange(a.seed0, a.seed0 + a.n)
+ if reserved_seed_hits(seeds):
+ raise ValueError("seeds 1000-2023 (gate), 400000-499999 (gate2) and 900000+ (test) are not training starts")
+ t0 = time.time()
+ st = sample_starts(seeds)
+ s = st["state"]
+ np.savez(a.out, seed=seeds, start_q=st["q"], start_cube_pos=st["cube_pos"], start_cube_quat=st["cube_quat"],
+ tries=st["tries"], **{k: getattr(s, k).numpy() for k in ("q", "qd", "cube_pos", "cube_quat", "cube_v", "cube_w")})
+ print(f"{a.n} fresh starts (seeds {seeds[0]}-{seeds[-1]}) -> {a.out} in {time.time() - t0:.0f} s")
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ p = sub.add_parser("train")
+ p.add_argument("--world", choices=("nrd",), default="nrd")
+ p.add_argument("--ckpt", nargs="*", help="NRD checkpoint(s)")
+ p.add_argument("--members", nargs="*", help="GraspNrdSim members (default split)")
+ p.add_argument("--starts", help="start bank: data dir or .npz (default: production_plus split 0)")
+ p.add_argument("--env-cfg"), p.add_argument("--train-cfg"), p.add_argument("--curriculum")
+ p.add_argument("--out", required=True), p.add_argument("--seed", type=int, default=1)
+ p.add_argument("--num-envs", type=int, default=4096), p.add_argument("--device", default="cuda")
+ p.add_argument("--set", nargs="*", action="extend"), p.add_argument("--resume", action="store_true")
+ p.add_argument("--init-from", help="new run only: policy weights (and normaliser) of this checkpoint")
+ p.add_argument("--max-world-steps", type=float, default=0, help="budget in 20 ms world steps (0: none)")
+ p.add_argument("--max-iterations", type=int, default=0), p.add_argument("--max-hours", type=float, default=3.6)
+ p.add_argument("--save-every", type=int, default=25), p.add_argument("--val-every", type=int, default=25)
+ p.add_argument("--val-n", type=int, default=512), p.add_argument("--val-seed", type=int, default=20261211)
+ p.add_argument("--pool-refresh", type=int, default=50, help="new task pool every N iterations (0: never)")
+ p.add_argument("--print-every", type=int, default=1), p.add_argument("--no-initial-val", action="store_true")
+ p.add_argument("--threads", type=int, default=0)
+ p = sub.add_parser("bank")
+ p.add_argument("--data", required=True), p.add_argument("--split", type=int, default=0), p.add_argument("--out", required=True)
+ p = sub.add_parser("starts")
+ p.add_argument("--out", required=True), p.add_argument("--seed0", type=int, default=FRESH_SEED0)
+ p.add_argument("--n", type=int, default=4096)
+ a = ap.parse_args()
+ if getattr(a, "threads", 0):
+ torch.set_num_threads(a.threads)
+ if a.cmd == "train":
+ a.max_world_steps = int(a.max_world_steps)
+ if a.world == "nrd" and not a.ckpt and not a.resume:
+ ap.error("--world nrd needs --ckpt")
+ globals()[f"cmd_{a.cmd}"](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/scripts/so101_policy/vision_viral.py b/so101_pick_place/code/scripts/so101_policy/vision_viral.py
new file mode 100644
index 0000000000000000000000000000000000000000..206bdc3d519a9aebe38bdf345315ba115cd5b4f4
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_policy/vision_viral.py
@@ -0,0 +1,879 @@
+"""VIRAL / DoorMan-style camera student of build9 (``nedm.so101_policy.vision.viral``; docs
+~/so101_policy/docs/build9_viral_student.md). The teacher is the Markov joint teacher (``vision_viral_teacher.py``).
+
+ export PYTHONPATH=src PY=~/miniconda3/envs/so101_vision/bin/python
+ $PY -P scripts/so101_policy/vision_viral.py run --out RUN --jt JT.pt --tasks train.npz --eval-tasks dev100.npz \
+ --config configs/so101_policy/vision/viral_v1.json --r0-tasks 2048 --rounds 4 --round-tasks 1024 \
+ --teacher-share 0.5
+ $PY -P scripts/so101_policy/vision_viral.py eval --student RUN/r4/last.pt --jt JT.pt --tasks dev100.npz \
+ --world mujoco [--randomise] [--record-states] --out e.npz
+ $PY -P scripts/so101_policy/vision_viral.py collect --jt JT.pt --tasks t.npz --world nrd --out d.npz [--student S]
+
+``run`` (VIRAL's mixing per WHOLE episode, never inside one): round 0 = JT-driven episodes (``--r0-noise-frac`` of them
+with noise ``--noise`` x the JT's PPO std on its normalised action); round i >= 1 = ``--round-tasks`` new tasks, the
+share ``--teacher-share`` JT-driven (the same noise mix), the rest driven by the previous round's student with
+randomised visuals (``--collect-randomise``); every visited decision labelled by the JT. After each round: train
+(round 0 from ImageNet, later rounds fine-tune on the aggregate), evaluate on the development tasks in CPU MuJoCo (and
+``--eval-worlds``), nominal visuals (+ randomised with ``--eval-randomise``). Files resume.
+
+Real2sim (``~/so101_r2s_claude/docs/integrate.md``): a config with ``scene`` renders the real scene (``viral.make_views``;
+the scene / calibration sha256 are pinned in the student config at the start of ``run`` and checked later:
+``--allow-scene-change``); a config with image lag (``lag``, ``lag_range``) records the 20 ms states in the round files
+(``row_lag``) and renders the lagged state everywhere (training, the online loop, the evaluations; ``eval --lag K``
+overrides the nominal lag). ``--eval-tasks`` takes several files (the first one keeps the old output names; the others
+add their file stem).
+
+Robot timing and servo (``joint_env.RobotDynConfig``, all off by default): training = the online config's ``dyn`` (per
+world per episode; with ``qd_robot_p``, ``horizon``, ``hold_cap_s``, ``qd_noise_zero_p``, ``lag_range``,
+``viral_r2s_online_dyn_v1.json``); evaluation / collection = one fixed setting for the process in
+``NEDM_SO101_DYN='{"d": 2, "jitter": 0.4, "s": 0.5, "tau": 0.1, "sag_deg": 1.5, "i_time_s": 0.2}'`` (recorded as
+"dyn" in eval files, "robot" + ``dyn_params`` in round files), with ``--horizon 1500 --hold-cap-s 20`` for slow worlds
+and ``eval --qd-robot 3`` for the robot's qdot estimate (``row_qd_input``: the student's qdot input). jt_h110 scores
+0 % in that robot-like setting (NRD and MuJoCo); settings with a teacher reference: the config note.
+
+Last-command input (``ViralConfig.lastcmd``, off by default): ``online --config viral_r2s_v1_lastcmd.json`` adds it to
+a student without it (zero weights: the initial student's actions at the start); ``eval`` / ``collect`` feed it from
+the env's executed targets; ``run`` (round files) refuses it.
+
+Studentlab (2026-10-22, ~/so101_studentlab_claude/trials/BUILD.md): ``online`` expands the loaded student when the
+config adds inputs (``hist``, ``cmd_in``, ``img_hist``: ``viral.expand_student``, zero-init) and takes
+``goal_jump`` / ``hold_cap_s`` in the online config (arms: ``configs/so101_policy/vision/studentlab/``,
+``cluster/studentlab_online.sbatch``); ``eval --goal-shift 'p=1,d=10:25,lat=8'`` is the evaluation-only goal shift
+(the overshoot gate: once per episode, same trigger as the training jumps, the cube ends PAST the moved goal; the
+summary adds ``goal_shift`` with the shifted / unshifted episodes). The online config's ``light_redraw_p`` (< 1: the
+per-call light and intrinsics stay for several decisions; the image-history arm A4) also applies to the in-run
+evaluations; ``eval --light-redraw-p P`` is the same for a standalone evaluation (with ``--randomise``).
+
+Wrist-roll cap (real2sim 2026-10-23, off by default; ``joint_env.JointEnvConfig.roll_hi_deg``): the real wrist roll
+ends at +101.2 sim deg (the guard's clamp; the servo reaches only ~100.7 there, so round v8 uses 98). ``online``: the
+online config's ``roll_hi_deg`` caps the online env's targets and the JT's labels, drops the task rows that start
+above it, and applies to the in-run evaluations (``--roll-hi-deg`` overrides the evaluations only); the labelling JT
+must have been trained with that cap or a lower one (its checkpoint's env record; else the run stops,
+``--allow-uncapped-jt`` accepts it). ``eval`` / ``collect`` / ``run``: ``--roll-hi-deg 98``. The summaries then add
+``roll_cmd_over`` (share of episodes whose commanded roll went above the cap), ``roll_q_at_cap`` and
+``roll_cmd_max_deg``.
+Table randomisation (real2sim v8, off by default; ``nedm.so101_policy.table_bias``): the online config's
+``table_bias`` puts a per-world table plane under the student's joint reading (q, qdot, cmd inputs, labels and applied
+targets in that frame), ``table_render`` draws the training images consistently (the arm at the reading, the world
+on the plane), ``plate_mm`` randomises the goal plate thickness of the TRAINING views only
+(``viral.online_views_cfg``; the evaluation views and the saved student config keep the scene's plate); configs
+``viral_r2s_online_v8_C_table.json`` / ``viral_r2s_online_v8_S_table.json``. The gate (pass rule in its docstring) is
+``scripts/so101_policy/real2sim/lowtable_gate.py`` (``eval --table-plane`` / ``--floor table``: the physical table
+moved in CPU MuJoCo); robot deploy with ``run_student_real.py --table-plane calib``.
+Table drop with the flat floor (real2sim v12, off by default): the online config's ``table_bias`` {"plane": [c0, c1,
+c2]} puts ONE fixed plane under every world (no draw) and ``student_floor`` "observed" keeps the online env's floor
+flat in the student's observed frame (the robot's flat arm-frame floor; the true-frame floor raised by -plane,
+``joint_env.JointEnvConfig.floor_raise``); the labelling JT must have been fine-tuned with that floor raise
+(``check_jt_floor``: the run stops otherwise, ``--allow-floor-raise-mismatch``; teacher configs
+``configs/so101_policy/ppo/r2s/teacher_roll_v12_*.json``); ``--eval-table-plane`` runs the in-run MuJoCo evaluations on
+that plane (table moved, floor 'zero' = flat in the arm frame, renders on the plane). A run with ``student_floor``
+"observed" turns it on by default and takes the evaluations' episode length and hold cap from the online config
+(``inrun_eval_setup``; ``--no-eval-table-plane`` / ``--horizon`` / ``--hold-cap-s`` override). The checkpoint records
+``v8_online.student_floor`` and the robot deploys it with the flat floor (``hw_lib.student_floor_mode``). ``eval`` /
+``collect --floor-raise`` = the raise in the TRUE frame (the student reads the true joints).
+Gripper look (real2sim v12 visual fix, off by default; ``nedm.render.gripper_look``): the online config's
+``gripper_look`` randomises the look of the gripper parts in the wrist view of the TRAINING renders (plate and servo
+bracket albedo, the scene's fitted screws, extra marks, plate top edge; ``viral.online_views_cfg``) and
+``require_scene_sha256`` refuses a student whose scene file is another one; configs ``viral_r2s_online_v12_visR.json``
+(student config ``viral_r2s_v12_visR_student.json``: the fitted real-look scene real_scene_v2_wb.json, sha256 pinned)
+and ``viral_r2s_online_v12_visH.json`` (D's scene v2, held-out cues excluded); ``viral_r2s_online_v12_visR_tbpl.json``
+= visR + tbpl's table keys (frpl teacher). The checkpoint records ``v12_vis``.
+"""
+from __future__ import annotations
+
+import argparse
+import contextlib
+import json
+import sys
+import time
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from nedm.so101_policy import joint_env as JE
+from nedm.so101_policy import joint_teacher as JT
+from nedm.so101_policy.paths import DATA
+from nedm.so101_policy.vision import viral as VI
+
+NRD = str(DATA / "nrd" / "c1_s62" / "best.pt") # the policy NRD (main-compatible file; README)
+MJ_PY = sys.executable # Python of the CPU MuJoCo worker processes
+GUARD = str(DATA / "rl_inputs" / "tasks" / "fresh100.npz")
+
+
+def log(s):
+ print(f"[{time.strftime('%H:%M:%S')}] {s}", flush=True)
+
+
+def x(p):
+ return str(Path(p).expanduser()) if p else p
+
+
+def progress(out, **kw):
+ with open(Path(out) / "progress.jsonl", "a") as f:
+ f.write(json.dumps(dict(time=time.strftime("%Y-%m-%d %H:%M:%S"), **kw), default=float) + "\n")
+
+
+def load_tasks(path, idx=None):
+ from nedm.so101_policy.vision.demos import load_tasks as lt
+ return lt(path, idx)
+
+
+def subset(t, idx):
+ n = len(t["seeds"])
+ return {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in t.items()}
+
+
+class EnvCache:
+ def __init__(self, jt, device, nrd, workers, mj_python, horizon, table=None, cli=None, hold_cap_s=None,
+ goal_jump=None, roll_hi_deg=None, floor_raise=None):
+ self.c, self.jt, self.dev, self.nrd, self.w, self.mp, self.h = {}, jt, device, nrd, workers, mj_python, horizon
+ self.table = table # (plane, floor, q_offset) for JointVecEnv.set_table (evaluation only), None: off
+ self.cli = cli # eval args (``--log-only-extra``), None: off
+ self.hold_cap_s = hold_cap_s # the hold_cap rule (s; ``--hold-cap-s``), None: the task default
+ self.goal_jump = goal_jump # JE.GoalJumpConfig: the evaluation-only goal shift (``--goal-shift``), None: off
+ self.roll_hi_deg = roll_hi_deg # the wrist-roll target cap (sim deg; ``--roll-hi-deg``), None: off
+ self.floor_raise = floor_raise # the action-layer floor raise (``--floor-raise``; JointEnvConfig), None: off
+
+ def get(self, world, B):
+ k = (world, B)
+ if k not in self.c:
+ self.c[k] = JT.make_env(world, B, self.jt.codec, self.dev, self.nrd, self.w, self.mp, self.h,
+ hold_cap_s=self.hold_cap_s, goal_jump=self.goal_jump, roll_hi_deg=self.roll_hi_deg,
+ floor_raise=self.floor_raise)
+ if self.c[k].roll_hi is not None:
+ log(f"roll cap ({world}, {B} worlds): {json.dumps(self.c[k].roll_info())}")
+ if self.c[k].cfg.floor_raise is not None:
+ log(f"floor raise ({world}, {B} worlds): the floor 1.5 mm above z = {list(self.c[k].cfg.floor_raise)} "
+ "(c0 + c1 x + c2 y at the grasp point; the student reads the true joints)")
+ if self.c[k].goal_jump is not None:
+ log(f"goal shift ({world}, {B} worlds): {json.dumps(VI.asdict(self.c[k].goal_jump.cfg))}")
+ if self.c[k].dyn is not None: # $NEDM_SO101_DYN (joint_teacher.make_env)
+ log(f"robot dynamics ({world}, {B} worlds): {json.dumps(VI.asdict(self.c[k].dyn.cfg))}")
+ if self.table is not None:
+ log(f"table: {json.dumps(self.c[k].set_table(*self.table))}")
+ if self.cli is not None:
+ from nedm.so101_policy import table as TB
+ if TB.log_only_extra(self.c[k], self.cli):
+ log(f"log-only task rules: {self.c[k].tcfg.log_only}")
+ return self.c[k]
+
+
+def taps(env, *fns):
+ """``viral.step_tap`` with the given 20 ms state callbacks (none: a no-op context)."""
+ fns = [f for f in fns if f is not None]
+ return VI.step_tap(env, *fns) if fns else contextlib.nullcontext()
+
+
+def robot_rec(env):
+ """The env's robot setting for output files (JSON string): the robot dynamics config (``RobotDynConfig``; the
+ per-world draws are separate), the hold cap / held-time scale and ``$NEDM_SO101_EVAL_KP_SCALE``; None = all
+ defaults (the old env)."""
+ roll = getattr(env, "roll_hi", None) is not None
+ if env.dyn is None and env.tcfg.hold_cap_s == JE.T.TaskConfig.hold_cap_s and not env.cfg.hold_obs_s \
+ and JE.EVAL_KP_SCALE == 1.0 and not roll:
+ return None
+ d = dict(cfg=VI.asdict(env.dyn.cfg) if env.dyn is not None else None, cols=list(JE.RobotDyn.COLS),
+ hold_cap_s=env.tcfg.hold_cap_s, hold_obs_s=float(env.cfg.hold_obs_s), kp_scale=JE.EVAL_KP_SCALE)
+ if roll: # the wrist-roll cap (no key while it is off: the old records)
+ d["roll_hi_deg"] = float(env.cfg.roll_hi_deg)
+ return json.dumps(d)
+
+
+@torch.no_grad()
+def collect(tasks, world, jt, cache: EnvCache, src, noise, seed, batch, student=None, log=log, lag_rec=False,
+ lag_kmax=0):
+ """Episodes on all tasks in batches -> concatenated record dict (``run_tasks`` layout); ``lag_rec``: also the
+ states of the last max(``viral.LAG_REC``, ``lag_kmax``) control steps before every row (``row_lag``, image
+ lag). Robot dynamics (``$NEDM_SO101_DYN``): per-episode draws ``dyn_params`` (``RobotDyn.COLS``) and the setting
+ "robot" (``robot_rec``)."""
+ n = len(tasks["seeds"])
+ parts, t0, rec = [], time.time(), None
+ for s0 in range(0, n, batch):
+ idx = np.arange(s0, min(n, s0 + batch))
+ env = cache.get(world, len(idx))
+ if student is not None:
+ student.bind(env) # cmd_in and the last-command input (ViralConfig.lastcmd): the env's u_exe
+ sl = VI.SubstepLog() if lag_rec else None
+ push = student.push if student is not None and student.needs_tap else None
+ with taps(env, sl, push):
+ r = JT.run_tasks(env, subset(tasks, idx), jt, student, src[idx], noise[idx], seed, record=True)
+ if env.dyn is not None:
+ r["dyn_params"] = env.dyn.params().cpu().numpy().astype(np.float32)
+ rec = robot_rec(env)
+ if sl is not None:
+ r["row_lag"] = VI.lag_rows(r, sl.array(), max(VI.LAG_REC, int(lag_kmax)))
+ parts.append(r)
+ s = np.asarray(r["src"]) == 1
+ msg = f" collect {world}: tasks {s0}-{idx[-1]}, lenient {r['lenient'].mean() * 100:.1f} %"
+ if s.any():
+ msg += f" (student-driven {r['lenient'][s].mean() * 100:.1f} % of {int(s.sum())}"
+ msg += f", JT-driven {r['lenient'][~s].mean() * 100:.1f} %)" if (~s).any() else ")"
+ log(msg + f", {time.time() - t0:.0f} s")
+ out = concat(parts)
+ if rec is not None: # after concat (it drops 0-d entries)
+ out["robot"] = np.array(rec)
+ return out
+
+
+def concat(parts):
+ if len(parts) == 1:
+ return parts[0]
+ out, e0, r0 = {}, 0, 0
+ for p in parts:
+ q = dict(p)
+ q["row_ep"] = p["row_ep"].astype(np.int64) + e0
+ q["ep_row_start"] = p["ep_row_start"] + r0
+ e0 += len(p["end"])
+ r0 += len(p["row_ep"])
+ for k, v in q.items():
+ if np.ndim(v) == 0:
+ continue
+ out.setdefault(k, []).append(v)
+ out = {k: np.concatenate(v) for k, v in out.items()}
+ out["wall_s"] = np.float64(sum(float(p["wall_s"]) for p in parts))
+ for k in ("roll_hi_deg", "roll_cap_rad"): # the roll cap (0-d, one env for every part): the summary's roll keys
+ if k in parts[0]:
+ out[k] = parts[0][k]
+ return out
+
+
+def jt_roll_cap(jt):
+ """The wrist-roll cap (sim deg) the JT was trained with (its checkpoint's env record), None = none."""
+ rec = getattr(jt, "env_rec", None) or {}
+ env = rec.get("env") if isinstance(rec, dict) else None
+ v = env.get("roll_hi_deg") if isinstance(env, dict) else None
+ return None if v is None else float(v)
+
+
+def jt_floor_raise(jt):
+ """The floor raise (``JE.JointEnvConfig.floor_raise`` tuple) the JT was trained with (its checkpoint's env record),
+ None = none (``JT.jt_floor_raise``)."""
+ return JT.jt_floor_raise(jt)
+
+
+def check_jt_floor(jt, floor_raise, allow=False, tol=1e-9):
+ """Online runs: the labelling JT must have been trained with the online env's floor raise
+ (``VI.online_floor_raise``; None = none; both None: no check), else SystemExit (``allow``: a warning). The JT's
+ labels are its raw targets; a JT trained under another floor learned descents for another action layer (the
+ baseline of D's teacher under raised floors: ~/so101_r2s_claude/v12/table/). -> the JT's own floor raise."""
+ jf = jt_floor_raise(jt)
+ a = (0.0, 0.0, 0.0) if floor_raise is None else tuple(floor_raise)
+ b = (0.0, 0.0, 0.0) if jf is None else jf
+ if max(abs(x - y) for x, y in zip(a, b)) > tol:
+ msg = (f"online floor raise {None if floor_raise is None else list(floor_raise)}: the JT "
+ f"{getattr(jt, 'path', '?')} was trained with floor raise {None if jf is None else list(jf)}")
+ if not allow:
+ raise SystemExit(msg + "; use the teacher fine-tuned with this raise or --allow-floor-raise-mismatch")
+ log("WARNING: " + msg + " (--allow-floor-raise-mismatch)")
+ return jf
+
+
+def inrun_eval_setup(a, ocfg, log=log):
+ """The in-run evaluation world of an online run (v12 review finding 5). ``student_floor`` "observed" (one fixed
+ lower table under every training world, the robot's flat floor): the evaluations run on that plane by default
+ (``--eval-table-plane``; ``--no-eval-table-plane``: the sim table, a WARNING: no training world is at that height)
+ and take the online config's episode length and hold cap (``OnlineConfig.horizon`` / ``hold_cap_s``) unless
+ ``--horizon`` / ``--hold-cap-s`` are given. Other runs: as before (the plane only with ``--eval-table-plane``, 400
+ steps, the task's hold cap). -> (eval_table_plane bool, horizon, hold_cap_s or None = the task default)."""
+ observed = getattr(ocfg, "student_floor", "true") == "observed"
+ etp = getattr(a, "eval_table_plane", None)
+ if etp is None:
+ etp = observed
+ elif observed and not etp:
+ log("WARNING: --no-eval-table-plane with student_floor observed: the in-run evaluations run on the sim table "
+ "(no training world is at that height)")
+ hor = getattr(a, "horizon", None)
+ hor = int(hor) if hor is not None else (int(ocfg.horizon) if observed else 400)
+ cap = getattr(a, "hold_cap_s", None)
+ if cap is None and observed and float(ocfg.hold_cap_s) != JE.T.TaskConfig.hold_cap_s:
+ cap = float(ocfg.hold_cap_s)
+ return bool(etp), hor, (None if cap is None else float(cap))
+
+
+def check_jt_roll(jt, roll_hi_deg, allow=False):
+ """Online runs with a wrist-roll cap (sim deg; None = off: no check): the labelling JT must have been trained with
+ that cap or a lower one, else SystemExit (``allow``: a warning). Capped labels of a JT trained without the cap teach
+ the student to sit at the cap and time out (jt_h110 on HOME45: lenient 97.6 -> 89.6 % with a cap of 100).
+ -> the JT's own cap (sim deg, None = none)."""
+ jt_roll = jt_roll_cap(jt)
+ if roll_hi_deg is not None and (jt_roll is None or jt_roll > float(roll_hi_deg) + 1e-9):
+ msg = (f"online roll_hi_deg {float(roll_hi_deg):g}: the JT {getattr(jt, 'path', '?')} was trained with roll "
+ f"cap {jt_roll} (capped labels of a JT trained without the cap teach the student to sit at it)")
+ if not allow:
+ raise SystemExit(msg + "; use a roll-capped fine-tune (r2s_online.sbatch TEACHER_JT) or --allow-uncapped-jt")
+ log("WARNING: " + msg + " (--allow-uncapped-jt)")
+ return jt_roll
+
+
+def evaluate(st, jt, tasks, world, cache, views, randomise=False, jaw_lead=None, record_states=False,
+ full_horizon=False, device="cuda", lag=None, lag_range=None, qd_window=0, light_redraw_p=1.0):
+ """``lag``: image lag in control steps (default the student's nominal ``cfg.lag``); ``lag_range``: drawn per world
+ instead; ``qd_window`` > 0: the robot-like qdot input (``viral.robot_qd``); ``light_redraw_p`` < 1: the per-call
+ light / intrinsics stay for several decisions (``viral.Actor``)."""
+ actor = VI.Actor(st, views, randomise=randomise, jaw_lead=jaw_lead, device=device, lag=lag, lag_range=lag_range,
+ qd_window=qd_window, light_redraw_p=light_redraw_p)
+ env = cache.get(world, len(tasks["seeds"]))
+ actor.bind(env) # cmd_in and the last-command input (ViralConfig.lastcmd):
+ # the env's executed targets (env.u_exe)
+ if getattr(env, "q_offset", None) is not None: # evaluation only (table.py): the student's joint frame
+ actor.q_offset = env.q_offset.tolist()
+ with taps(env, actor.push if actor.needs_tap else None):
+ r = JT.run_tasks(env, tasks, jt, actor, np.ones(len(tasks["seeds"]), np.int64), None, 0,
+ record=True, record_states=record_states, full_horizon=full_horizon)
+ r["render_s"], r["model_s"] = np.float64(actor.t_render), np.float64(actor.t_model)
+ if getattr(env, "table_plane", None) is not None or getattr(env, "q_offset", None) is not None \
+ or getattr(env, "floor_z", 0.0) != 0.0 or getattr(env, "floor_plane", None) is not None:
+ r["table"] = np.array(json.dumps(env.table_info()))
+ if cache.cli is not None:
+ r["log_only"] = np.array(json.dumps(list(env.tcfg.log_only)))
+ summ = JT.summarize(r)
+ if env.goal_jump is not None: # the evaluation-only goal shift: outcomes of the shifted / unshifted episodes
+ summ["goal_shift"] = goal_shift_summary(r)
+ r["summary"] = np.array(json.dumps(summ))
+ r["world"] = np.array(world)
+ r["randomise"] = np.bool_(randomise)
+ r["jaw_lead"] = np.int64(actor.jaw_lead)
+ if actor.light_redraw_p < 1.0: # per-call light / intrinsics kept for several decisions: the setting, the changes
+ r["light_redraw"] = np.array(json.dumps(dict(p=actor.light_redraw_p, changes=actor.state_changes,
+ decisions=actor.calls)))
+ if actor.kmax > 0:
+ r["image_lag"] = np.array(json.dumps(dict(lag=actor.lag, lag_range=actor.lag_range)))
+ if actor.qd_window > 0: # the robot-like qdot: window and the student's qdot INPUT per row (row_qd: the sim's)
+ r["qd_robot"] = np.int64(actor.qd_window)
+ if actor.qd_log and "row_ep" in r:
+ r["row_qd_input"] = torch.stack(actor.qd_log, 1).numpy()[r["row_ep"].astype(np.int64),
+ r["row_t"].astype(np.int64)]
+ if env.dyn is not None: # robot dynamics of the evaluation ($NEDM_SO101_DYN): the setting + per-episode draws
+ r["dyn"] = np.array(json.dumps(env.dyn_info()))
+ elif env.tcfg.hold_cap_s != JE.T.TaskConfig.hold_cap_s:
+ r["hold_cap_s"] = np.float64(env.tcfg.hold_cap_s)
+ if JE.EVAL_KP_SCALE != 1.0: # $NEDM_SO101_EVAL_KP_SCALE (also when the robot dynamics are off)
+ r["kp_scale"] = np.float64(JE.EVAL_KP_SCALE)
+ if st.cfg.scene:
+ r["scene"] = np.array(json.dumps(dict(scene=st.cfg.scene, scene_sha256=st.cfg.scene_sha256,
+ calib_sha256=st.cfg.calib_sha256, crops=st.cfg.crops)))
+ return r
+
+
+def goal_shift_summary(r):
+ """Outcomes of the episodes with / without a goal jump (``run_tasks`` output with ``goal_jumps``): count, lenient,
+ strict, end xy error p50 / p90 (mm; to the final goal), failure causes; the shift offsets (mm, + = past)."""
+ from nedm.so101_policy import task as T
+ n = np.asarray(r["goal_jumps"]) > 0
+ le, s = np.asarray(r["lenient"]).astype(bool), np.asarray(r["success"]).astype(bool)
+ ex = np.asarray(r["end_xy"], np.float64) * 1e3
+ out = {}
+ for tag, m in (("shifted", n), ("unshifted", ~n)):
+ if not m.any():
+ out[tag] = dict(n=0)
+ continue
+ e = ex[m][np.isfinite(ex[m])]
+ causes = {T.ENDS[int(k)]: int(v) for k, v in zip(*np.unique(np.asarray(r["end"])[m & ~le], return_counts=True))}
+ out[tag] = dict(n=int(m.sum()), lenient=float(le[m].mean()), strict=float(s[m].mean()),
+ end_xy_mm_p50=float(np.median(e)) if len(e) else None,
+ end_xy_mm_p90=float(np.percentile(e, 90)) if len(e) else None, causes_not_lenient=causes)
+ if n.any():
+ d = np.asarray(r["goal_jump_d"], np.float64)[n] * 1e3
+ out["shift_d_mm"] = [float(v) for v in np.percentile(d, [0, 50, 100])]
+ return out
+
+
+def eval_sets(paths, n=0):
+ """``--eval-tasks`` files -> [(tag prefix, tasks)]: the first file keeps the old names (prefix ""), the others
+ are prefixed with their file stem."""
+ out = []
+ for i, p_ in enumerate(paths):
+ out.append(("" if i == 0 else Path(p_).stem + "_", load_tasks(p_, np.arange(n) if n else None)))
+ return out
+
+
+def guard(tasks, paths):
+ """No training task may be an evaluation task."""
+ tr = set(np.asarray(tasks["seeds"]).tolist())
+ for p_ in paths:
+ hit = tr & set(np.asarray(load_tasks(p_)["seeds"]).tolist())
+ if hit:
+ raise ValueError(f"{len(hit)} training task seeds are in {p_}")
+
+
+def agree(r_a, r_b):
+ a, b = np.asarray(r_a["lenient"]).astype(bool), np.asarray(r_b["lenient"]).astype(bool)
+ return dict(both=int((a & b).sum()), a_only=int((a & ~b).sum()), b_only=int((~a & b).sum()),
+ neither=int((~a & ~b).sum()), agreement=float((a == b).mean()))
+
+
+def cmd_run(a):
+ out = Path(a.out)
+ (out / "data").mkdir(parents=True, exist_ok=True)
+ if not (out / "args.json").exists():
+ (out / "args.json").write_text(json.dumps({k: v for k, v in vars(a).items() if k != "fn"}, indent=1, default=str))
+ jt = JE.JointTeacher(x(a.jt), a.device)
+ cfg_d = json.loads(Path(a.config).read_text())
+ for s in a.set or []:
+ k, v = s.split("=", 1)
+ cfg_d[k] = json.loads(v)
+ cfg_d["seed"] = a.seed
+ cfg = VI.ViralConfig.from_dict(cfg_d)
+ VI.pin_real(cfg, a.allow_scene_change) # real scene: crops + file hashes into the student config
+ if cfg.scene: # a resumed run must keep its scene (rounds share one scene)
+ pin = dict(scene=cfg.scene, scene_sha256=cfg.scene_sha256, calib_sha256=cfg.calib_sha256, crops=cfg.crops)
+ pf = out / "real_pin.json"
+ if pf.exists():
+ old = json.loads(pf.read_text())
+ diff = [k for k in ("scene_sha256", "calib_sha256", "crops") if old.get(k) != pin[k]]
+ if diff and not a.allow_scene_change:
+ raise ValueError(f"{pf}: {diff} changed since the run started (--allow-scene-change to continue)")
+ else:
+ pf.write_text(json.dumps(pin, indent=1))
+ tasks = load_tasks(a.tasks)
+ from nedm.so101_policy.vision.teacher import check_seeds
+ check_seeds(tasks["seeds"])
+ evs = eval_sets(a.eval_tasks, a.eval_n)
+ guard(tasks, list(a.eval_tasks) + list(a.guard_tasks or []))
+ cache = EnvCache(jt, a.device, x(a.nrd_ckpt), a.eval_workers, x(a.mj_python), a.horizon, hold_cap_s=a.hold_cap_s,
+ roll_hi_deg=a.roll_hi_deg)
+ views = VI.make_views(cfg, a.render_worlds, seed=a.seed, allow_change=a.allow_scene_change, device=a.device)
+ lag_rec = cfg.lag_max > 0
+ rows = [np.arange(0, a.r0_tasks)]
+ for i in range(a.rounds):
+ s0 = a.r0_tasks + i * a.round_tasks
+ rows.append(np.arange(s0, s0 + a.round_tasks))
+ if rows[-1][-1] >= len(tasks["seeds"]):
+ raise ValueError(f"{len(tasks['seeds'])} tasks, need {rows[-1][-1] + 1}")
+ files = [x(f) for f in (a.extra_data or [])]
+ prev = x(a.init_from) if a.init_from else None
+ for i in range(a.rounds + 1):
+ f = out / "data" / f"r{i}.npz"
+ t = subset(tasks, rows[i])
+ n = len(rows[i])
+ if not f.exists():
+ t0 = time.time()
+ rng = np.random.default_rng(a.seed * 1000 + i)
+ share = 1.0 if i == 0 else a.teacher_share
+ src = np.where(rng.random(n) < share, 0, 1).astype(np.int64)
+ if prev is None:
+ src[:] = 0
+ noisy = (src == 0) & (rng.random(n) < a.r0_noise_frac)
+ noise = np.where(noisy, a.noise, 0.0)
+ student = None
+ if (src == 1).any():
+ st, _ = VI.load_student(prev, a.device)
+ student = VI.Actor(st, views, randomise=a.collect_randomise, device=a.device,
+ lag_range=cfg.lag_range, seed=a.seed + i)
+ d = collect(t, a.world, jt, cache, src, noise, a.seed + 1000 * i, a.batch, student, lag_rec=lag_rec,
+ lag_kmax=cfg.lag_max)
+ d["meta"] = np.array(json.dumps(dict(round=i, world=a.world, jt=jt.info(), teacher_share=share,
+ noise=a.noise, student=str(prev) if student else "",
+ collect_randomise=a.collect_randomise, wall_s=time.time() - t0)))
+ np.savez_compressed(f, **d)
+ s = d["src"] == 1
+ progress(out, stage=f"data r{i}", wall_s=time.time() - t0, rows=int(len(d["row_ep"])),
+ lenient_jt=float(d["lenient"][~s].mean()) if (~s).any() else None,
+ lenient_student=float(d["lenient"][s].mean()) if s.any() else None, n_student=int(s.sum()))
+ del d, student
+ torch.cuda.empty_cache()
+ files.append(str(f))
+ ck = out / f"r{i}" / "last.pt"
+ if not ck.exists():
+ t0 = time.time()
+ data = VI.StudentSet(files, a.device, cfg.chunk, seed=a.seed, lag=cfg.lag_max)
+ first = i == 0 and not a.init_from
+ steps = a.train_steps0 if first else a.train_steps
+ VI.train(data, views, cfg, out / f"r{i}", max_steps=steps, init_from=None if first else prev, log=log,
+ device=a.device, extra_meta=dict(argv=sys.argv))
+ progress(out, stage=f"train r{i}", wall_s=time.time() - t0, steps=steps, rows=data.n_rows,
+ eps=data.n_eps)
+ del data
+ torch.cuda.empty_cache()
+ prev = str(ck)
+ if i % a.eval_every == 0 or i == a.rounds:
+ st, _ = VI.load_student(ck, a.device)
+ res = {}
+ for pre, ev, w, rnd in [(p_, e_, w_, r_) for p_, e_ in evs for w_ in a.eval_worlds
+ for r_ in ([False, True] if a.eval_randomise else [False])]:
+ tag = f"{pre}{w}{'_dr' if rnd else ''}"
+ fe = out / f"r{i}" / f"eval_{tag}.npz"
+ if not fe.exists():
+ t0 = time.time()
+ r = evaluate(st, jt, ev, w, cache, views, rnd, device=a.device)
+ np.savez_compressed(fe, **r)
+ s = json.loads(str(r["summary"]))
+ progress(out, stage=f"eval r{i} {tag}", wall_s=time.time() - t0, **s)
+ log(f"r{i} eval {tag}: lenient {s['lenient'] * 100:.0f} % strict {s['strict'] * 100:.0f} % "
+ f"lifted {s['lifted'] * 100:.0f} % causes {s['causes_not_lenient']}")
+ res[tag] = dict(np.load(fe))
+ if "mujoco" in res and "nrd" in res:
+ progress(out, stage=f"agree r{i}", **agree(res["mujoco"], res["nrd"]))
+ del st
+
+
+def cmd_online(a):
+ """VIRAL's online loop (``viral.OnlineDAgger``) from an initial student checkpoint; config overrides of the student
+ (``--config`` keys that differ, e.g. qd_noise, jaw_lead, dr) are applied to the loaded student."""
+ import csv
+ out = Path(a.out)
+ (out / "ckpt").mkdir(parents=True, exist_ok=True)
+ (out / "args.json").write_text(json.dumps({k: v for k, v in vars(a).items() if k != "fn"}, indent=1, default=str))
+ jt = JE.JointTeacher(x(a.jt), a.device)
+ st, ck = VI.load_student(x(a.init), a.device)
+ if a.config:
+ over = json.loads(Path(a.config).read_text())
+ for s_ in a.set or []:
+ k, v = s_.split("=", 1)
+ over[k] = json.loads(v)
+ from dataclasses import asdict as _ad
+ cd = _ad(st.cfg)
+ arch = {k: over.get(k, cd[k]) for k in VI.ARCH_KEYS} # input options: zero-init expansion of the student
+ lastcmd = bool(over.get("lastcmd", cd["lastcmd"])) # the last-command input (own zero-init layer)
+ if "cmd_scale" in over and st.cfg.cmd_in and tuple(over["cmd_scale"]) != tuple(st.cfg.cmd_scale):
+ raise SystemExit("cmd_scale: the student already has a cmd input with another scale")
+ cd.update({k: v for k, v in over.items() if k in cd and k not in VI.ARCH_KEYS and k != "lastcmd"})
+ st.cfg = VI.ViralConfig.from_dict(cd)
+ if (int(arch["hist"]), bool(arch["cmd_in"]), bool(arch["img_hist"])) != \
+ (int(st.cfg.hist), bool(st.cfg.cmd_in), bool(st.cfg.img_hist)):
+ st = VI.expand_student(st, hist=int(arch["hist"]), cmd_in=bool(arch["cmd_in"]),
+ img_hist=bool(arch["img_hist"]), device=a.device)
+ log(f"student inputs: hist {st.cfg.hist}, cmd_in {st.cfg.cmd_in}, img_hist {st.cfg.img_hist} "
+ f"(zero-init expansion of {a.init})")
+ if lastcmd != st.cfg.lastcmd: # + the last-command input, zero weights (acts as the init)
+ if not lastcmd:
+ raise SystemExit("--config lastcmd false: the initial student has the last-command input")
+ st = VI.expand_lastcmd(st, a.device)
+ log("student: + the last-command input (zero-initialised; ViralConfig.lastcmd)")
+ VI.pin_real(st.cfg, a.allow_scene_change)
+ oc = json.loads(Path(a.online_config).read_text()) if a.online_config else {}
+ for s_ in a.oset or []:
+ k, v = s_.split("=", 1)
+ oc[k] = json.loads(v)
+ ocfg = VI.OnlineConfig.from_dict(oc)
+ try: # v12 visual fix: the online config's scene guard
+ VI.check_scene_requirement(st.cfg, ocfg)
+ except ValueError as e:
+ raise SystemExit(str(e)) from None
+ jt_roll = check_jt_roll(jt, ocfg.roll_hi_deg, a.allow_uncapped_jt)
+ o_raise = VI.online_floor_raise(ocfg) # v12: student_floor observed (None: the online env's floor at z 0)
+ jt_raise = check_jt_floor(jt, o_raise, a.allow_floor_raise_mismatch)
+ if ocfg.lag_range and tuple(ocfg.lag_range) != tuple(st.cfg.lag_range): # the online config's image lag range
+ sets = dict(s_.split("=", 1) for s_ in a.set or []) # (wins over --config, not --set)
+ if a.config and "lag_range" in sets and tuple(json.loads(sets["lag_range"])) != tuple(ocfg.lag_range):
+ raise SystemExit(f"lag_range: --set {sets['lag_range']} vs the online config {list(ocfg.lag_range)}")
+ log(f"image lag range {list(ocfg.lag_range)} (online config; student {list(st.cfg.lag_range)})")
+ st.cfg = VI.ViralConfig.from_dict({**VI.asdict(st.cfg), "lag_range": list(ocfg.lag_range)})
+ tasks = load_tasks(a.tasks)
+ from nedm.so101_policy.vision.teacher import check_seeds
+ check_seeds(tasks["seeds"])
+ evs = eval_sets(a.eval_tasks, a.eval_n)
+ guard(tasks, list(a.eval_tasks) + list(a.guard_tasks or []))
+ vcfg = VI.online_views_cfg(st.cfg, ocfg) # training views: + the online config's plate thickness (v8)
+ if vcfg is not st.cfg and ocfg.plate_mm:
+ log(f"training views: RealDR plate_thickness {vcfg.real_dr['plate_thickness']} m (online config plate_mm; "
+ "the evaluation views and the student's config keep the scene's plate)")
+ if vcfg is not st.cfg and ocfg.gripper_look:
+ log(f"training views: RealDR gripper_look {json.dumps(ocfg.gripper_look)} (online config; the evaluation "
+ f"views and the student's config keep the scene's look; scene {st.cfg.scene} sha256 "
+ f"{st.cfg.scene_sha256[:12]})")
+ views = VI.make_views(vcfg, ocfg.envs, seed=a.seed, allow_change=a.allow_scene_change, device=a.device)
+ etab = None # v12 --eval-table-plane: the in-run evaluations on the training plane (robot-like)
+ e_plane, e_hor, e_cap = inrun_eval_setup(a, ocfg) # (student_floor observed: plane, horizon and cap by default)
+ if e_plane:
+ from nedm.so101_policy import table as TB
+ from nedm.so101_policy.table_bias import TableBiasConfig, is_on
+ if not is_on(ocfg.table_bias) or not TableBiasConfig.from_dict(ocfg.table_bias).plane:
+ raise SystemExit("--eval-table-plane: needs the online config's table_bias with a fixed plane")
+ etab = TB.parse(plane=TableBiasConfig.from_dict(ocfg.table_bias).plane) # (a zero plane: None, as off)
+ log(f"in-run evaluations: MuJoCo {TB.describe(etab)} (the training plane), floor 'zero' (flat in the arm "
+ "frame, the robot's), renders on the plane")
+ eviews = VI.make_views(st.cfg, a.render_worlds, seed=a.seed + 1, allow_change=a.allow_scene_change, device=a.device,
+ **({} if etab is None else dict(geometry_over={"table_plane": list(etab)})))
+ # the in-run evaluations: the online config's wrist-roll cap (--roll-hi-deg: another one for the evaluations only)
+ eval_roll = a.roll_hi_deg if a.roll_hi_deg is not None else ocfg.roll_hi_deg
+ if eval_roll != ocfg.roll_hi_deg:
+ log(f"NOTE: in-run evaluations with roll cap {eval_roll}, training env {ocfg.roll_hi_deg}")
+ if etab is not None or e_hor != 400 or e_cap is not None:
+ log(f"in-run evaluations: {e_hor} steps, hold cap {e_cap if e_cap is not None else JE.T.TaskConfig.hold_cap_s} s"
+ f", table {'the training plane' if etab is not None else 'the sim table'}")
+ cache = EnvCache(jt, a.device, x(a.nrd_ckpt), a.eval_workers, x(a.mj_python), e_hor, hold_cap_s=e_cap,
+ roll_hi_deg=eval_roll, table=None if etab is None else (etab, "zero", None))
+ od = VI.OnlineDAgger(st, jt, tasks, x(a.nrd_ckpt), views, ocfg, a.device, a.seed, log)
+ meta = dict(student_cfg=VI.cfg_dict(st.cfg), online=VI.asdict(ocfg), init=str(a.init), jt=jt.info(), argv=sys.argv)
+ if etab is not None or e_hor != 400 or e_cap is not None: # v12 (the old default: no key)
+ meta["inrun_eval"] = dict(horizon=e_hor, hold_cap_s=e_cap, table_plane=None if etab is None else list(etab))
+ robot_opts = od.env.dyn is not None or od.qd_hist is not None or od.env.tcfg.horizon != 400 \
+ or od.env.tcfg.hold_cap_s != JE.T.TaskConfig.hold_cap_s or od.env.goal_jump is not None \
+ or od.env.roll_hi is not None or od.env.cfg.floor_raise is not None or jt_raise is not None or etab is not None
+ if robot_opts: # the resolved online env (robot dynamics, episode length, hold cap)
+ meta["online_env"] = dict(horizon=od.env.tcfg.horizon, hold_cap_s=od.env.tcfg.hold_cap_s,
+ hold_obs_s=od.env.cfg.hold_obs_s,
+ dyn=VI.asdict(od.env.dyn.cfg) if od.env.dyn is not None else None)
+ if od.env.goal_jump is not None:
+ meta["online_env"]["goal_jump"] = VI.asdict(od.env.goal_jump.cfg)
+ if od.env.roll_hi is not None:
+ meta["online_env"]["roll_cap"] = dict(od.env.roll_info(), eval_roll_hi_deg=eval_roll,
+ jt_roll_hi_deg=jt_roll)
+ if od.env.cfg.floor_raise is not None or jt_raise is not None or etab is not None: # v12 (off: no key)
+ meta["online_env"]["floor_raise"] = dict(
+ env=None if od.env.cfg.floor_raise is None else list(od.env.cfg.floor_raise),
+ jt=None if jt_raise is None else list(jt_raise), student_floor=ocfg.student_floor,
+ eval_table_plane=None if etab is None else list(etab))
+ log(f"online env: {json.dumps(meta['online_env'])}")
+ (out / "meta.json").write_text(json.dumps(meta, indent=1, default=str))
+ f = open(out / "curve.csv", "a", newline="")
+ wr = None
+ t0 = time.time()
+ acc, tacc, n_acc = {}, {}, 0
+ min_fill = max(st.cfg.batch * 4, ocfg.envs)
+ base_lr = [g_["lr"] for g_ in od.opt.param_groups]
+ for it in range(1, ocfg.iterations + 1):
+ od.it = it - 1
+ if ocfg.lr_decay_start >= 0 and it > ocfg.lr_decay_start:
+ u = (it - ocfg.lr_decay_start) / max(1, ocfg.iterations - ocfg.lr_decay_start)
+ for g_, b_ in zip(od.opt.param_groups, base_lr):
+ g_["lr"] = b_ * (1 - (1 - ocfg.lr_final_frac) * u)
+ T = od.act()
+ if it == 1 and robot_opts:
+ log(f"robot draws at the start: {json.dumps(od.log_extra())}")
+ tt = time.time()
+ info = od.train_steps() if od.buf.n >= min_fill else {}
+ T["train"] = time.time() - tt
+ for k, v in info.items():
+ acc[k] = acc.get(k, 0.0) + v
+ for k, v in T.items():
+ tacc[k] = tacc.get(k, 0.0) + v
+ n_acc += 1
+ if it % ocfg.log_every == 0:
+ s_ = od.stats
+ row = dict(it=it, wall_min=round((time.time() - t0) / 60, 2), samples=od.samples, buffer=od.buf.n,
+ **{k: round(v / n_acc, 4) for k, v in acc.items()},
+ **{f"t_{k}": round(v / n_acc, 3) for k, v in tacc.items()},
+ ep_student=s_["ep_student"], len_student=round(s_["len_student"] / max(s_["ep_student"], 1), 3),
+ ep_teacher=s_["ep_teacher"], len_teacher=round(s_["len_teacher"] / max(s_["ep_teacher"], 1), 3),
+ **{k: s_[k] for k in ("ep_jump_student", "len_jump_student", "ep_jump_teacher",
+ "len_jump_teacher") if k in s_},
+ **({} if "roll_over_student" not in s_ else dict( # roll cap: episodes that commanded above it
+ roll_over_student=round(s_["roll_over_student"] / max(s_["ep_student"], 1), 4),
+ roll_over_teacher=round(s_["roll_over_teacher"] / max(s_["ep_teacher"], 1), 4))),
+ **od.log_extra())
+ od.stats = {k: 0 for k in s_}
+ acc, tacc, n_acc = {}, {}, 0
+ if wr is None:
+ wr = csv.DictWriter(f, fieldnames=list(row), extrasaction="ignore")
+ wr.writeheader()
+ wr.writerow(row)
+ f.flush()
+ log(json.dumps(row))
+ if (ocfg.save_every > 0 and it % ocfg.save_every == 0) or it == ocfg.iterations:
+ rec = od.ckpt_record() # v8: the image lag / table options trained with ({} when off)
+ VI.save_student(st, out / "ckpt" / f"it_{it:05d}.pt", it=it, samples=od.samples, **rec)
+ VI.save_student(st, out / "last.pt", it=it, samples=od.samples, **rec)
+ if ocfg.eval_every > 0 and (it % ocfg.eval_every == 0 or it == ocfg.iterations): # eval_every 0: none
+ st.eval()
+ for (pre, ev), rnd in [(e_, r_) for e_ in evs for r_ in ([False, True] if a.eval_randomise else [False])]:
+ tag = f"{pre}mujoco{'_dr' if rnd else ''}"
+ te = time.time()
+ r = evaluate(st, jt, ev, "mujoco", cache, eviews, rnd, device=a.device,
+ light_redraw_p=ocfg.light_redraw_p)
+ np.savez_compressed(out / f"eval_it{it:05d}_{tag}.npz", **r)
+ s_ = json.loads(str(r["summary"]))
+ progress(out, stage=f"eval it {it} {tag}", wall_s=time.time() - te, samples=od.samples, **s_)
+ log(f"it {it} eval {tag}: lenient {s_['lenient'] * 100:.0f} % strict {s_['strict'] * 100:.0f} % "
+ f"lifted {s_['lifted'] * 100:.0f} % causes {s_['causes_not_lenient']}")
+ st.train()
+ if torch.cuda.is_available() and torch.device(a.device).type == "cuda":
+ log(f"done: {ocfg.iterations} decisions in {(time.time() - t0) / 60:.1f} min, peak GPU memory (torch) "
+ f"{torch.cuda.max_memory_allocated() / 1e9:.2f} GB")
+
+
+def cmd_eval(a):
+ from nedm.so101_policy import table as TB
+ jt = JE.JointTeacher(x(a.jt), a.device)
+ st, _ = VI.load_student(a.student, a.device)
+ if a.scene_path: # the same scene / calibration files at another path (the pinned sha256 is still checked)
+ st.cfg.scene = x(a.scene_path)
+ if a.calib_path:
+ st.cfg.calib = x(a.calib_path)
+ t = load_tasks(a.tasks, np.arange(a.first, a.first + a.n) if a.n else None)
+ plane, floor, qo, moved = TB.from_cli(a)
+ gs = JE.GoalJumpConfig.from_spec(a.goal_shift, max_n=1, before_p=0.0) if a.goal_shift else None
+ if not a.floor_raise and jt_floor_raise(jt) is not None: # (v12 review finding 4: a note, no default)
+ log(f"NOTE: the JT was trained with floor raise {list(jt_floor_raise(jt))}; this student evaluation has none "
+ "(--floor-raise: the TRUE-frame raise; a table-frame student's robot-like check is --table-plane with "
+ "--floor zero)")
+ cache = EnvCache(jt, a.device, x(a.nrd_ckpt), a.workers, x(a.mj_python), a.horizon,
+ table=(plane, floor, qo) if moved else None, cli=a if a.log_only_extra else None,
+ hold_cap_s=a.hold_cap_s, goal_jump=gs, roll_hi_deg=a.roll_hi_deg,
+ floor_raise=a.floor_raise or None)
+ geo = {"table_plane": list(plane)} if plane is not None and not a.no_render_table else None
+ if geo:
+ log(f"render: {TB.describe(plane)} (scene geometry override, evaluation only)")
+ views = VI.make_views(st.cfg, a.render_worlds, seed=a.seed, allow_change=a.allow_scene_change, device=a.device,
+ geometry_over=geo)
+ r = evaluate(st, jt, t, a.world, cache, views, a.randomise, a.jaw_lead, a.record_states, a.full_horizon, a.device,
+ lag=a.lag, lag_range=a.lag_range, qd_window=a.qd_robot, light_redraw_p=a.light_redraw_p)
+ r["student"] = np.array(str(a.student))
+ if a.out:
+ np.savez_compressed(a.out, **r)
+ log(f"student {a.world}{' randomised' if a.randomise else ''}: {str(r['summary'])}")
+
+
+def cmd_collect(a):
+ jt = JE.JointTeacher(x(a.jt), a.device)
+ t = load_tasks(a.tasks, np.arange(a.first, a.first + a.n) if a.n else None)
+ n = len(t["seeds"])
+ cache = EnvCache(jt, a.device, x(a.nrd_ckpt), a.workers, x(a.mj_python), a.horizon, hold_cap_s=a.hold_cap_s,
+ roll_hi_deg=a.roll_hi_deg, floor_raise=JT.resolve_floor_raise(a.floor_raise, jt, log, "collect"))
+ rng = np.random.default_rng(a.seed)
+ student = None
+ src = np.zeros(n, np.int64)
+ if a.student:
+ st, _ = VI.load_student(a.student, a.device)
+ views = VI.make_views(st.cfg, a.render_worlds, seed=a.seed, allow_change=a.allow_scene_change, device=a.device)
+ student = VI.Actor(st, views, randomise=a.randomise, device=a.device, lag_range=st.cfg.lag_range, seed=a.seed)
+ src = np.where(rng.random(n) < a.teacher_share, 0, 1)
+ noise = np.where((src == 0) & (rng.random(n) < a.noise_frac), a.noise, 0.0)
+ kmax = max(int(a.lag_kmax), st.cfg.lag_max if a.student else 0) # a lag above viral.LAG_REC needs more states
+ d = collect(t, a.world, jt, cache, src, noise, a.seed, a.batch, student, lag_rec=a.lag_rec or a.lag_kmax > 0,
+ lag_kmax=kmax)
+ np.savez_compressed(a.out, **d)
+ log(f"-> {a.out}")
+
+
+def main(argv=None):
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = p.add_subparsers(dest="cmd", required=True)
+
+ def common(q):
+ q.add_argument("--device", default="cuda")
+ q.add_argument("--nrd-ckpt", default=NRD)
+ q.add_argument("--jt", required=True)
+ q.add_argument("--mj-python", default=MJ_PY)
+ q.add_argument("--horizon", type=int, default=400)
+ q.add_argument("--hold-cap-s", type=float, default=None,
+ help="evaluation / collection envs: the hold_cap rule (s held in the air; default 3.5)")
+ q.add_argument("--roll-hi-deg", type=float, default=None,
+ help="evaluation / collection envs: the wrist-roll target cap (sim deg; the real roll ends at "
+ "101.2); online: the in-run evaluations only (default the online config's roll_hi_deg)")
+ q.add_argument("--seed", type=int, default=0)
+ q.add_argument("--render-worlds", type=int, default=256)
+ q.add_argument("--allow-scene-change", action="store_true",
+ help="real scene: render with scene / calibration files whose sha256 differ from the student's")
+
+ q = sub.add_parser("run")
+ common(q)
+ q.add_argument("--out", required=True)
+ q.add_argument("--tasks", required=True)
+ q.add_argument("--eval-tasks", nargs="+", required=True)
+ q.add_argument("--eval-n", type=int, default=0)
+ q.add_argument("--guard-tasks", nargs="*", default=[GUARD])
+ q.add_argument("--config", required=True)
+ q.add_argument("--set", nargs="*")
+ q.add_argument("--world", default="nrd")
+ q.add_argument("--r0-tasks", type=int, default=2048)
+ q.add_argument("--rounds", type=int, default=4)
+ q.add_argument("--round-tasks", type=int, default=1024)
+ q.add_argument("--teacher-share", type=float, default=0.5)
+ q.add_argument("--r0-noise-frac", type=float, default=0.5)
+ q.add_argument("--noise", type=float, default=1.0)
+ q.add_argument("--collect-randomise", action="store_true")
+ q.add_argument("--batch", type=int, default=1024)
+ q.add_argument("--train-steps0", type=int, default=8000)
+ q.add_argument("--train-steps", type=int, default=4000)
+ q.add_argument("--init-from", default="")
+ q.add_argument("--extra-data", nargs="*")
+ q.add_argument("--eval-worlds", nargs="+", default=["mujoco"])
+ q.add_argument("--eval-randomise", action="store_true")
+ q.add_argument("--eval-every", type=int, default=1)
+ q.add_argument("--eval-workers", type=int, default=8)
+ q.set_defaults(fn=cmd_run)
+
+ q = sub.add_parser("online")
+ common(q)
+ q.add_argument("--out", required=True)
+ q.add_argument("--init", required=True)
+ q.add_argument("--tasks", required=True)
+ q.add_argument("--eval-tasks", nargs="+", required=True)
+ q.add_argument("--eval-n", type=int, default=0)
+ q.add_argument("--guard-tasks", nargs="*", default=[GUARD])
+ q.add_argument("--config", default="")
+ q.add_argument("--set", nargs="*")
+ q.add_argument("--online-config", default="")
+ q.add_argument("--oset", nargs="*")
+ q.add_argument("--eval-randomise", action="store_true")
+ q.add_argument("--eval-workers", type=int, default=8)
+ q.add_argument("--allow-uncapped-jt", action="store_true",
+ help="online config with roll_hi_deg: accept a JT trained without that cap (or a higher one)")
+ q.add_argument("--allow-floor-raise-mismatch", action="store_true",
+ help="accept a JT trained with another floor raise than the online env's (student_floor observed: "
+ "-table_bias.plane; else none)")
+ q.add_argument("--eval-table-plane", action=argparse.BooleanOptionalAction, default=None,
+ help="v12: the in-run MuJoCo evaluations on the online config's fixed table plane (table moved, "
+ "floor flat in the arm frame = the robot's, renders on the plane); default on for "
+ "student_floor observed, else off")
+ # in-run evaluations: --horizon / --hold-cap-s unset = 400 steps and the task's cap, or (student_floor observed) the
+ # online config's horizon / hold_cap_s (inrun_eval_setup)
+ q.set_defaults(fn=cmd_online, horizon=None)
+
+ q = sub.add_parser("eval")
+ common(q)
+ q.add_argument("--student", required=True)
+ q.add_argument("--tasks", required=True)
+ q.add_argument("--world", default="mujoco")
+ q.add_argument("--n", type=int, default=0)
+ q.add_argument("--first", type=int, default=0)
+ q.add_argument("--workers", type=int, default=8)
+ q.add_argument("--randomise", action="store_true")
+ q.add_argument("--jaw-lead", type=int, default=None)
+ q.add_argument("--record-states", action="store_true")
+ q.add_argument("--full-horizon", action="store_true")
+ q.add_argument("--lag", type=int, default=None, help="image lag (control steps); default the student's cfg.lag")
+ q.add_argument("--lag-range", type=int, nargs=2, default=None, help="image lag drawn per world (lo hi)")
+ q.add_argument("--qd-robot", type=int, default=0,
+ help="qdot input = the robot's slope over this many 20 ms states of the quantised q (0 = sim qdot)")
+ q.add_argument("--goal-shift", default="",
+ help="evaluation-only goal shift (overshoot gate), e.g. 'p=1,d=10:25,lat=8' (mm; JE.GoalJumpConfig "
+ "with the training trigger; defaults n=1 jump per episode, before=0: the cube ends PAST the "
+ "moved goal); the student's renders and the success check use the moved goal")
+ q.add_argument("--light-redraw-p", type=float, default=1.0,
+ help="with --randomise: per decision the probability of a new random light / intrinsics draw, else "
+ "the last one stays (an image-history student: use its online config's light_redraw_p); "
+ "1 = a new draw every decision")
+ q.add_argument("--floor-raise", default="",
+ help="the action-layer floor raise ('c0,c1,c2' m or one height; JointEnvConfig.floor_raise) in "
+ "the TRUE frame: the student reads the true joints (a table-frame student's robot-like "
+ "check is --table-plane with --floor zero); default off")
+ q.add_argument("--out", default="")
+ q.add_argument("--scene-path", default="", help="the student's scene file at this path (same sha256)")
+ q.add_argument("--calib-path", default="", help="the student's calibration file at this path (same sha256)")
+ from nedm.so101_policy import table as TB
+ TB.add_cli(q, student=True)
+ q.set_defaults(fn=cmd_eval)
+
+ q = sub.add_parser("collect")
+ common(q)
+ q.add_argument("--tasks", required=True)
+ q.add_argument("--world", default="nrd")
+ q.add_argument("--n", type=int, default=0)
+ q.add_argument("--first", type=int, default=0)
+ q.add_argument("--workers", type=int, default=8)
+ q.add_argument("--student", default="")
+ q.add_argument("--teacher-share", type=float, default=0.5)
+ q.add_argument("--noise-frac", type=float, default=0.5)
+ q.add_argument("--noise", type=float, default=1.0)
+ q.add_argument("--randomise", action="store_true")
+ q.add_argument("--batch", type=int, default=1024)
+ q.add_argument("--lag-rec", action="store_true", help="record the 20 ms states for image lag (row_lag)")
+ q.add_argument("--lag-kmax", type=int, default=0,
+ help="row_lag states per row (default viral.LAG_REC 4 or the student lag_max; implies --lag-rec)")
+ q.add_argument("--floor-raise", default="auto",
+ help="the action-layer floor raise ('c0,c1,c2' m or one height; JointEnvConfig.floor_raise): "
+ "'auto' (default) = the JT's own (none = off, the old behaviour), '0' = off; another value "
+ "than the JT's own is logged as a WARNING")
+ q.add_argument("--out", required=True)
+ q.set_defaults(fn=cmd_collect)
+
+ a = p.parse_args(argv)
+ a.fn(a)
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
diff --git a/so101_pick_place/code/scripts/so101_policy/vision_viral_teacher.py b/so101_pick_place/code/scripts/so101_policy/vision_viral_teacher.py
new file mode 100644
index 0000000000000000000000000000000000000000..6de360bd46673efaa8951e1388c71a11d6745c92
--- /dev/null
+++ b/so101_pick_place/code/scripts/so101_policy/vision_viral_teacher.py
@@ -0,0 +1,491 @@
+"""Markov joint teacher (JT) of build9 (``nedm.so101_policy.joint_env`` / ``joint_teacher``; docs
+~/so101_policy/docs/build9_viral_student.md).
+
+ export PYTHONPATH=src PY=~/miniconda3/envs/so101_vision/bin/python
+ $PY -P scripts/so101_policy/vision_viral_teacher.py tasks --kind C --n 100 --dev --out dev100.npz # MuJoCo tasks
+ $PY -P scripts/so101_policy/vision_viral_teacher.py expert --n 8192 --noise-frac 0.5 --noise 1.0 --out e0.npz
+ $PY -P scripts/so101_policy/vision_viral_teacher.py bc --data e0.npz [e1.npz ...] --out RUN/bc
+ $PY -P scripts/so101_policy/vision_viral_teacher.py eval --jt RUN/bc/bc.pt --tasks dev100.npz --world mujoco
+ $PY -P scripts/so101_policy/vision_viral_teacher.py eval-expert --tasks dev100.npz --world mujoco # current teacher
+ $PY -P scripts/so101_policy/vision_viral_teacher.py ppo --init RUN/bc/bc.pt --out RUN/ppo --iterations 200
+
+Task kinds: ``C`` = build8's stage-C sampler (collector start sampler + MuJoCo warm-up; random cube, random goal 6-30 cm,
+yaw +-30 deg), seeds 640,000+ (training) or 590,000+ (``--dev``; ``--first 1000`` = the fresh set 591,000+, ``--first 2000`` videos);
+``bank`` = start bank + sample_goals (NRD only), seeds 700,000+; ``H`` (real2sim) = HOME starts (``tray.make_tasks``
+stage H: the real robot's HOME pose + ``--home-config`` noise, a start-bank cube, stage C's goal), seeds 690,000+
+(training) or 597,000+ (``--dev``; ``--first 1000`` = fresh 598,000+). ``mix`` = a training table of several task files
+(e.g. 50 % C + 50 % H, rows shuffled):
+
+ $PY -P scripts/so101_policy/vision_viral_teacher.py tasks --kind H --n 100 --dev --home-config \
+ configs/so101_policy/vision/viral_r2s_home.json --out home_dev100.npz
+ $PY -P scripts/so101_policy/vision_viral_teacher.py mix --inputs C.npz H.npz --counts 8192 8192 --out mix.npz
+
+``starts`` = a PPO start bank from start banks and training task files (no goals, no seeds; e.g. the round v8 roll-cap
+fine-tune's bank: bank_pp_split0 once + the HOME45 training starts 3 times, ~50 % HOME45):
+
+ $PY -P scripts/so101_policy/vision_viral_teacher.py starts --inputs bank_pp_split0.npz train_H45_8k.npz \
+ --repeat 1 3 --exclude dev100.npz fresh100.npz home45_dev100.npz home45_fresh100.npz --roll-hi-deg 98 \
+ --out bank_pp_h45mix.npz
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+import time
+from dataclasses import asdict
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from nedm.so101_policy import joint_env as JE
+from nedm.so101_policy import joint_teacher as JT
+from nedm.so101_policy.paths import DATA
+
+TEACHER = str(DATA / "teacher" / "t0_nC1_s62_b" / "model_00171.pt") # T0, the decoder-PPO expert (README)
+NRD = str(DATA / "nrd" / "c1_s62" / "best.pt") # the policy NRD (main-compatible file; README)
+MJ_PY = sys.executable # Python of the CPU MuJoCo worker processes
+TRAIN_FIRST, DEV_FIRST = 90_000, 28_000 # tray.make_tasks("C", first=...): 640,000+ (training) / 590,000+ (dev)
+
+
+def log(s):
+ print(f"[{time.strftime('%H:%M:%S')}] {s}", flush=True)
+
+
+def x(p):
+ return str(Path(p).expanduser()) if p else p
+
+
+def cmd_tasks(a):
+ if a.kind == "bank":
+ t = JT.bank_tasks(a.n, a.seed, a.first)
+ elif a.kind == "H":
+ from nedm.so101_policy.vision import tray as TR
+ home = json.loads(Path(a.home_config).read_text()) if a.home_config else {}
+ t = TR.make_tasks("H", a.n, a.first, a.dev, log=log, home=home)
+ else:
+ from nedm.so101_policy.vision import tray as TR
+ t = TR.make_tasks("C", a.n, (DEV_FIRST if a.dev else TRAIN_FIRST) + a.first, a.dev, log=log)
+ from nedm.so101_policy.vec_env import reserved_seed_hits
+ if reserved_seed_hits(t["seeds"]):
+ raise ValueError("reserved seeds")
+ np.savez(a.out, **t)
+ log(f"-> {a.out}: {len(t['seeds'])} tasks, seeds {t['seeds'][0]}-{t['seeds'][-1]}")
+
+
+def cmd_mix(a):
+ from nedm.so101_policy.vision import tray as TR
+ from nedm.so101_policy.vec_env import reserved_seed_hits
+ tables = [dict(np.load(x(p_))) for p_ in a.inputs]
+ t = TR.mix_tasks(tables, a.counts, a.seed)
+ if reserved_seed_hits(t["seeds"]):
+ raise ValueError("reserved seeds")
+ t["mix_inputs"] = np.array([str(x(p_)) for p_ in a.inputs])
+ np.savez(a.out, **t)
+ log(f"-> {a.out}: {len(t['seeds'])} tasks, kinds {np.bincount(t['kind']).tolist()} ({t['kind_stage'].tolist()})")
+
+
+def cmd_starts(a):
+ """A PPO start bank (``vec_env.load_starts`` layout: q, qd, cube_pos, cube_quat, cube_v, cube_w; no goals, no seeds)
+ from start banks and TRAINING task files (their ``state_*`` rows): every row of input i ``--repeat[i]`` times, in
+ input order (the env draws rows uniformly, so the repeats set the mix). Refused: a sealed-test path, a bank with a
+ reserved seed, a task file with a reserved seed or ``dev`` set, a task file sharing a seed with an ``--exclude``
+ file (development / fresh sets). Rows above ``--roll-hi-deg`` are dropped (``JE.drop_high_roll``)."""
+ import math
+ from nedm.so101_policy.vec_env import reserved_seed_hits
+ rep = list(a.repeat or [1]) * (len(a.inputs) if len(a.repeat or [1]) == 1 else 1)
+ if len(rep) != len(a.inputs) or min(rep) < 1:
+ raise SystemExit("--repeat: one value (>= 1) or one per input")
+ ex = set()
+ for p_ in a.exclude or []:
+ ex |= set(np.asarray(np.load(x(p_))["seeds"]).tolist())
+ keys = ("q", "qd", "cube_pos", "cube_quat", "cube_v", "cube_w")
+ parts, src, rows = [], [], []
+ for i, (p_, k) in enumerate(zip(a.inputs, rep)):
+ if "test_sealed" in str(p_):
+ raise SystemExit(f"{p_}: the sealed test data must not be used for starts")
+ f = np.load(x(p_))
+ task = "goal_xy" in f.files
+ sd = [np.asarray(f[n]) for n in ("seeds", "seed") if n in f.files]
+ hits = sum(reserved_seed_hits(v) for v in sd)
+ if hits:
+ raise SystemExit(f"{p_}: {hits} reserved (validation / test) seeds")
+ if task:
+ if "dev" in f.files and bool(f["dev"]):
+ raise SystemExit(f"{p_}: a development task set")
+ if not sd:
+ raise SystemExit(f"{p_}: a task file without seeds")
+ ov = ex & set(sd[0].tolist())
+ if ov:
+ raise SystemExit(f"{p_}: {len(ov)} seeds are in the --exclude sets")
+ pre = "state_" if task else ""
+ d = {n: np.asarray(f[pre + n], np.float64) for n in keys}
+ m = len(d["q"])
+ parts.append({n: np.concatenate([v] * k) for n, v in d.items()})
+ src.append(np.full(m * k, i, np.int16))
+ rows.append(np.tile(np.arange(m), k))
+ log(f"{p_}: {m} rows x {k} ({'task file' if task else 'bank'})")
+ out = {n: np.concatenate([q[n] for q in parts]) for n in keys}
+ out["src_input"], out["src_row"] = np.concatenate(src), np.concatenate(rows)
+ if a.roll_hi_deg is not None:
+ t, n_drop = JE.drop_high_roll({n: torch.as_tensor(v) for n, v in out.items()},
+ math.radians(JE.roll_hi_config(a.roll_hi_deg)))
+ out = {n: v.numpy() for n, v in t.items()}
+ log(f"roll cap {a.roll_hi_deg:g} deg: {n_drop} rows dropped")
+ out["src_inputs"] = np.array([str(x(p_)) for p_ in a.inputs])
+ out["src_repeat"] = np.asarray(rep, np.int64)
+ np.savez(a.out, **out)
+ sh = np.bincount(out["src_input"], minlength=len(a.inputs)) / len(out["q"])
+ log(f"-> {a.out}: {len(out['q'])} rows, share per input {np.round(sh, 4).tolist()}, wrist roll max "
+ f"{math.degrees(float(out['q'][:, JE.ROLL].max())):.1f} deg")
+
+
+def cmd_expert(a):
+ from nedm.so101_policy.vision import teacher as TT
+ te = TT.Teacher(x(a.teacher))
+ if a.tasks:
+ t = dict(np.load(a.tasks))
+ else:
+ t = JT.bank_tasks(a.n, a.seed, a.first)
+ n = len(t["seeds"])
+ nz = np.zeros(n)
+ nz[int(round(n * (1 - a.noise_frac))):] = a.noise
+ d = JT.expert_collect(t, te, a.world, nz, a.seed, a.device, x(a.nrd_ckpt), a.workers, x(a.mj_python), a.horizon,
+ a.batch, log, record=not a.no_record)
+ np.savez_compressed(a.out, **d)
+ log(f"-> {a.out}: success {np.mean(d['success']) * 100:.1f} %, lenient {np.mean(d['lenient']) * 100:.1f} %")
+
+
+def cmd_bc(a):
+ data = JT.BCSet([x(p) for p in a.data], a.device, seed=a.seed)
+ log(f"bc data: {len(data.train_rows)} train rows, {len(data.val_rows)} val rows")
+ env_cfg = dict(JE.JointEnvConfig(ckpts=[x(a.nrd_ckpt)]).to_dict())
+ JT.train_bc(data, a.out, tuple(a.hidden), a.steps, a.batch, a.lr, seed=a.seed, log=log, env_cfg=env_cfg,
+ rate_noise=a.rate_noise)
+ (Path(a.out) / "args.json").write_text(json.dumps({k: v for k, v in vars(a).items() if k != "fn"}, indent=1))
+
+
+def load_tasks(path, n=0, first=0):
+ from nedm.so101_policy.vision.demos import load_tasks as lt
+ return lt(path, np.arange(first, first + n) if n else None)
+
+
+def cmd_eval(a):
+ jt = JE.JointTeacher(x(a.jt), a.device)
+ t = load_tasks(a.tasks, a.n, a.first)
+ B = len(t["seeds"])
+ fr = JT.resolve_floor_raise(a.floor_raise, jt, log, f"eval ({a.world})") # auto: the JT's own (v12)
+ env = JT.make_env(a.world, B, jt.codec, a.device, x(a.nrd_ckpt), a.workers, x(a.mj_python), a.horizon,
+ lead_clamp=not a.no_lead, floor_guard=not a.no_floor, hold_cap_s=a.hold_cap_s,
+ hold_obs_s=a.hold_obs_s, roll_hi_deg=a.roll_hi_deg, floor_raise=fr)
+ if env.dyn is not None: # $NEDM_SO101_DYN (joint_teacher.make_env)
+ log(f"robot dynamics ({a.world}, {B} worlds): {json.dumps(env.dyn_info()['cfg'])}")
+ if env.roll_hi is not None: # the wrist-roll cap (--roll-hi-deg)
+ log(f"roll cap: {json.dumps(env.roll_info())}")
+ if env.cfg.floor_raise is not None: # the action-layer floor raise (--floor-raise)
+ log(f"floor raise: the floor 1.5 mm above z = {list(env.cfg.floor_raise)} (c0 + c1 x + c2 y, m)")
+ from nedm.so101_policy import table as TB
+ plane, floor, _, moved = TB.from_cli(a)
+ if moved: # evaluation only: a lowered / tilted table (table.py)
+ log(f"table: {TB.describe(plane)}, floor {floor}: {json.dumps(env.set_table(plane, floor))}")
+ extra = TB.log_only_extra(env, a)
+ if extra:
+ log(f"log-only task rules: {env.tcfg.log_only}")
+ r = JT.run_tasks(env, t, jt, noise=a.noise, record_states=a.record_states, log=log,
+ floor_gap=a.floor_gap or env.cfg.floor_raise is not None) # the floor creep (v12; off: no key)
+ env.close()
+ if moved:
+ r["table"] = np.array(json.dumps(env.table_info()))
+ if extra:
+ r["log_only"] = np.array(json.dumps(list(env.tcfg.log_only)))
+ s = JT.summarize(r)
+ if env.dyn is not None: # robot dynamics of the evaluation ($NEDM_SO101_DYN, joint_teacher.make_env)
+ r["dyn"] = np.array(json.dumps(env.dyn_info()))
+ on = env.dyn.params()[:, 0].cpu().numpy() > 0.5
+ le = np.asarray(r["lenient"]).astype(bool)
+ s["lenient_perturbed"] = float(le[on].mean()) if on.any() else None
+ s["lenient_unperturbed"] = float(le[~on].mean()) if (~on).any() else None
+ elif env.tcfg.hold_cap_s != JE.T.TaskConfig.hold_cap_s or env.cfg.hold_obs_s:
+ r["hold_cap"] = np.array(json.dumps(dict(hold_cap_s=env.tcfg.hold_cap_s, hold_obs_s=env.cfg.hold_obs_s)))
+ r["summary"] = np.array(json.dumps(s))
+ r["jt"] = np.array(json.dumps(jt.info()))
+ r["world"] = np.array(a.world)
+ if JE.EVAL_KP_SCALE != 1.0: # $NEDM_SO101_EVAL_KP_SCALE (also when the robot dynamics are off)
+ r["kp_scale"] = np.float64(JE.EVAL_KP_SCALE)
+ if a.out:
+ np.savez_compressed(a.out, **r)
+ log(f"JT {a.world} ({B} tasks): {json.dumps(s)}")
+
+
+def cmd_eval_expert(a):
+ from nedm.so101_policy.vision import teacher as TT
+ te = TT.Teacher(x(a.teacher))
+ t = load_tasks(a.tasks, a.n, a.first)
+ d = JT.expert_collect(t, te, a.world, 0.0, 0, a.device, x(a.nrd_ckpt), a.workers, x(a.mj_python), a.horizon,
+ len(t["seeds"]), log, record=False)
+ s = JT.summarize(dict(success=d["success"], lenient=d["lenient"], end=d["end"],
+ success10=np.zeros_like(d["success"]), lifted=d["lifted"], end_xy=d["end_xy"]))
+ if a.out:
+ np.savez_compressed(a.out, **d, summary=np.array(json.dumps(s)))
+ log(f"current teacher + decoder v3, {a.world}: {json.dumps(s)}")
+
+
+def cmd_ppo(a):
+ from nedm.so101_policy import ppo as P
+ out = Path(a.out)
+ (out / "ckpt").mkdir(parents=True, exist_ok=True)
+ (out / "args.json").write_text(json.dumps({k: v for k, v in vars(a).items() if k != "fn"}, indent=1))
+ init = torch.load(x(a.init), map_location=a.device, weights_only=False)
+ codec = JE.Codec(np.asarray(init["env"]["codec"]["mean"]), np.asarray(init["env"]["codec"]["std"]))
+ env_over = json.loads(Path(a.env_config).read_text()) if a.env_config else {}
+ cfg = JE.JointEnvConfig.from_dict({**dict(world="nrd", num_envs=a.envs, device=a.device, seed=a.seed,
+ ckpts=[x(a.nrd_ckpt)]), **env_over})
+ env = JE.JointVecEnv(cfg, codec)
+ if env.roll_hi is not None: # the wrist-roll cap of the env config (roll_hi_deg): also in the dev evaluations
+ log(f"roll cap: {json.dumps(env.roll_info())}")
+ if env.rest is not None: # held-cube rest starts of the env config (rest; round v9)
+ log(f"rest starts: {json.dumps(env.rest_info())}")
+ if env.pause is not None: # the arm pause of the env config (pause)
+ log(f"pause: {json.dumps(asdict(cfg.pause))}")
+ if cfg.far_open is not None: # the jaw-open cost far from the goal (far_open; round v9)
+ log(f"far-open jaw cost: {json.dumps(asdict(cfg.far_open))}")
+ if cfg.arm_table is not None: # the kinematic arm-table end (arm_table; round v9c)
+ log(f"kinematic arm-table end: {json.dumps(asdict(cfg.arm_table))}")
+ if cfg.grasp_shift is not None: # the grasp target toward the fixed jaw (grasp_shift; round v11)
+ log(f"grasp shift: {json.dumps(asdict(cfg.grasp_shift))}")
+ if cfg.floor_raise is not None: # the action-layer floor raise (floor_raise; round v12): the dev evaluations too
+ log(f"floor raise: the floor 1.5 mm above z = {list(cfg.floor_raise)} (c0 + c1 x + c2 y, m)")
+ gs_last = env.gs_stats.clone()
+ tc = JT.ppo_train_cfg(json.loads(Path(a.train_config).read_text()) if a.train_config else None)
+ tc["seed"] = a.seed
+ pk = dict(init["policy_kwargs"])
+ pk.update(init_std=tc["init_std"])
+ pol = P.Policy(**pk).to(a.device)
+ sd = init["policy"]
+ own = pol.state_dict()
+ for k in ("std",):
+ sd = {**sd, k: own[k]}
+ pol.load_state_dict(sd)
+ ref = None
+ if a.bc_coef > 0:
+ import copy
+ ref_pol = copy.deepcopy(pol).eval()
+ for p_ in ref_pol.parameters():
+ p_.requires_grad_(False)
+ ref = lambda o: ref_pol.actor(o) # noqa: E731 (normalised obs)
+ algo = JT.JointPPO(env, pol, tc, ref, a.bc_coef, a.critic_warmup)
+ start = 0
+ if a.resume:
+ d = algo.load(x(a.resume))
+ start = algo.iteration
+ curve = P.CurveWriter(out / "learning_curve.csv")
+ dev_t = load_tasks(a.dev_tasks) if a.dev_tasks else None
+ # more development sets (--dev-tasks-extra): the same evaluation, in the log and dev_evals.jsonl only
+ dev_x = [(Path(p_).stem, load_tasks(p_)) for p_ in a.dev_tasks_extra or []]
+ if dev_x and dev_t is None:
+ raise SystemExit("--dev-tasks-extra needs --dev-tasks")
+ dev_kw = {} # --dev-match-env: the training env's episode length, hold cap and held-time scale
+ if a.dev_match_env:
+ dev_kw = dict(horizon=int(cfg.horizon), hold_cap_s=env.tcfg.hold_cap_s, hold_obs_s=float(cfg.hold_obs_s))
+ log(f"dev evaluations: {json.dumps(dev_kw)} (the training env's)")
+ fgap = cfg.floor_raise is not None # v12: the dev evaluations log the floor creep before the lift (review F2)
+ dev_cols = [] # the dev columns in every CSV row (the header is the first row's keys: empty
+ if dev_t is not None and fgap: # before the first dev evaluation; v12 floor-raise runs only)
+ dev_cols = ["dev_nrd_lenient", "dev_nrd_strict"] + (["dev_nrd_roll_cmd_over"] if cfg.roll_hi_deg is not None
+ else []) + ["dev_nrd_floor_gap_p50_mm",
+ "dev_nrd_floor_gap_p10_mm"]
+ t0 = time.time()
+ for it in range(start, a.iterations):
+ row = algo.iterate()
+ dev_more = []
+ if dev_t is not None and (algo.iteration % a.eval_every == 0 or algo.iteration == a.iterations):
+ jt_path = out / "ckpt" / f"model_{algo.iteration:05d}.pt"
+ algo.save(jt_path)
+ jt = JE.JointTeacher(jt_path, a.device)
+ rec = dict(iteration=algo.iteration, sets={})
+ for k_, (name, tt) in enumerate([(Path(a.dev_tasks).stem, dev_t)] + dev_x):
+ ev = JT.make_env("nrd", len(tt["seeds"]), jt.codec, a.device, x(a.nrd_ckpt),
+ roll_hi_deg=cfg.roll_hi_deg, floor_raise=cfg.floor_raise, **dev_kw)
+ r = JT.run_tasks(ev, tt, jt, floor_gap=fgap)
+ ev.close()
+ s = JT.summarize(r)
+ rec["sets"][name] = s
+ gap_txt = (f" floor gap p50 {s['floor_gap_mm_p50']:+.1f} p10 {s['floor_gap_mm_p10']:+.1f} mm"
+ if "floor_gap_mm_p10" in s else "")
+ if k_ == 0: # the first set: the learning curve's dev columns (as before)
+ row["dev_nrd_lenient"], row["dev_nrd_strict"] = s["lenient"], s["strict"]
+ if "roll_cmd_over" in s:
+ row["dev_nrd_roll_cmd_over"] = s["roll_cmd_over"]
+ if "floor_gap_mm_p10" in s:
+ row["dev_nrd_floor_gap_p50_mm"] = s["floor_gap_mm_p50"]
+ row["dev_nrd_floor_gap_p10_mm"] = s["floor_gap_mm_p10"]
+ dev_more.insert(0, gap_txt)
+ else:
+ dev_more.append(f" | {name} len {s['lenient']:.2f} strict {s['strict']:.2f}"
+ + (f" roll over {s['roll_cmd_over']:.2f} at cap {s['roll_q_at_cap']:.2f}"
+ if "roll_cmd_over" in s else "") + gap_txt)
+ with open(out / "dev_evals.jsonl", "a") as f_: # every dev set's summary (the CSV keeps its header)
+ f_.write(json.dumps(rec) + "\n")
+ for k_ in dev_cols: # (v12 floor-raise runs: the dev columns in the header, empty between evaluations)
+ row.setdefault(k_, None)
+ gs_txt = ""
+ if cfg.grasp_shift is not None: # this iteration's grasp-shift events (training rollouts)
+ g_ = (env.gs_stats - gs_last).tolist()
+ gs_last = env.gs_stats.clone()
+ n1, n2 = max(g_[0], 1.0), max(g_[3], 1.0)
+ row.update(gs_n_descent=g_[0], gs_hx_descent_mm=g_[1] / n1 * 1e3, gs_err_descent_mm=g_[2] / n1 * 1e3,
+ gs_n_close=g_[3], gs_hx_close_mm=g_[4] / n2 * 1e3, gs_err_close_mm=g_[5] / n2 * 1e3,
+ gs_cost=g_[6])
+ gs_txt = (f" | grasp shift: descent n {g_[0]:.0f} hx {row['gs_hx_descent_mm']:+.1f} |err| "
+ f"{row['gs_err_descent_mm']:.1f} mm, close n {g_[3]:.0f} hx {row['gs_hx_close_mm']:+.1f} |err| "
+ f"{row['gs_err_close_mm']:.1f} mm, cost {g_[6]:.1f}")
+ curve.write(row)
+ log(f"it {algo.iteration}: succ {row['success']:.3f} len {row['lenient']:.3f} lifted {row['lifted']:.3f} "
+ f"kl {row['kl']:.4f} lr {row['lr']:.2e} vloss {row['value_loss']:.4f} std {row['std_move']:.3f}/"
+ f"{row['std_trigger']:.3f} {row['world_steps_per_s']:.0f} st/s"
+ + (f" | roll over cap {row['roll_cmd_over']:.3f}" if "roll_cmd_over" in row else "")
+ + (f" | dev nrd len {row['dev_nrd_lenient']:.2f} strict {row['dev_nrd_strict']:.2f}"
+ if row.get("dev_nrd_lenient") is not None else "")
+ + (f" roll over {row['dev_nrd_roll_cmd_over']:.2f}"
+ if row.get("dev_nrd_roll_cmd_over") is not None else "")
+ + "".join(dev_more)
+ + (f" | rest starts {env.rest_n}/{env.rest_resets}" if env.rest is not None else "")
+ + (f" | pauses {env.pause.started}" if env.pause is not None else "")
+ + (f" | far-open cost {float(env.far_open_sum):.1f}" if cfg.far_open is not None else "")
+ + (f" | arm-table rule ends {int(env.arm_table_n)}" if cfg.arm_table is not None else "")
+ + gs_txt)
+ if algo.iteration % a.save_every == 0 or algo.iteration == a.iterations:
+ algo.save(out / "ckpt" / f"model_{algo.iteration:05d}.pt")
+ algo.save(out / "ckpt" / "last.pt")
+ log(f"done in {(time.time() - t0) / 60:.1f} min")
+
+
+def main(argv=None):
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = p.add_subparsers(dest="cmd", required=True)
+
+ def common(q):
+ q.add_argument("--device", default="cuda")
+ q.add_argument("--nrd-ckpt", default=NRD)
+ q.add_argument("--teacher", default=TEACHER)
+ q.add_argument("--workers", type=int, default=8)
+ q.add_argument("--mj-python", default=MJ_PY)
+ q.add_argument("--horizon", type=int, default=400)
+ q.add_argument("--seed", type=int, default=0)
+
+ q = sub.add_parser("tasks")
+ q.add_argument("--kind", choices=("C", "bank", "H"), default="C")
+ q.add_argument("--n", type=int, required=True)
+ q.add_argument("--first", type=int, default=0)
+ q.add_argument("--dev", action="store_true")
+ q.add_argument("--seed", type=int, default=0)
+ q.add_argument("--home-config", default="", help="kind H: JSON with home_deg, noise_deg, bank")
+ q.add_argument("--out", required=True)
+ q.set_defaults(fn=cmd_tasks)
+
+ q = sub.add_parser("mix")
+ q.add_argument("--inputs", nargs="+", required=True)
+ q.add_argument("--counts", type=int, nargs="+", required=True)
+ q.add_argument("--seed", type=int, default=0)
+ q.add_argument("--out", required=True)
+ q.set_defaults(fn=cmd_mix)
+
+ q = sub.add_parser("starts")
+ q.add_argument("--inputs", nargs="+", required=True, help="start banks (.npz) and training task files")
+ q.add_argument("--repeat", type=int, nargs="+", default=[1], help="times every row of input i (one or per input)")
+ q.add_argument("--exclude", nargs="*", default=[], help="task files (dev / fresh) no task-file seed may be in")
+ q.add_argument("--roll-hi-deg", type=float, default=None, help="drop rows with the wrist roll above (sim deg)")
+ q.add_argument("--out", required=True)
+ q.set_defaults(fn=cmd_starts)
+
+ q = sub.add_parser("expert")
+ common(q)
+ q.add_argument("--world", default="nrd")
+ q.add_argument("--tasks", default="")
+ q.add_argument("--n", type=int, default=1024)
+ q.add_argument("--first", type=int, default=0)
+ q.add_argument("--noise-frac", type=float, default=0.5)
+ q.add_argument("--noise", type=float, default=1.0)
+ q.add_argument("--batch", type=int, default=1024)
+ q.add_argument("--no-record", action="store_true")
+ q.add_argument("--out", required=True)
+ q.set_defaults(fn=cmd_expert)
+
+ q = sub.add_parser("bc")
+ common(q)
+ q.add_argument("--data", nargs="+", required=True)
+ q.add_argument("--out", required=True)
+ q.add_argument("--hidden", type=int, nargs="+", default=[512, 256, 128])
+ q.add_argument("--steps", type=int, default=20000)
+ q.add_argument("--batch", type=int, default=4096)
+ q.add_argument("--lr", type=float, default=1e-3)
+ q.add_argument("--rate-noise", type=float, default=0.0)
+ q.set_defaults(fn=cmd_bc)
+
+ q = sub.add_parser("eval")
+ common(q)
+ q.add_argument("--jt", required=True)
+ q.add_argument("--tasks", required=True)
+ q.add_argument("--world", default="mujoco")
+ q.add_argument("--n", type=int, default=0)
+ q.add_argument("--first", type=int, default=0)
+ q.add_argument("--noise", type=float, default=0.0)
+ q.add_argument("--no-lead", action="store_true")
+ q.add_argument("--no-floor", action="store_true")
+ q.add_argument("--record-states", action="store_true")
+ q.add_argument("--hold-cap-s", type=float, default=None, help="the hold_cap rule (s held in the air; default 3.5)")
+ q.add_argument("--hold-obs-s", type=float, default=0.0,
+ help="held-time scale of the JT observation (s; 0: the task's, 3.5 with another --hold-cap-s)")
+ q.add_argument("--roll-hi-deg", type=float, default=None,
+ help="the wrist-roll target cap (sim deg; the real roll ends at 101.2); default off")
+ q.add_argument("--floor-raise", default="auto",
+ help="the action-layer floor raise (joint_env.JointEnvConfig.floor_raise): 'auto' (default) = the "
+ "JT's own (its checkpoint's env record; none = off, the old behaviour), '0' = off, "
+ "'c0,c1,c2' (m, the floor 1.5 mm above z = c0 + c1 x + c2 y at the grasp point; a negative "
+ "first value: --floor-raise=-0.005,0,0) or one height (m); another value than the JT's own "
+ "is logged as a WARNING. MuJoCo evaluations of a JT: --device cpu (or the GPU lock)")
+ q.add_argument("--floor-gap", action="store_true",
+ help="record floor_gap_prelift (the lowest measured gripper point above the action layer's floor "
+ "before the lift; on by itself with a floor raise)")
+ q.add_argument("--out", default="")
+ from nedm.so101_policy import table as TB
+ TB.add_cli(q)
+ q.set_defaults(fn=cmd_eval)
+
+ q = sub.add_parser("eval-expert")
+ common(q)
+ q.add_argument("--tasks", required=True)
+ q.add_argument("--world", default="mujoco")
+ q.add_argument("--n", type=int, default=0)
+ q.add_argument("--first", type=int, default=0)
+ q.add_argument("--out", default="")
+ q.set_defaults(fn=cmd_eval_expert)
+
+ q = sub.add_parser("ppo")
+ common(q)
+ q.add_argument("--init", required=True)
+ q.add_argument("--out", required=True)
+ q.add_argument("--envs", type=int, default=4096)
+ q.add_argument("--iterations", type=int, default=200)
+ q.add_argument("--env-config", default="")
+ q.add_argument("--train-config", default="")
+ q.add_argument("--bc-coef", type=float, default=0.0)
+ q.add_argument("--critic-warmup", type=int, default=10)
+ q.add_argument("--dev-tasks", default="")
+ q.add_argument("--dev-tasks-extra", nargs="+", default=None,
+ help="more development sets (same evaluation; the log and dev_evals.jsonl, not the CSV)")
+ q.add_argument("--dev-match-env", action="store_true",
+ help="dev evaluations with the env config's horizon, hold cap and held-time scale (default: 400 "
+ "steps and the task defaults)")
+ q.add_argument("--eval-every", type=int, default=10)
+ q.add_argument("--save-every", type=int, default=10)
+ q.add_argument("--resume", default="")
+ q.set_defaults(fn=cmd_ppo)
+
+ a = p.parse_args(argv)
+ a.fn(a)
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
diff --git a/so101_pick_place/code/so101_pick_place/README.md b/so101_pick_place/code/so101_pick_place/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..4e49d902936e941cb485252331b2b76917994082
--- /dev/null
+++ b/so101_pick_place/code/so101_pick_place/README.md
@@ -0,0 +1,463 @@
+# SO101 pick and place: a camera policy trained only in the NRD, tested on the real arm
+
+One camera policy (the "student") drives a real SO101 arm. It picks a 30 mm cube from the table and puts it on a
+plate. Every training step ran inside the NRD, a learned simulator of the arm and the cube (a contact NRD of the
+design in [`../contact_nrd/`](../contact_nrd/README.md)). The chain has four parts:
+
+1. NRD: the arm and cube dynamics, learned from CPU MuJoCo episodes.
+2. Teacher: a state policy (it sees the true cube pose), trained with PPO in the NRD.
+3. Student: a camera policy, trained in the NRD with ray-traced images of a calibrated copy of the real scene. The
+ student drives and the teacher gives the labels (online DAgger).
+4. Real arm: the student runs with no further training.
+
+No real image was a training sample. Real data set the simulator, the training worlds and the checks:
+
+- the camera calibration and the look of the scene (from two LeRobot teleop recordings) and the table height;
+- from S3 on, robot-like servo ranges in the student's training worlds (speed, lag and sag, set from robot timing
+ logs), the wrist-roll limit of 98 deg (T5 / S4: from the motor range and two robot stalls) and the 10 mm lower
+ table (T6 / S5: the measured real mat is 8-17 mm below the sim table at the cube and plate positions);
+- a fitted servo model (used only in the sim checks) and the choice of the student for the robot test.
+
+Each fine-tune round (S3, T5 / S4, T6 / S5) answered failures of the student before it on the robot. Section
+"Real-data inputs" lists where each input came from.
+
+This is follow-on work to the NeDM paper, not part of it. The study history (every stage commit named below) is the
+branch `so101-pick-place-study` (tip `3599103704032ba67cb2736ff0aee501f2e537b9`). The data, checkpoints, robot logs
+and videos are in the folder `so101_pick_place/` of the Hugging Face dataset (section "Data").
+
+## Results on the real arm
+
+Released student: run `v12_tb10_s1210`, checkpoint `it_01000` ("tb10"), SHA-256 `6458a4f791d10521...`. It was
+trained for a fixed table 10 mm lower than the nominal sim table. D ("reference") is the previous robot student and
+the start checkpoint of tb10: run `v8_roll_s801`, checkpoint `it_02000` (SHA-256 `d9a35bfc...`). "Placed" = the
+operator typed `p` (cube on the plate). Intervals: Wilson 95 %. Source of the counts: the 19 session logs on the Hub
+(`robot/logs/`), counted by `scripts/so101_pick_place/robot/build_results.py` (per-episode table:
+[`results/robot_results.md`](results/robot_results.md)). Source of the cube and plate positions, the directions and
+the end distances: the Hub file `results/robot/stress_episodes.json`, an image + kinematics estimate whose script
+was not found (it is not released).
+
+| Test (2026-10-27 unless stated) | Student | Placed | 95 % interval |
+|---|---|---|---|
+| Stress test, 6 sessions | tb10 | **36/50 = 72 %** | 58-83 % |
+| Stress test, plate left of the cube (R->L) | tb10 | 19/23 = 83 % | 63-93 % |
+| Stress test, plate right of the cube (L->R) | tb10 | 17/27 = 63 % | 44-78 % |
+| Screening, 4 episodes | tb10 | 4/4 | 51-100 % |
+| Screening, 7 students, 4 episodes each (D 8) | all | 22/32 = 69 % (note 1) | 51-82 % |
+| All sessions 2026-10-24 to 10-27 | D | 19/28 = 68 % (note 1) | 49-82 % |
+
+Stress test, per session (in time order): 8/10, 2/2, 5/8, 7/10, 8/10, 6/10.
+
+- Protocol, as run (it was not fixed before the test): the plate stayed in one place in each of the first 5 sessions
+ (sessions `150916` and `151136` share one place); in the last session it was moved twice (3 places). Plate centre
+ (mm from the base pan axis / deg): `145520` 200 / +18; `150916` + `151136` 189 / +31; `151953` 188 / -19; `153045`
+ 177 / -29; `153943` ep 1-4 204 / -11, ep 5-8 154 / -15, ep 9-10 170 / +19. The cube was moved to many positions:
+ 177-289 mm from the base pan axis, -47 to +40 deg, cube yaw about 0. One start that stopped at the home pose before
+ the policy ran is not counted (`eval_20261027_150916/ep_03`). The study's note `STRESS_tb10_20261027.md` says the
+ plate moved once; the positions above show two moves.
+- Placed cubes: distance from the cube's end position to the plate centre (image + kinematics estimate) p50 20 mm,
+ max 29 mm; the plate is a square with 50 mm sides (25 mm from the centre to an edge).
+- Cubes closer than 19 cm to the pan axis: 1/7 placed. Cubes 19-29 cm: 35/43. 48 of the 50 cubes were inside the
+ training range 15-27 cm (35/48 placed).
+- D per day: 6/8, 6/8, 2/4, 5/8.
+- Note 1: in two of D's episodes the operator typed `p` with a note that the cube was off the plate or the mat
+ (`eval_20261027_133039/ep_02` "GLP PLACE OFF MAT", `eval_20261024_205852/ep_02` "GLP BUT PLACE IN THE WRONG
+ SPOT"). Without them: D 17/28, screening 21/32 (D 4/8). tb10's notes have no such case: 3 placed tb10 episodes are
+ typed "GLP OFF" (end distance 22-29 mm) and 13 "GLP BIT OFF"; all count as placed.
+
+| Stress-test failure (14 of 50) | Episodes | Direction |
+|---|---|---|
+| Held the cube at the plate, no release (carry stop) | 6 | 5 L->R, 1 R->L |
+| Grasp failed | 5 | 3 R->L (3 of the last 4 episodes of session `151136`: ep 5, 7, 8), 2 L->R (far cubes, 260 and 278 mm) |
+| Released short of the plate | 3 | 3 L->R |
+
+Screening (2026-10-27 13:30-14:04; 4 episodes per student, D at the start and at the end; the names are those of
+`results/sim_checks/LAB_PLAN_v13.md` on the Hub):
+
+| Student | Placed |
+|---|---|
+| D (reference, 2 rounds) | 5/8 |
+| tb10: table 10 mm lower, 1,000 steps (released) | 4/4 |
+| visual fix, seed 1231, 500 steps (`visR500`) | 2/4 |
+| visual fix, seed 1304, 750 steps (`visR_s1304 it750`) | 3/4 |
+| visual fix + table 5 mm lower, seed 1301, 500 steps (`visRtb05_s1301 it500`) | 2/4 |
+| table 5 mm lower, 1,500 steps (`tb05`) | 3/4 |
+| real-look gripper, no randomisation, 250 steps (`visR0_250`) | 3/4 |
+
+Only tb10 and D are released. The other five students are students of the v12 and v13 runs (2026-10-26/27).
+
+### How tb10 was chosen
+
+- The frozen sim rule of its round (`results/sim_checks/SELECTION_v12.md` on the Hub) passed no student. tb10 failed
+ G1 (3.5 %, nominal sim table; expected for a student trained for a lower table) and the place line of G3 +3 mm
+ (94 places, line 144.9) (`results/sim_checks/SELECTION_RESULT_v12.md`).
+- At the user's request, a relaxed lab rule (`LAB_PICK_RULE_v13.md`) was written on 2026-10-27 at 09:30, before the
+ new gate results of that day. The v12 gate results of all 24 checkpoints, tb10's among them, were known when it was
+ written. Its G3 place line is 90, and students trained for a lower table are exempt from G1, so tb10 passed just
+ above the line (94).
+- Five students met the lab rule, which allowed four. tb10 was the optional fifth ("opt. A" in `LAB_PLAN_v13.md`) and
+ ran after D's closing round. One screened student (`visR0_250`, "opt. B") did not meet the lab rule (grasps 171,
+ line 172).
+- The user then chose tb10 for the stress test. The 50 stress episodes are new episodes, but the choice used robot
+ results, and the stress protocol was not fixed in advance.
+
+## Sim checks of the released student
+
+Frozen runner of the round (`check_eval.py` sha256 `f70011ab`), AMD MI350X, CPU MuJoCo with GPU renders. J224 = the
+224 task layouts (cube and plate) of the robot sessions; on them the check counts grasps, places and carry stops
+(the arm holds the cube at the plate and does not release it), with the measured table plane, a flat robot floor,
+the fitted servo model and 40 s episodes. D's reference: G2 = mean of 3 D runs; G3 = one D run each. Source:
+`results/sim_checks/v12_tb10_s1210_it1000.json`, `D_reference.json`.
+
+| Check | tb10 | D | Rule | Result |
+|---|---|---|---|---|
+| G1: success on the nominal sim table, 200 tasks (%) | 3.5 | 99.0 | D - 3 | fail (expected: trained for a table 10 mm lower) |
+| G2: J224, grasps / places / carry stops | 184 / 143 / 4 | 193 / 156 / 28.7 | D -10.5 / -13.9 / +12.1 | pass |
+| G2 per direction, L->R (112 tasks): grasps / places, sim rule / places, robot rule / carry stops | 101 / 63 / 85 / 4 | 102.7 / 78 / 90.3 / 18.0 | report | |
+| G2 per direction, R->L (112 tasks) | 83 / 80 / 83 / 0 | 90.3 / 78 / 85.7 / 10.7 | report | |
+| G3: table plane -3 mm | 181 / 154 / 1 | 170 / 126 / 22 | D -12.9 / -17.1 / +14.9 | pass |
+| G3: table plane +3 mm | 180 / 94 / 3 | 184 / 162 / 13 | same | fail (places) |
+| Release check: grasp releases at the 68 real hold starts x 4 draws, 2 seed blocks | 0 / 0 | 0 / 0 | 2+ starts in both blocks vetoes | no veto |
+
+- In-run evaluation of the run (CPU MuJoCo, training plane, decision 1,500; there is none at 1,000): 97 % lenient /
+ 92 % strict on `dev100` (100 fixed tasks with random cube starts), 98 % / 94 % on `home45_dev100` (100 tasks that
+ start at the robot's HOME pose, wrist roll 45 deg) (`student/s5_v12_tb10_s1210/progress.jsonl`). Lenient = the cube
+ released and at rest inside the 50 mm goal square, any yaw; strict = within 15 mm and 15 deg of the goal.
+- By the sim place rule, G2 shows a weaker L->R side (63 vs 80 of 112), like the robot (63 % vs 83 %); by the looser
+ robot place rule it does not (85 vs 83). The G2 row uses the sim rule (63 + 80 = 143).
+- There is no sealed sim test of the student.
+
+## The NRD
+
+| Item | Value |
+|---|---|
+| Design | Contact NRD of `contact_nrd/` (stored name `contact_graph_nrd_v6`): core, collision and contact networks, width 128, 4 heads, FFN 512, 4 layers, history 4, step 20 ms, 2,424,735 parameters |
+| State | Arm 12 (6 joint angles, 6 joint rates), cube 13 (position, quaternion, velocity, angular velocity); the rates are 20 ms step averages |
+| Action | 6 joint position targets |
+| Contact pairs | fixed jaw - cube, moving jaw - cube, cube - table |
+| Base NRD `c0_s62` | From scratch, seed 62, on `production_plus` (37,500 scripted episodes); best check at update 100,000; 8.5 GPU-h (AMD MI350X) |
+| Policy NRD `c1_s62` | `c0_s62` fine-tuned, 20,000 updates at lr 1e-4, on the 4 data parts merged (train rows of `policy_v3` x 2.5); best check at update 2,500; 1.6 GPU-h. Every teacher and student stage ran in it |
+
+| Data part (Hub `nrd_data/`) | Episodes (train / validation) | Records | What |
+|---|---|---|---|
+| `production_plus` | 34,647 / 2,853 | 49.3 h | Scripted grasps, 12 families (nominal, off-centre, one-sided, near miss, weak closure, drop, push and 5 probe families) |
+| `noisy_v1` | 9,000 / 1,000 | 15.6 h | Scripted plans with policy-like command noise |
+| `expert_v2` | 24,684 / 2,079 | 30.9 h | A scripted expert through the study's action decoder |
+| `policy_v3` | 17,749 / 1,482 | 25.4 h | 7 PPO policies of the study, rolled out in MuJoCo (`policies/` holds them) |
+
+All parts: CPU MuJoCo 3.15.0, 0.5 ms physics step, records every 10 ms, 4 s episodes; 93,494 episodes, 121 h.
+
+Released files. Main's `nedm.contact_nrd.model.load_model` cannot load the files the study used: they hold two
+training-only geometry heads (config key `aux_geometry`, tensors `geo_collision.*`, `geo_contact.*`, 3,096
+parameters) that the step never uses. The release has both:
+
+| Hub file | SHA-256 (16) | Loads with main's code | Use |
+|---|---|---|---|
+| `nrd/c1_s62/best.pt` | `2d1a24926d463c54` | yes | the policy NRD for every step of this release |
+| `nrd/c1_s62/original/best.pt` | `f45ee8be2c1bb1e6` | no (training code, commit `f6f05c21c`) | the file the study used |
+| `nrd/c0_s62/best.pt` | `01c44cd0424d4f0b` | yes | the base NRD |
+| `nrd/c0_s62/original/best.pt` | `c2b44e7f89e617d5` | no | the base NRD as trained; the `init_from` of the fine-tune |
+
+The main-compatible file is the original with only the key and the 4 tensors removed
+(`scripts/so101_pick_place/nrd/strip_ckpt.py`); every other entry is equal bit for bit. Check
+(`scripts/so101_pick_place/nrd/equiv.py`, `equiv_compare.py`): the original in the training code and the new file in
+main's code give bit-identical 100-step rollouts (from the first state and from the recorded history at step 100),
+contact switches and task metrics on 256 validation episodes (64 of each data part, `subsets.py`), on CPU and on the
+GPU. `reproduce.sh` step `nrd_strip` repeats the strip (bytes equal to the released file with torch 2.12) and this
+check.
+
+Sealed test: 3,050 scripted episodes (Hub `nrd_test/`, SHA-256 `657e3b47`, same collector, another master seed),
+run once on 2026-10-27 with main's `python -m nedm.contact_nrd.test` unchanged (RTX 5090, 104 s). The 7 scored
+families (`select: true`): 2,000 test episodes; validation = the 1,803 validation episodes of `production_plus` in
+those families, scored by the same code on the same GPU. "1 s windows": 1 s rollouts from the recorded 4-state
+history, started every 0.5 s. "4 s": one rollout from the first recorded state. Source: Hub `results/nrd/`; table by
+`scripts/so101_pick_place/nrd/summarize.py`. `reproduce.sh` steps `nrd_test` (test columns) and `nrd_val` (validation
+columns, needs `--with-nrd-data`) rebuild both.
+
+| Metric | c0 validation | c0 test | c1 validation | c1 test |
+|---|---|---|---|---|
+| Cube position, 1 s windows, p50 / p95 (mm) | 0.16 / 3.26 | 0.16 / 3.48 | 0.21 / 4.04 | 0.22 / 4.13 |
+| Cube angle, 1 s windows, p95 (deg) | 2.98 | 2.94 | 3.06 | 3.04 |
+| Arm joint RMS, 1 s windows, p95 (mrad) | 3.61 | 3.63 | 2.31 | 2.37 |
+| Cube position at 4 s, p50 / p95 (mm) | 1.20 / 8.57 | 1.20 / 9.41 | 1.34 / 10.42 | 1.37 / 11.03 |
+| Wrong contact events per recorded event | 0.338 | 0.341 | 0.351 | 0.356 |
+| Lift / drop disagreement (%) | 1.44 / 0.50 | 1.55 / 0.65 | 2.55 / 0.94 | 2.45 / 0.90 |
+| Selection score (lower is better) | 11.77 | 12.58 | 13.27 | 13.68 |
+
+| Family: cube position, 1 s windows, p95 (mm) | nominal | off_centre | one_sided | near_miss | weak_closure | drop | push |
+|---|---|---|---|---|---|---|---|
+| c0 validation / test | 2.14 / 2.16 | 3.04 / 3.14 | 2.51 / 2.34 | 9.94 / 10.03 | 13.08 / **37.14** | 4.41 / 5.56 | 9.08 / 7.47 |
+| c1 validation / test | 2.81 / 2.95 | 4.75 / 4.40 | 2.88 / 3.18 | 10.95 / 9.49 | 46.72 / 47.13 | 4.86 / 5.46 | 9.88 / 8.39 |
+
+- The test agrees with validation. One outlier: base NRD weak_closure goes from 13.1 to 37.1 mm (the p95 of only 125
+ episodes).
+- All 12 families (3,050 episodes): 1 s cube p95 3.84 mm (c0), 4.61 mm (c1).
+- The policy NRD's own validation set (19 selected families of its 4 data parts, 4,922 episodes, with the expert,
+ noisy-command and policy episodes): 1 s cube p95 8.40 mm, cube angle p95 4.08 deg, 4 s cube p95 14.37 mm (training
+ record `nrd/c1_s62/validation.json`; the merged training file is not released, so no step rebuilds it). It has no
+ test counterpart: the test set has only scripted families.
+- Neither NRD was selected with the test set. The test set is not fully blind: it was run once before (2026-10-10)
+ on an older NRD design, and the base NRD's config was made after that run.
+- Closed loop in the policy NRD, 3 PPO policies trained outside the NRD (among them a MuJoCo Warp policy and a
+ kinematic-world policy) reach 87.5 / 78.9 / 82.0 % on 256 tasks (in MuJoCo 96.5 / 93.0 / 96.9 %, study notes, not
+ re-checked), and the scripted expert 91.3 % on 1,024 tasks.
+
+## Teacher and student
+
+| | Teacher (T2-T6) | Student |
+|---|---|---|
+| Inputs | Privileged state: arm joints and rates, true cube pose and velocity, goal | Two RGB images, 224 x 224: a crop (52, 103, 288, 288) of the external camera and the full wrist camera; joint angles and rates. Two ResNet18 encoders (ImageNet start in S0) |
+| Output | Joint targets | A chunk of 10 joint targets; 5 are executed per query (every 100 ms) |
+| Training world | The NRD, 8,192 worlds | The NRD, 1,024 worlds, with ray-traced images of the calibrated scene (Newton / Warp ray tracer; batches of 128 worlds) |
+| Labels | PPO reward | The teacher's targets at the states the student reaches (online DAgger) |
+
+What each robot-round fine-tune added (configs in `configs/so101_policy/`):
+
+- S3: robot-like servos in 80 % of the student's worlds (speed 0.3-1 x, lag 20-150 ms, sag up to 1.5 deg), image
+ lag of 1-4 frames, and teacher labels at the commanded speed.
+- T5 / S4: a wrist-roll limit of 98 deg (the real servo range).
+- T6: the action floor (the lowest target height the action layer allows) 10 mm higher, on the sim table.
+- S5: one fixed flat table 10 mm below the sim table in every world (the images show it; the real mat is lower),
+ the action floor flat in the student's observed frame, and T6 as the labelling teacher.
+
+T0 is a decoder policy: it outputs commands of a scripted action decoder. T1 records 24,576 NRD episodes of T0
+through the decoder; T2 learns joint targets from them by behaviour cloning.
+
+## Training chain
+
+Each teacher starts from the teacher above it; each student starts from the student above it. GPU: one AMD MI350X per
+job (S3: MI300X; T1 and T2: one RTX 5090). Commits are on the branch `so101-pick-place-study`. A GPU re-run gives a
+similar, not an equal, checkpoint. Re-run types:
+
+- "same code": this branch runs the code of the stage (options added later are off).
+- "probably same code": the configs are equal and later options are off, but the stage's commit is inferred and no
+ bit-identity test covers the commits in between.
+- "same recipe": the commit of the stage is known only from file times.
+- "recipe only": the code of the stage is in no commit or was changed later.
+
+| Stage | Run | Start | Labels | Length | Checkpoint (SHA-256) | GPU-h | Commit | Re-run |
+|---|---|---|---|---|---|---|---|---|
+| NRD c0 | `full_ns_rk_cc_geo_cs_s62_plus` | nothing | - | 100,000 of 120,000 updates | `best.pt` (`c2b44e7f`) | 8.5 | uncommitted (`provenance/code_v16_base_nrd.tar.gz` on the Hub) | recipe only |
+| NRD c1 | `nrd_ft_c1_s62` | NRD c0 | - | update 2,500 of 20,000 | `best.pt` (`f45ee8be`) | 1.6 | `f6f05c21c` | same code (study branch) |
+| T0 | `nC1_s62_b` | nothing (PPO) | - | 171 iterations, 448 M steps | `model_00171.pt` (`8069d5b3`) | 3.3 | `e205b801b` + NRD code of `f6f05c21c` | same code |
+| T1 | expert e0 / e1 / e2 | T0 | - | 3 x 8,192 NRD episodes | `e0_n1.npz`, `e1_n2.npz`, `e2_n15.npz` | 0.6 | uncommitted (close to `6ea7ddb6e`) | recipe only |
+| T2 | `bc_all` | nothing (BC) | T1 | 60,000 steps | `bc.pt` (`95df5ff7`) | 0.05 | uncommitted (close to `6ea7ddb6e`) | recipe only |
+| T3 | `jt_ppo_b_v3` | T2 | - | 140 iterations | `model_00140.pt` (`41693858`) | 0.9 | about `6ea7ddb6e` (not exact) | recipe only |
+| T4 | `jt_ppo_h_hold25` | T3 | - | 110 iterations, hold limit 2.5 s | `model_00110.pt` (`0c1b6142`) | 0.4 | `6ea7ddb6e` (by file times) | same recipe (commit by file times) |
+| T5 | `tppo_roll_v8_s21` | T4 | - | 200 iterations, roll limit 98 deg | `model_00200.pt` (`c4ea842c`) | 0.8 | `46f74a797` | same code |
+| T6 | `tppo_v12_fr10_s122` | T5 | - | 200 iterations, floor raised 10 mm | `model_00200.pt` (`069cd896`) | 0.8 | `24b71df62` | same code |
+| S0 | `v2_start_s2` | ImageNet ResNet18 | T4 | 4,096 + 2 x 2,048 episodes; 10,000 + 2 x 4,000 steps | `r2/last.pt` (`3fe3fb5a`) | 0.5 | `b38677cf1` (inferred) | probably same code (commit inferred, no bit test) |
+| S1 | `v2_online_s18` | S0 | T4 | 3,000 decisions | `it_03000.pt` (`8fe355c7`) | 0.8 | `b38677cf1` (inferred) | probably same code (commit inferred, no bit test) |
+| S2 | `v2_online2_s28` | S1 | T4 | 3,000 decisions | `it_03000.pt` (`68d08d0b`) | 0.8 | `b38677cf1` (inferred) | probably same code (commit inferred, no bit test) |
+| S3 | `v4_relabel_s63` ("C1") | S2 | T4 | 2,000 of 3,000 decisions | `it_02000.pt` (`ceebbd2f`) | 1.6 | `977863c9e` (inferred) | recipe only here (exact code: `977863c9e`) |
+| S4 | `v8_roll_s801` ("D") | S3 | T5 | 2,000 decisions | `it_02000.pt` (`d9a35bfc`) | 0.6 | `46f74a797` | same code |
+| S5 | `v12_tb10_s1210` ("tb10") | S4 | T6 | 1,000 of 1,500 decisions | `it_01000.pt` (`6458a4f7`) | 0.5 | `362b48801` | same code |
+
+- Total about 21.7 GPU-h (NRD 10.0, teachers 6.9, students 4.8) plus the CPU MuJoCo collection of the NRD data
+ (each scripted campaign about 15 min on 24 workers; `expert_v2` 1.4 h, `policy_v3` 1.0 h on one 128-core node).
+- "Inferred" (S0-S3): the commit comes from the launch notes and from the saved config keys; the cluster copy of the
+ code was overwritten later, so there is no hash proof.
+- S3: commit `550a58cb6` (2026-10-23) changed the labels at the commanded speed (the first decision of an episode is
+ skipped). This branch has that change; the exact S3 code is `977863c9e`. Recipe for an exact S3 re-run (not run): a
+ git worktree of `977863c9e`, the `s3` command of `reproduce.sh` (`vision_viral.py online` with the config
+ `configs/so101_policy/vision/viral_r2s_online_relabel_v4.json`, seed 63) run in that worktree, with the paths of
+ that commit's configs (start banks, scene, calibration, NRD) changed to the downloaded files under
+ `artifacts/so101_pick_place/`.
+- T3 and T4 were planned for 400 and 200 iterations; the jobs were cancelled after the used checkpoint. PPO here has
+ an adaptive learning rate, so `reproduce.sh` stops at 140 and 110. T0 stopped at its 3.3 h time limit after 171
+ iterations; `reproduce.sh` stops at 171 iterations.
+- NRD c0: `configs/so101_pick_place/nrd/base_c0.json` says seed 61; the run used seed 62 (`--seed 62` on its command
+ line, as in `reproduce.sh`).
+- The policy stages (`t0` ... `s5`) run in the released policy NRD. Only `chain` (or `--parents own`) after an own
+ `nrd_train` + `nrd_strip` runs them in the own NRD (`OUT/nrd_main/c1_s62/best.pt`).
+- The commands of every stage are in `scripts/so101_pick_place/reproduce.sh` (steps `t0` ... `s5`); the run records on
+ the Hub (`args.json`, `meta.json`, `manifest.json`, `cmdline.txt`) hold the original command lines.
+
+### Real-data inputs
+
+The outputs are small files in git (`configs/so101_pick_place/`, the same bytes in the Hub folder `scene_calib/`).
+Paths of committed code are on the study branch. The exact command lines of these steps were not recorded.
+
+| Output | Real input | Code | Re-run |
+|---|---|---|---|
+| `calib_v1.json`: camera models and poses, joint map, table plane, mat, plate per episode | the 2 LeRobot teleop recordings (Hub `robot/lerobot_recordings/`) | `scripts/so101_policy/real2sim/calib_*.py` (13 files, commit `0338f2c3d`, committed 47 min after the file was written). Order: `calib_detect`, `calib_wrist_det`, `calib_segment`, `calib_lines`, `calib_jaw`, `calib_colors`, `calib_run.py full` / `holdout`, `calib_export`, `calib_finalize` (usage in each docstring) | recipe |
+| `real_scene_v2.json`: the look of the scene (colours, light, tone, crops) | the same recordings + `calib_v1.json` | study scripts in no commit (not released) | no |
+| `parts_override_v2.json`: real-look parts of the arm (the release check) | the same recordings | study scripts in no commit (not released) | no |
+| `dyn_fit_d2q.json`: fitted servo model of the sim checks | servo recordings of the robot (not released) | study scripts in no commit (not released) | no |
+| Table height and the 10 mm lower table (T6 / S5); robot-like servo, lag and sag ranges (S3 on); wrist-roll limit 98 deg (T5 / S4) | robot logs of 2026-10-22 to 10-26 (the Hub has the sessions from 10-24 on) | values set by hand from the logs (the reasons are in the `note` of each config); the study's measurement scripts are `scripts/so101_policy/real2sim/sysid/` (`run_all.sh`, `table_height.py`, `lag_fit.py`, ..., commit `6f7ee661b`) | recipe |
+| `so101_follower_lerobot_calib.json` | LeRobot motor calibration of the lab robot (`lerobot-calibrate`) | LeRobot | another robot needs its own |
+
+## Reproduce
+
+```bash
+# install the torch / torchvision build for your GPU first (https://pytorch.org; tested: 2.12.0+cu130, 2.10.0+rocm7.1)
+pip install -r requirements-so101-pick-place.txt # not requirements.txt: it pins torch 2.8.0
+
+scripts/so101_pick_place/reproduce.sh smoke # setup check, tiny sizes: about 5 min on one RTX 5090 (files local)
+scripts/so101_pick_place/reproduce.sh full # T6 and S5 from the released T5 / S4 (study: 0.8 + 0.5 GPU-h), the sim checks (21 runs), the bundle
+scripts/so101_pick_place/reproduce.sh chain --with-nrd-data # every stage from scratch (about 22 GPU-h)
+scripts/so101_pick_place/reproduce.sh full --steps download,nrd_test # the sealed NRD test
+scripts/so101_pick_place/reproduce.sh full --steps download,nrd_val --with-nrd-data # the NRD validation columns
+```
+
+`reproduce.sh --help` lists the steps and options. The download step fetches 0.86 GB by default (NRD, test set,
+teachers, students, RL inputs, results, bundle, LeRobot recordings) and checks the size and SHA-256 of every file;
+`--with-nrd-data` adds 10.6 GB (needed by `nrd_val`, `nrd_train` and `t1`), `--with-expert-data` 0.83 GB,
+`--with-robot` 1.15 GB. `scripts/so101_pick_place/download.py` does the download alone; `--source DIR` (or
+`SO101_PP_HF_SOURCE`) takes the files from a local folder with the Hub layout instead of the Hub. All data go to
+`artifacts/so101_pick_place/` of the checkout: every default path of the code points there
+(`src/nedm/so101_policy/paths.py`). Run from the repository root.
+
+The sealed NRD test with main's code alone:
+
+```bash
+PYTHONPATH=src python -m nedm.contact_nrd.test --data artifacts/so101_pick_place/nrd_test \
+ --model c1_s62=artifacts/so101_pick_place/nrd/c1_s62 c0_s62=artifacts/so101_pick_place/nrd/c0_s62 --output nrd_test.json
+```
+
+| Step | Check | Result in the smoke run (fresh clone, RTX 5090, torch 2.12.0) |
+|---|---|---|
+| download | size + SHA-256 of 173 files | all OK |
+| geometry | kin points and task geometry rebuilt from MuJoCo vs `rl_inputs/geometry/` | arrays and files equal |
+| nrd | main's `load_model` on both NRDs, 2 s rollouts | load, 2,424,735 parameters, finite |
+| nrd_strip | `strip_ckpt.py` on the released originals; original in the training code vs the new file in main's code | bytes equal to the released `best.pt` (both NRDs); rollouts, contact switches and metrics bit-identical |
+| nrd_test | main's test code on 24 test episodes vs the released test | per-episode values equal to 2e-6 (c1) and 3e-3 (c0): other batch, float noise |
+| nrd_collect | the collector regenerates 1 test episode per family | 12 of 12 bit for bit |
+| t6 | 2 PPO iterations, 256 worlds | checkpoint bit-equal to the study code (`359910370`) with the original NRD file |
+| s5 | 12 online decisions, 64 worlds, renderer | rows before the first training step equal to the study code; then the loss differs by GPU noise (0.0718 vs 0.0710 after the first update; two runs of the same study commit differ by as much) |
+| simcheck | G2-type run (one G2 evaluation, cut to 4 J224 tasks and 300 steps) | every array equal to the frozen runner `f70011ab` with the code of `362b48801` (timing keys aside); metrics equal |
+| bundle, fake | build, robot_test.sh check / eval 1 6 / replay of 3 recordings on a fake robot | replay outputs (joint inputs, images, action chunks) bit-equal to the released robot bundle |
+
+- GPU runs do not repeat bit for bit across machines; compare rates (the `summary` step prints them next to the
+ released records). CPU MuJoCo and the renderer repeat on one machine with the same package versions.
+- GPU memory: every full-size stage ran on AMD MI350X / MI300X (192-288 GB); `full` was not run on a 32 GB card.
+ T6 logged up to 7.8 GB of torch GPU memory (`gpu_mem_gb` in its `learning_curve.csv`); the student stages did not
+ log it. On a smaller GPU, lower the render batch (`--render-worlds`) first.
+- Teacher runs need `NEDM_SO101_DYN` unset (`reproduce.sh` unsets it); the sim checks set it to
+ `configs/so101_pick_place/dyn_fit_d2q.json` (`run_gates.sh`).
+- NRD retraining (step `nrd_train`) uses the training code of commit `f6f05c21c` (main's `train.py` lacks its options:
+ push guard, history noise, loss scales, contact sampling, co-training, the geometry heads, `init_from`). The step
+ makes a git worktree of that commit, writes the fine-tune config with an absolute `init_from` (the own base run with
+ `--parents own`, else the released `nrd/c0_s62/original/best.pt`) and checks the merged data against the fine-tune's
+ episode counts. The base NRD ran on uncommitted code (`provenance/` on the Hub); `f6f05c21c` is the closest commit.
+ A re-trained NRD is in the training format: step `nrd_strip` makes its main-compatible file.
+- `expert_v2` and `policy_v3` are not re-collected (no step). `policy_v3`, recipe (not run): commit `e205b801b`,
+ `scripts/so101_policy/collect_round.py` `ptasks` -> `prun` (with the 7 policies of `nrd_data/policy_v3/policies/`)
+ -> `label` -> `write --campaign policy_v3` (usage in its docstring). `expert_v2` is recipe only: its collector is
+ in no commit (`provenance/round2_expert_v2_code.tar.gz` on the Hub). The collector of this branch regenerates the
+ scripted parts bit for bit (checked on the first episode of every family: production 12/12, extra 4/4, noisy_v1
+ 4/4, test 12/12); `chain` collects the 4 scripted campaigns and compares their episode counts with the released
+ manifests.
+- Robot videos: `python3 scripts/so101_pick_place/robot/render_videos.py all --logs artifacts/so101_pick_place/robot/logs
+ --results artifacts/so101_pick_place/results/robot/results.json --out ` (needs `--with-robot`, opencv and an
+ ffmpeg with libx264).
+
+## Deploy on the robot
+
+The robot computer (Jetson AGX Orin, conda env `lerobot`: torch, torchvision, numpy, opencv-python, pyarrow, LeRobot)
+needs no MuJoCo, Warp or Newton: the bundle carries the kin points (the collision points of the arm). The study's
+notes record LeRobot 0.6.2 on the Orin: the version string of LeRobot's GitHub main branch after the v0.6.1 tag, so a
+source install whose commit was not recorded (not a PyPI release). PyPI `lerobot==0.6.1` ran the replay and the fake robot on the
+workstation, not the real arm (`requirements-so101-pick-place.txt`, section 2).
+[`scripts/so101_policy/real2sim/hw/README.md`](../scripts/so101_policy/real2sim/hw/README.md) holds study notes of
+2026-10-24 (older students, the study's paths); the steps below are the current guide.
+
+1. Take the tested folder `bundle/so101_hw_v13_tb10/` (or its `.tar.gz`) from the Hub, or build it:
+ `reproduce.sh full --steps download,bundle,fake`. A bundle built from this branch differs from the tested folder in
+ 14 files (11 code modules with the changes of section "Code", 2 doc files with a header that marks them as study
+ notes, the build time in `deploy.json`), has 2 small new modules (`paths.py`, `npz_rows.py`) and lacks 7 study
+ modules that the robot never loads. Its replay outputs are bit-equal to those of the tested folder (smoke run).
+ The Hub keeps no file modes: use the `.tar.gz`, or run `chmod +x robot_test.sh` in the downloaded folder.
+2. Copy it to the robot computer; check `sed -n '4,$p' MANIFEST.txt | sha256sum -c --quiet` in the folder.
+3. LeRobot motor calibration: the robot needs its own (`lerobot-calibrate`, in
+ `~/.cache/huggingface/lerobot/calibration/robots/so_follower/so101_follower.json`);
+ `configs/so101_pick_place/so101_follower_lerobot_calib.json` is the lab robot's file (replay and fake robot only).
+4. In the folder, in an interactive terminal: `./robot_test.sh check`, `DATA_ROOT= ./robot_test.sh replay` (default `~/lerobot/data`), `dry 30`, `live 15`, then
+ `eval 10 40` (10 episodes of 40 s). Logs: `~/so101_hw_runs/_/` (the layout of `robot/logs/`).
+5. Each episode: home move (type `MOVE`), place the cube and the plate, type `RUN`; type the result (`g` grasp,
+ `l` lift, `p` placed, then a note), `r` back to home, `s` end. Stop keys: q, space, Esc, Ctrl+C.
+6. Guard of the eval mode (`assets/deploy.json`): command floor -15 mm, measured floor -20 mm, joint and box limits,
+ camera age, blocked joints.
+7. Scene: cube and plate 15-27 cm from the shoulder pan axis, within +-75 deg of straight ahead, 6-30 cm apart (the
+ training task area). On this robot, cubes closer than 19 cm failed 6 of 7 times.
+
+The USB port and camera paths of the lab robot are written in `run_student_real.py` (`FOLLOWER_PORT`, `CAM_PATHS`);
+another robot needs its own values and its own camera calibration (`configs/so101_pick_place/calib_v1.json` is
+specific to this camera mount; section "Real-data inputs").
+
+## Code
+
+| Path | Contents |
+|---|---|
+| `src/nedm/so101_policy/` | Task, NRD worlds (`nrd_sim.py`), CPU MuJoCo worlds (`mujoco_env.py`), joint-target environment and teacher (`joint_env.py`, `joint_teacher.py`), decoder PPO (`vec_env.py`, `decoder.py`, `ppo.py`), kinematics, table rules; `paths.py` (data folder) |
+| `src/nedm/so101_policy/vision/` | The student, its online DAgger loop and images (`viral.py`), the tray / ACT code it builds on, datasets |
+| `src/nedm/render/` | The ray-traced renderer of the student's cameras (Newton / Warp), the calibrated camera models, the scene |
+| `src/nedm/contact_nrd/collect/` | The MuJoCo collector of the NRD data and its checks (new sub-package of main's `contact_nrd`) |
+| `scripts/so101_policy/vision_viral_teacher.py`, `vision_viral.py`, `train_ppo.py` | Teacher (tasks, expert, BC, PPO), student (`run`, `online`, `eval`), decoder PPO (T0) |
+| `scripts/so101_policy/real2sim/hw/` | Robot runner, bundle builder, robot test launcher (the files of the robot bundle) |
+| `scripts/so101_pick_place/` | `reproduce.sh`, `download.py`, sim checks (`check/`), NRD release checks (`nrd/`: strip, validation subsets, rollout comparison, tables), robot result tables and videos (`robot/`) |
+| `configs/so101_policy/`, `configs/so101_pick_place/` | Stage configs; camera calibration, scene, servo fit, real-look parts, LeRobot motor calibration, teacher env configs, NRD configs |
+| `configs/contact_nrd/collection/so101_grasp.json`, `contact_nrd/so101_grasp/` | Collector config; the pinned MuJoCo Menagerie fetch |
+
+The code files are copies of commit `359910370` of `so101-pick-place-study` (= `2b6dc4d8d`, the robot bundle, for
+every code file). Changes against the study code, all in the copied files (no main file changed):
+
+| Change | Why | Check |
+|---|---|---|
+| `nrd_sim.py`: no derived / relative channels, pair preview or contact mask | runs on main's `ContactNRD` (this NRD has none of them) | teacher checkpoint bit-equal (smoke) |
+| `mujoco_env.step_rates`: main's `data.step_average_rates` | the study's `_step_average` is not on main | bit-identical on 4,096 random states |
+| `task.load_start_bank`: `npz_rows.npz_members` (new file) | `contact_nrd/rollouts.py` is not added | same function |
+| Default data paths: `artifacts/so101_pick_place/...` (`paths.py`), interpreter of the MuJoCo workers = the running Python | the study read home-folder copies of the same files | same files (SHA-256) |
+| Config paths: start banks, scene, NRD `init_from` -> `artifacts/so101_pick_place/...`, `configs/so101_pick_place/...` | the study configs named cluster or home paths | - |
+| Robot scripts: workstation defaults of the calibration, LeRobot calibration, recordings, kin points, output folder (`~/so101_hw_runs`), bundle Python (`python3`) | the same rule; the robot computer gets its paths from `robot_test.sh` | fake replay equal to the tested bundle |
+| Study options whose modules are not released fail with a clear "not part of this release" error: worlds `kin` / `mjwarp` (`train_ppo.py --world nrd` only), the FSM expert act (`ExpertAct`), the Madrona backend, the gripper-look / base add-on / background randomisation of the renderer; `check_eval.py` keeps only the released scene family | the release carries only the code of the released chain; no released config uses these options | smoke runs |
+| Sim-check and robot-result scripts: paths are arguments; `check_eval.py` without its `build68` command; `build_results.py` reads the bundle records from the released `results.json` | ported from the study folders | same arrays / same tables |
+
+`real_scene_v2.json` keeps the study's home path of the calibration inside it (its SHA-256 is pinned in every
+student); commands pass `calib=...` (as every run did). Comments and docstrings of the copied code cite study notes
+(`~/so101_policy/docs/...`, `~/so101_r2s_claude/...`) that are not released.
+
+## Data
+
+Hugging Face dataset [harryzhang1018/NeDM](https://huggingface.co/datasets/harryzhang1018/NeDM), folder
+`so101_pick_place/` (503 files, 13.3 GB), pinned in [`release_manifest.json`](release_manifest.json) (revision,
+bytes and SHA-256 of every file; the Hub copy also holds the provenance: commits, run records, sources).
+
+| Path | Contents | Size |
+|---|---|---|
+| `nrd/c1_s62/`, `nrd/c0_s62/` | Main-compatible `best.pt`, the original in `original/`, training records (`run_config.json`, `train_log.jsonl`, `validation.json`, `complete.json`, `contact_scale.json`, `core_validation.json`) | 65 MB |
+| `nrd_data/` | The 4 data parts (`unified_data.npz`, `system.json`, `manifest.json`); `policy_v3/policies/` | 10.6 GB |
+| `nrd_test/` | The sealed scripted test set | 0.34 GB |
+| `teacher/t0_*` ... `t6_*` | Teacher checkpoints and run records; `t1_expert_data/` (24,576 NRD episodes, 0.83 GB) | 0.91 GB |
+| `student/s0_*` ... `s5_*` | Student checkpoints (S4 = D, S5 = tb10) and run records (`args.json`, `meta.json`, `curve.csv`, `progress.jsonl`) | 0.15 GB |
+| `rl_inputs/` | Task sets (`tasks/`), start banks (`banks/`), geometry, the task sets of the sim checks (`check_tasks/`). Released inputs: the recipes of the task sets, mixes and start banks are in the docstrings of `vision_viral_teacher.py` (`tasks`, `mix`, `starts`) and `train_ppo.py` (`bank`); `geometry/` is rebuilt by the `geometry` step; the sim-check sets J224 and H68 (from the robot logs) have no rebuild step here | 28 MB |
+| `results/` | `nrd/` (sealed test, validation re-score, tables), `sim_checks/` (gate results, selection rules), `robot/` (per-episode results, stress-test geometry, the study's test notes) | 27 MB |
+| `robot/logs/` | 19 sessions: 6 stress (tb10), 8 screening, 5 of D; per episode `episode_live.json` + `.npz` (50 Hz joints and commands, guard events, each query with its action chunk and the two input images at 112 px) | 0.96 GB |
+| `robot/videos/` | 50 stress-test videos (one per episode, real time) and 2 compilations (stress test, screening, 4x) | 65 MB |
+| `robot/lerobot_recordings/` | 2 LeRobot teleop recordings (15 episodes): calibration input and replay input | 0.12 GB |
+| `bundle/` | `so101_hw_v13_tb10/`: the folder installed on the robot computer (`MANIFEST.txt`), and its `.tar.gz` | 49 MB |
+| `scene_calib/`, `provenance/` | The same bytes as `configs/so101_pick_place/`; code snapshots that are in no commit | 2 MB |
+
+- The videos show the student's input images as logged on the robot (112 px, external | wrist, about 7.9 Hz; the
+ student sees them at 224 px). There is no full-resolution or third-person video.
+- The robot logs hold lab background images (`first_frames.npz`), the robot computer's user path and the USB
+ adapter serial; the code holds the same serial.
+
+## Limits
+
+- One robot, one lab, one cube and one plate; the stress test took about 1 h. The camera calibration belongs to this
+ camera mount.
+- The outcome is typed by the operator. The stress protocol was not fixed in advance, and the student was chosen with
+ robot results (section "How tb10 was chosen").
+- The logs do not record a checkpoint hash: the student of each session is known from the bundle folder named in the
+ logs and the study's local copy of that bundle; the files on the robot computer were not compared with
+ `MANIFEST.txt`.
+- The cube and plate positions, directions and end distances are an image + kinematics estimate whose script is not
+ released.
+- L->R is weaker than R->L (63 % vs 83 %). Cubes near the base fail (1/7 under 19 cm).
+- The release detector of the earlier sim checks false-fires on tb10: on the 50 robot stress episodes it flags 19
+ releases (tb10 carries the cube low; the traces show the jaw closed until the plate). A slightly higher table hurts
+ placing in simulation (G3 +3 mm: 94 places).
+- There is no sealed sim test of the student. The NRD test set is not fully blind and has only scripted families.
+- No stage repeats bit for bit on a GPU. T1-T3, S3 (with this branch) and the base NRD are recipe only; the S0-S3
+ commits are inferred. The scene look, the real-look parts and the servo fit cannot be made again from this release.
diff --git a/so101_pick_place/code/so101_pick_place/release_manifest.json b/so101_pick_place/code/so101_pick_place/release_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..d7ece26ee67f4c20a27680c2807e2b9f316e6720
--- /dev/null
+++ b/so101_pick_place/code/so101_pick_place/release_manifest.json
@@ -0,0 +1,2021 @@
+{
+ "schema": "nedm-so101-pick-place-release/1",
+ "repo_id": "harryzhang1018/NeDM",
+ "prefix": "so101_pick_place/",
+ "hf_revision": "dcb873bc5da3da8ad5abdec6137c77ef46038f43",
+ "note": "Pinned copy of so101_pick_place/release_manifest.json on the Hub (that file also holds the provenance: code commits, run records, sources). hf_revision = the Hub commit that adds this manifest; the data files come in the commit before it. Released student: student/s5_v12_tb10_s1210/it_01000.pt (sha256 6458a4f7...). NRD of every policy stage: nrd/c1_s62/best.pt (main-compatible copy; original/best.pt = the file the study used). scripts/so101_pick_place/download.py checks the size and sha256 of every file.",
+ "files": {
+ "so101_pick_place/README.md": {
+ "bytes": 15533,
+ "sha256": "b65763a8a38ff0bf0d9d85c3f881a867945ecbb30579cfc6c9433e6c0b394cc8"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10.tar.gz": {
+ "bytes": 23280447,
+ "sha256": "5a229cddccc8a683da0083dc981ab4bc9faf7515285eb8726cea6b909e01522c"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/MANIFEST.txt": {
+ "bytes": 4273,
+ "sha256": "fcba1454a402a53651c7fd56441ff108e54b0b0c27a90dd86dd178b73c18791e"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/QDGAIN_TEST.md": {
+ "bytes": 6541,
+ "sha256": "87becae0ad0bb8bb1af7a79e4e4c91361f053f7478d405cb0fa75c05ca4e970f"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/assets/calib_v1.json": {
+ "bytes": 39147,
+ "sha256": "3b7a2124d1b56bd6049a682a4eb29e9f4cef62818f4a420665171bbe31e0410f"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/assets/deploy.json": {
+ "bytes": 1587,
+ "sha256": "d29074110d67a79c003c4e324bf4a9dcc75273f5381ca09a72e58dd4d104deaf"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/assets/kin_points_v1.npz": {
+ "bytes": 153922,
+ "sha256": "32dcf834a1dc3d31b1e6082bf0f2f6c80056861bd97a8856b0d8e4f733365f64"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/assets/student.pt": {
+ "bytes": 24555983,
+ "sha256": "6458a4f791d1052148bb8f7621413259342a7018757668fde244cfc098f99f5c"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/robot_test.sh": {
+ "bytes": 10556,
+ "sha256": "313e5d82a11f3a38dec96cdd052900d332dda7a87b427612cc0296159c4c46b4"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/scripts/so101_policy/real2sim/hw/README.md": {
+ "bytes": 21445,
+ "sha256": "bf635927181c43646541ea968892f23e0cd2412fb52f64a035ff2418d865d600"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/scripts/so101_policy/real2sim/hw/hw_lib.py": {
+ "bytes": 66600,
+ "sha256": "958cc71178723cc352f21114d0ec58d5862f682c51decdd199a0a04b0844fb16"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/scripts/so101_policy/real2sim/hw/run_student_real.py": {
+ "bytes": 66625,
+ "sha256": "90c629574ac17579ce2cdfa7baf975985c34c7d95cbf2fad3519288fde9700c4"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/__init__.py": {
+ "bytes": 38,
+ "sha256": "0b92e78ad52036c9e3c282ced58aadf360940c587b126ce5b4bb8a1974cfad12"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/render/student_view.py": {
+ "bytes": 5678,
+ "sha256": "1f2093327df62a87f0759bf19648ae088ccfd5ae9a16d2f6a053cd74c5223ba9"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/__init__.py": {
+ "bytes": 123,
+ "sha256": "9f3d9faf9d8c2b7874f9b4f4cb80b05bf828a5ea6e83c2b3cf4a05bc9d3649f3"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/cube_symmetry.py": {
+ "bytes": 7224,
+ "sha256": "c2b3b99c67c8b91597d426fb0f5c6ef502b22e993def9f493032c13fd96c15c5"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/data_round.py": {
+ "bytes": 75670,
+ "sha256": "8c606bd4c25b3f19fbe89aa48c87df3e6ab0105c399d483e4bd39eb7159e1fc0"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/decoder.py": {
+ "bytes": 91166,
+ "sha256": "fddfa91c60ca78e937e3dddc48d0c43fefb7b304b4d32d61b2c5762025b90640"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/expert.py": {
+ "bytes": 24722,
+ "sha256": "ae0129f3678ca6a9e7df2bfda46411c3eec2a1d449ac0c83b7796e3c22e9ab84"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/joint_env.py": {
+ "bytes": 125701,
+ "sha256": "549c84a5856f293b8a2b95fdfffd761238e5d796250c1f007771ad1a29b0a2e5"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/joint_teacher.py": {
+ "bytes": 34658,
+ "sha256": "4e4b439ddd6934d31fe23d23852923c2df41b64e83f15faf591e346ff3beba9e"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/kin.py": {
+ "bytes": 25198,
+ "sha256": "20388d992ffaf8f1e49b2a3e1bb1e6b0fadf39b0d292019c9aa3e945e4a44d4d"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/kin_world.py": {
+ "bytes": 18954,
+ "sha256": "390a57f15430954bca16ee1fd5c8e4f1250dc581972677c3e821a92a5f060514"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/mjwarp_env.py": {
+ "bytes": 41059,
+ "sha256": "416500a0101034fa64ef8f338c0072b4c51871e8e0cf52be01cbcdb0c45952cd"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/mujoco_env.py": {
+ "bytes": 50038,
+ "sha256": "9c2daf8375068f07a5a3989a5e19d76c0f35ec9aee09c894634e6cd875f11dbc"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/nrd_sim.py": {
+ "bytes": 35963,
+ "sha256": "bc7a402a66b30092b7e1549f8484677cea9d0988e2846bae64a1bca22350e682"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/ppo.py": {
+ "bytes": 28858,
+ "sha256": "b026e361f0f285112000d6533770d5478b2e6a11a3885b65af4af8d9f41118be"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/table.py": {
+ "bytes": 7639,
+ "sha256": "9e8f1a316dfc404aa1e921e65031f09b282a7ebfbf199207161157872d08e638"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/table_bias.py": {
+ "bytes": 19848,
+ "sha256": "70eeb69db57d6c58fb2028e6f51aff214a17337dd11ef8bd86bf0dc45cb136c9"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/task.py": {
+ "bytes": 70955,
+ "sha256": "bf05c91dfc0090fef3203e1704b788930e7412832e6974c39088893b812d033b"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vec_env.py": {
+ "bytes": 40373,
+ "sha256": "deedc6239b51ffbbc86dfecd066135bb7323dfd3cb50f7eb2aadecf4e2d163eb"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/__init__.py": {
+ "bytes": 359,
+ "sha256": "61fc1f756e386e006acf692806a94c828857754c43516ba6fa8c559a06bd04d0"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/act7.py": {
+ "bytes": 16006,
+ "sha256": "731ca7508aa6348d5947eb30349f5701f651e3e655ca78fcd43d52b79d8d0f5b"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/dataset.py": {
+ "bytes": 12492,
+ "sha256": "f9537fa7607b70857cd30083c94488156cc76b1bd642a4d80965a2f29c7333af"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/demos.py": {
+ "bytes": 13630,
+ "sha256": "dcd6af52209c8e47ffd46286aa3f2a37641c3464740425bc20f0f20c5630cdbf"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/perstep.py": {
+ "bytes": 21219,
+ "sha256": "76caa665585b33e83ed8baa69232e4cd5cc1d99ad2011f555250cda0c39dc7fb"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/rollout.py": {
+ "bytes": 23354,
+ "sha256": "600df4aa64f3baf86ce7cc43acc8d9d4eb784bf28de50f405e7a8a3a0fbc479b"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/student.py": {
+ "bytes": 17174,
+ "sha256": "686e3813a933fc9e3a56c4365b12b32d5c84b768e6411ca24795eeac21dc27f8"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/teacher.py": {
+ "bytes": 18395,
+ "sha256": "bb2c80ce5b2c4c6a08d3a6ac7c145b9652c33e5f094d3046b518061f0babceb3"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/tray.py": {
+ "bytes": 72013,
+ "sha256": "ab7cbe9d052a069936780c29c32df5a2bf907778e65b50e332b67ca1b2fcd8fd"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/vision/viral.py": {
+ "bytes": 179050,
+ "sha256": "c0708f0ad8a254badedb4ccb2a4af99c7515e3467327f7b2f63973a846fcb957"
+ },
+ "so101_pick_place/bundle/so101_hw_v13_tb10/src/nedm/so101_policy/world.py": {
+ "bytes": 2197,
+ "sha256": "8650e24eca6a19d2c0a578822b4ce0cd63daddcc216ebdd43e9f27742d44e576"
+ },
+ "so101_pick_place/nrd/c0_s62/best.pt": {
+ "bytes": 10886175,
+ "sha256": "01c44cd0424d4f0bee47c18bd29a58ef0465c184a2f309df509f2555b733b007"
+ },
+ "so101_pick_place/nrd/c0_s62/complete.json": {
+ "bytes": 1293,
+ "sha256": "f00e1d55030bc8b460ba09c58a88ae448dddc6ab3fd90b045cec569ab10c9e43"
+ },
+ "so101_pick_place/nrd/c0_s62/contact_scale.json": {
+ "bytes": 2340,
+ "sha256": "0f32dcbe3993eda89b1f53adb7d41e376f003bae01ba14f6f5e79bd662098b8c"
+ },
+ "so101_pick_place/nrd/c0_s62/core_validation.json": {
+ "bytes": 1372,
+ "sha256": "40a2c0af7e42e3758761da42a4ef8f5bd0523745da7ef01f5cdb57eff1027a49"
+ },
+ "so101_pick_place/nrd/c0_s62/original/best.pt": {
+ "bytes": 10902283,
+ "sha256": "c2b44e7f89e617d51bdbad0e5001dc86b169b01220422c52f39e4efad7c853ab"
+ },
+ "so101_pick_place/nrd/c0_s62/run_config.json": {
+ "bytes": 3348,
+ "sha256": "e07929cb4a15d009445f01c6eb3881e185140213938f04507f7f833eb7a55338"
+ },
+ "so101_pick_place/nrd/c0_s62/train_log.jsonl": {
+ "bytes": 23646,
+ "sha256": "e1e0461ab727837931ebe1aba5710aa4e62f02af53544d61ef4d7e90c4b70a6c"
+ },
+ "so101_pick_place/nrd/c0_s62/validation.json": {
+ "bytes": 5934837,
+ "sha256": "9fe323f9b7c8505fc8f77bf6e213eea43d44ec07e5dc9ea6ebc411977de76f93"
+ },
+ "so101_pick_place/nrd/c1_s62/best.pt": {
+ "bytes": 10893663,
+ "sha256": "2d1a24926d463c5432a8dcb6897c05fe1082f04095c773ec914dd53986d66abc"
+ },
+ "so101_pick_place/nrd/c1_s62/complete.json": {
+ "bytes": 1952,
+ "sha256": "b22e7b2038606ec3b40236a8cde2801d3c38c7d34b6bc5dce60e94933e36755d"
+ },
+ "so101_pick_place/nrd/c1_s62/contact_scale.json": {
+ "bytes": 2340,
+ "sha256": "0f32dcbe3993eda89b1f53adb7d41e376f003bae01ba14f6f5e79bd662098b8c"
+ },
+ "so101_pick_place/nrd/c1_s62/core_validation.json": {
+ "bytes": 1378,
+ "sha256": "f0fb4b1f6dbc9a8925988df63ff1cb8b9c5f871bd9284b79152e8d6fc60ef5ee"
+ },
+ "so101_pick_place/nrd/c1_s62/original/best.pt": {
+ "bytes": 10909835,
+ "sha256": "f45ee8be2c1bb1e60876b2868746632b2c7d84c9d7fb746b6c70b32975c31237"
+ },
+ "so101_pick_place/nrd/c1_s62/run_config.json": {
+ "bytes": 5031,
+ "sha256": "88f32d33b17650adca2726a069afc840b7de54369299f7fbdbef0c85574d0b75"
+ },
+ "so101_pick_place/nrd/c1_s62/train_log.jsonl": {
+ "bytes": 15359,
+ "sha256": "98fa797d20fd27092a044f8c866a7bc73dbf4b1376c794e7fe929a3eb08414a5"
+ },
+ "so101_pick_place/nrd/c1_s62/validation.json": {
+ "bytes": 15046209,
+ "sha256": "6214836fa900b0a9fa1e2ebf5e2df429fd296d354eb9da1c220570baf2f0c8b8"
+ },
+ "so101_pick_place/nrd_data/expert_v2/manifest.json": {
+ "bytes": 20982,
+ "sha256": "3a532ca30a013d9ee90ef68c96a1685dcc59ea8f48b8b2507f782178ce4b7f34"
+ },
+ "so101_pick_place/nrd_data/expert_v2/system.json": {
+ "bytes": 23300,
+ "sha256": "3ca0f9ff57eeb54b4a45c4c8e429aa6ce08c25bef21c7b1e06f394f7f6bdb3eb"
+ },
+ "so101_pick_place/nrd_data/expert_v2/unified_data.npz": {
+ "bytes": 3025938686,
+ "sha256": "54419a2dd8ebb9df037eacf684ca97c30fc85919af14a4a20067b277af7383ab"
+ },
+ "so101_pick_place/nrd_data/noisy_v1/manifest.json": {
+ "bytes": 29508,
+ "sha256": "42a94d43bc08ba04f7194a89b6ebad5336ffaf0c6a697314672f8fd6503e3522"
+ },
+ "so101_pick_place/nrd_data/noisy_v1/system.json": {
+ "bytes": 21069,
+ "sha256": "27fbf0d3d21f767ecf8b41f54bbd758aeb687238c48e371edeaf184397170ad2"
+ },
+ "so101_pick_place/nrd_data/noisy_v1/unified_data.npz": {
+ "bytes": 1130646550,
+ "sha256": "08be0218b65a329a4e6aab5d054c1b78b7c0d5c5dd1b714497452656d78f9810"
+ },
+ "so101_pick_place/nrd_data/policy_v3/manifest.json": {
+ "bytes": 25244,
+ "sha256": "c94c62dde473733a38885394376c1cd09e15bbd5b6aec0ae9dd60141b1b20540"
+ },
+ "so101_pick_place/nrd_data/policy_v3/policies/kCa_kC_00060.pt": {
+ "bytes": 5100533,
+ "sha256": "6644b08722775e1469c83c422a539f9c593b03bfbd64eed52d8f80a5f98ed506"
+ },
+ "so101_pick_place/nrd_data/policy_v3/policies/kCb_kC_s2_00059.pt": {
+ "bytes": 5100917,
+ "sha256": "cceba11c3456466bb4bdbfa2a3cbdcfda3ec03af57eb3495d02f3be533d694fa"
+ },
+ "so101_pick_place/nrd_data/policy_v3/policies/kCc_kC_s3_00060.pt": {
+ "bytes": 5100917,
+ "sha256": "737fe261d2bafd24e83ec06be0f1de2718e1e8f060e8efc479bab4338016a4e1"
+ },
+ "so101_pick_place/nrd_data/policy_v3/policies/nRa_nR2_s62_a_00160.pt": {
+ "bytes": 5100981,
+ "sha256": "c147e0d4b3806368921b13fd3c853c1d166007e0f28b6cf01f258472279ae1c4"
+ },
+ "so101_pick_place/nrd_data/policy_v3/policies/nRc_nR2_s62_c_00155.pt": {
+ "bytes": 5100981,
+ "sha256": "1248f306e0ff60fcca2566ea0f74001117c47acff06e1cd7e7427571df2c8c95"
+ },
+ "so101_pick_place/nrd_data/policy_v3/policies/w5a_w5_dc_00121.pt": {
+ "bytes": 5035509,
+ "sha256": "fb098936c4f3b64085211c3cbe52c5f9ea8da8e54e8ecaaddb915bc0e6b9dbe9"
+ },
+ "so101_pick_place/nrd_data/policy_v3/policies/w5b_w5_dc_s2_00123.pt": {
+ "bytes": 5035253,
+ "sha256": "4b965ca9b6fe4ad6447104e02efee484feab7f1fc32a8d6f40b3e43480e22456"
+ },
+ "so101_pick_place/nrd_data/policy_v3/system.json": {
+ "bytes": 24573,
+ "sha256": "a7066c3690b22de6212d6f3e70a11ce71d0485f20a0da02cebf8ce2a2cf449d8"
+ },
+ "so101_pick_place/nrd_data/policy_v3/unified_data.npz": {
+ "bytes": 2174340578,
+ "sha256": "74b8912a9da91537f55769d67fb29d9a31783069c4be38b2ee07772e3491d765"
+ },
+ "so101_pick_place/nrd_data/production_plus/extra_manifest.json": {
+ "bytes": 24220,
+ "sha256": "49571b925d178a0a5c96216d08e732032320079020d2f0b7af0fa222f096da4d"
+ },
+ "so101_pick_place/nrd_data/production_plus/manifest.json": {
+ "bytes": 263,
+ "sha256": "662f887d9018708ecb6c5cd25f336a7bcabde499b8f3c27d2e425d0da4ad8737"
+ },
+ "so101_pick_place/nrd_data/production_plus/production_manifest.json": {
+ "bytes": 35621,
+ "sha256": "86df9afbc73c304747919dcc8d4683a3ba140bc2d5e5cc4446a612717845fbe8"
+ },
+ "so101_pick_place/nrd_data/production_plus/system.json": {
+ "bytes": 18470,
+ "sha256": "8d96d4aaea77a1a4482f46a33ec9278ae97eaf4498c215f0216c3a56f4ea5b5f"
+ },
+ "so101_pick_place/nrd_data/production_plus/unified_data.npz": {
+ "bytes": 4239906914,
+ "sha256": "b454d8fb2a23732edafc064b58d0577f7131aeadda2ba0d66fddfd226bb948be"
+ },
+ "so101_pick_place/nrd_test/manifest.json": {
+ "bytes": 34493,
+ "sha256": "65d1430ff9ca1f18e86e67a3288905009215990475511de7bef5c4ede651eb21"
+ },
+ "so101_pick_place/nrd_test/system.json": {
+ "bytes": 18470,
+ "sha256": "8d96d4aaea77a1a4482f46a33ec9278ae97eaf4498c215f0216c3a56f4ea5b5f"
+ },
+ "so101_pick_place/nrd_test/unified_data.npz": {
+ "bytes": 344851750,
+ "sha256": "657e3b471849340dc17eb130fb6441ba981084d687755b4517f3fd44bbeae4b8"
+ },
+ "so101_pick_place/provenance/code_v16_base_nrd.tar.gz": {
+ "bytes": 517756,
+ "sha256": "67e57422e9da110896576935eedf71a130949549ed041815eaa3c283e9b4d82b"
+ },
+ "so101_pick_place/provenance/code_v16_base_nrd_sha256.txt": {
+ "bytes": 16315,
+ "sha256": "867f299b75fd3b8e38d4807a1d46946a7c8850bb51dfa33137ac8955ac41aea2"
+ },
+ "so101_pick_place/provenance/round2_expert_v2_code.tar.gz": {
+ "bytes": 896958,
+ "sha256": "2866ec3acfbb1fbe58b375a533524f0200c2f0abb7ab0424ea1d8d799e9bce3e"
+ },
+ "so101_pick_place/provenance/round2_expert_v2_code_sha256.txt": {
+ "bytes": 33685,
+ "sha256": "7548e5098d2e41039a75076c1461263fe86f91eac7a279019ccb8c7881838c18"
+ },
+ "so101_pick_place/results/nrd/sealed_test.json": {
+ "bytes": 13729783,
+ "sha256": "f3df465e76d9fd2b7ec5407933b6263c1f8c5d48a3103e7825767181d980c20a"
+ },
+ "so101_pick_place/results/nrd/sealed_test.txt": {
+ "bytes": 83084,
+ "sha256": "736a7dd9d6da034341b3fe3bbd3cffbe8f6039420403c42c51a765b641cfcea3"
+ },
+ "so101_pick_place/results/nrd/summary_all.json": {
+ "bytes": 7258,
+ "sha256": "00dde13180ac222148e90de679c2d5f626517d73c5287cd630fd6bf9fd63105f"
+ },
+ "so101_pick_place/results/nrd/summary_all.md": {
+ "bytes": 1999,
+ "sha256": "8a574a55fc6cff0e5c752e00ba56aa3b2b721b5f9b6e11ab48b08eb065c061c9"
+ },
+ "so101_pick_place/results/nrd/summary_selected.json": {
+ "bytes": 7242,
+ "sha256": "49fe212229fc6fa78dd07242fb946f4dc9fd21464e6ac59a53de8eb124d730eb"
+ },
+ "so101_pick_place/results/nrd/summary_selected.md": {
+ "bytes": 1989,
+ "sha256": "cae37edc151da6f47100a67cec4d245cce165f71fe7f37b0324ac86e5639c05f"
+ },
+ "so101_pick_place/results/nrd/validation_rescore.json": {
+ "bytes": 12960388,
+ "sha256": "87f1d12d1233398103ed3c57a03c0cfaca01385379abe43ab44981df8bf87739"
+ },
+ "so101_pick_place/results/nrd/validation_rescore.txt": {
+ "bytes": 83063,
+ "sha256": "4f27e761b3e8cf134dc4fdd036534ad70bc7b951eee40b481f6883173bb98f54"
+ },
+ "so101_pick_place/results/robot/ROBOT_20261027.md": {
+ "bytes": 1949,
+ "sha256": "3af613d2bf6b3f00a66a18dd5b4170511041a520dc8f40af2b201100b6784f15"
+ },
+ "so101_pick_place/results/robot/STRESS_tb10_20261027.md": {
+ "bytes": 1476,
+ "sha256": "fdec2cbe6696b087db1b88eb19019b6c3213a7c1937d1757c3a946a9711ecb45"
+ },
+ "so101_pick_place/results/robot/results.json": {
+ "bytes": 70275,
+ "sha256": "dc6aa66306602d59b512c2e28ec30b5c2dc8b9925b3195ab17ac444315dfd319"
+ },
+ "so101_pick_place/results/robot/results.md": {
+ "bytes": 15029,
+ "sha256": "4c5bf3c43032b907bae593f8a39a6433e489ec01a09247acaf4b659e5c6fb0a1"
+ },
+ "so101_pick_place/results/robot/stress_episodes.json": {
+ "bytes": 26908,
+ "sha256": "4d49c1f64ecc2ace3e145e659497f718d0e7ee1442ebb390a130063b106e8dc7"
+ },
+ "so101_pick_place/results/sim_checks/D_reference.json": {
+ "bytes": 3437,
+ "sha256": "08f4198e0680991893d2770e99085df1b6747b5eddedc5da5ef1c6c8384c971f"
+ },
+ "so101_pick_place/results/sim_checks/LAB_PICK_RULE_v13.md": {
+ "bytes": 1872,
+ "sha256": "4d8e1abde9e295c51da12ea69bef8624ff81f2207a234bd460239f1f800303f0"
+ },
+ "so101_pick_place/results/sim_checks/LAB_PLAN_v13.md": {
+ "bytes": 4366,
+ "sha256": "9c20a4d973009a247a4c000182e64311b75e2f48a1391437b20bd939acbe7c7d"
+ },
+ "so101_pick_place/results/sim_checks/SELECTION_RESULT_v12.json": {
+ "bytes": 10243,
+ "sha256": "bd719ced5944bac8be96ec98015be71ebfca9ff6d1f1de33c6d0f40fcd46d726"
+ },
+ "so101_pick_place/results/sim_checks/SELECTION_RESULT_v12.md": {
+ "bytes": 17310,
+ "sha256": "0dbb33e6b8b4a1d73bdb8dc6c0af914f32b29eba3c3ae51b8ef2f876c3b39d9a"
+ },
+ "so101_pick_place/results/sim_checks/SELECTION_v12.md": {
+ "bytes": 12205,
+ "sha256": "41a74ca24aa2dbcdad51d7c8cb3af52eafffd1f9796529f326d36888af743d9b"
+ },
+ "so101_pick_place/results/sim_checks/v12_tb10_s1210_it1000.json": {
+ "bytes": 6274,
+ "sha256": "71152cae8924f9049dd0d98ad7153de56409639ac68942aefea0f58a225fdb58"
+ },
+ "so101_pick_place/rl_inputs/banks/bank_pp_h45mix.npz": {
+ "bytes": 10455360,
+ "sha256": "9e911360354bece69cb36754a14e16113e1a45e82100a5ebc72a3974cfe43b2f"
+ },
+ "so101_pick_place/rl_inputs/banks/bank_pp_s0.npz": {
+ "bytes": 5445192,
+ "sha256": "fccf9543b25b96ccbdca88d332e6c1a02eb8eb0705976e9c7f731ae10fb35025"
+ },
+ "so101_pick_place/rl_inputs/banks/bank_pp_split0.npz": {
+ "bytes": 5040878,
+ "sha256": "0f78f4bc5859121a046c876f4866d5669ef65cfbd4a9cfe4da9f06031e80b23d"
+ },
+ "so101_pick_place/rl_inputs/check_tasks/all280.json": {
+ "bytes": 152622,
+ "sha256": "3456fc5fb190fa6ccdaf76b42d303100b2322bed7d511a70c860f486612d28bc"
+ },
+ "so101_pick_place/rl_inputs/check_tasks/h68.json": {
+ "bytes": 37531,
+ "sha256": "a846560c3debb40b813a8a964bb32f1f68b45200b3257810849a0ae17ccd2705"
+ },
+ "so101_pick_place/rl_inputs/check_tasks/h68.npz": {
+ "bytes": 26387,
+ "sha256": "887478818f0576571fe2b1ec70674c1a1c97c32102a0cccd9af7f1dbacfb9349"
+ },
+ "so101_pick_place/rl_inputs/check_tasks/jit224.npz": {
+ "bytes": 88551,
+ "sha256": "ea9709bf3ecdf33269e745622d58734d7a1b25fd0a75c9aa1195ab2a1f77467a"
+ },
+ "so101_pick_place/rl_inputs/geometry/kin_points_v1.npz": {
+ "bytes": 153922,
+ "sha256": "32dcf834a1dc3d31b1e6082bf0f2f6c80056861bd97a8856b0d8e4f733365f64"
+ },
+ "so101_pick_place/rl_inputs/geometry/task_geom_v2.npz": {
+ "bytes": 337622,
+ "sha256": "330c37748ecab12061f227ca0ffdfffdafeabf7060836f672b59948377284bf9"
+ },
+ "so101_pick_place/rl_inputs/tasks/dev100.npz": {
+ "bytes": 39233,
+ "sha256": "507f078b7b1c0b37f1f67ecd79dc20ec60de24556d9d517541d0629e33f08a6c"
+ },
+ "so101_pick_place/rl_inputs/tasks/fresh100.npz": {
+ "bytes": 39233,
+ "sha256": "2090bef43c7340924654111d601d7ceddc37b704a610611d198955f0821d2786"
+ },
+ "so101_pick_place/rl_inputs/tasks/home45_dev100.npz": {
+ "bytes": 41365,
+ "sha256": "f817bc4468c92158fe45b23f530ea1906ba2bdd47261a8d04766c26bb79c050a"
+ },
+ "so101_pick_place/rl_inputs/tasks/home45_fresh100.npz": {
+ "bytes": 41365,
+ "sha256": "761bc699cecedfddca984afa1790f50702f5fdf450b39aca413e49b7632b3691"
+ },
+ "so101_pick_place/rl_inputs/tasks/home_dev100.npz": {
+ "bytes": 41365,
+ "sha256": "b6d208768cacb8a1f5b276ce73e096b0776f5260b68d439698b58bf4bbf01596"
+ },
+ "so101_pick_place/rl_inputs/tasks/train_mix45_16k.npz": {
+ "bytes": 5903316,
+ "sha256": "48c7d732c85d1bbb9b2bbd5f78ca6470274d1b7e7c61f75e3dd667a3c7fd6be8"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate/data/chunk-000/file-000.parquet": {
+ "bytes": 123692,
+ "sha256": "d348e36bcb290a1303daa27c0b70029c45b14e9637e1661a7fba47d68734452b"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate/meta/episodes/chunk-000/file-000.parquet": {
+ "bytes": 59039,
+ "sha256": "d2ec0021040200c2725d4aaa5d373df2f19a4cedd27c61745bf30a5749acab26"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate/meta/info.json": {
+ "bytes": 3691,
+ "sha256": "002f32cdfe89cf766f25c3b469eb773666ae32308acfb4e4b1cd29a4c6ed2258"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate/meta/stats.json": {
+ "bytes": 13039,
+ "sha256": "192c7a3e80b165ce10f288e18886fbf3142b78dbeacebf0dbfc81738e41972df"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate/meta/tasks.parquet": {
+ "bytes": 2255,
+ "sha256": "bd6d63a6fdd6622d42e867b8640b6752f97e8f252e704e944f91817a50e44635"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate/videos/observation.images.external/chunk-000/file-000.mp4": {
+ "bytes": 14079988,
+ "sha256": "dc865477081a981730cd156271f128fb29a2744c3fbfc4322a67aca68eb00ce6"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate/videos/observation.images.wrist/chunk-000/file-000.mp4": {
+ "bytes": 15251861,
+ "sha256": "5d73e6c4101e89cefb69740e03a6124d4b3607f0b85a12c8f9a0872423dc2374"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate_1/data/chunk-000/file-000.parquet": {
+ "bytes": 343802,
+ "sha256": "47806e0d24139b012f417ac72a18ae9892c002f29aba5938cc970b2c868acca7"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate_1/meta/episodes/chunk-000/file-000.parquet": {
+ "bytes": 66484,
+ "sha256": "7e705c354d59130b022c1876c2f25c78b7e205e3e3ad1b09daa3e4e3bcce2ee4"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate_1/meta/info.json": {
+ "bytes": 3693,
+ "sha256": "5fbe8bb4413faf7e0fa979603b0ea0dee5f9adff30a58156186bb4b3d7f9004e"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate_1/meta/stats.json": {
+ "bytes": 13025,
+ "sha256": "130cda659eeffc37e9b2e24772987c19c0f9c77cfc8a53e62dd1cea4feac38da"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate_1/meta/tasks.parquet": {
+ "bytes": 2255,
+ "sha256": "bd6d63a6fdd6622d42e867b8640b6752f97e8f252e704e944f91817a50e44635"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate_1/videos/observation.images.external/chunk-000/file-000.mp4": {
+ "bytes": 42649127,
+ "sha256": "967808097979dfdb6a90419fe357a5039f83178757ba45542665570dd9a1c97a"
+ },
+ "so101_pick_place/robot/lerobot_recordings/green_cube_red_plate_1/videos/observation.images.wrist/chunk-000/file-000.mp4": {
+ "bytes": 48566599,
+ "sha256": "80081f24ea9960c7ea3323ed35364781542245505bd8805baa975ed82d113125"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/ep_01/episode_live.json": {
+ "bytes": 5859,
+ "sha256": "8c8e7b09f18aabf6ff6a7010eb3694aed9c8cd5197cbbebec57516bea718c459"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/ep_01/episode_live.npz": {
+ "bytes": 8829778,
+ "sha256": "6eeb8ff501e647ead09d1c2e3d8a9bf007c5194c91c328151b0fad29d263d87f"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/ep_02/episode_live.json": {
+ "bytes": 5854,
+ "sha256": "a54be509882ebc9ddb12e6febf0db8bc25199a1e09c4c5eae1dfbafc885d3b4e"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/ep_02/episode_live.npz": {
+ "bytes": 9496183,
+ "sha256": "058a437d471e958a96642ff05eb0efcec7aa646e9268eab6b727576d404c1293"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/ep_03/episode_live.json": {
+ "bytes": 5909,
+ "sha256": "36506ae22c4abb9a47f60b98e0b46c4ff349287ad2fff4fe158fe31973eb975f"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/ep_03/episode_live.npz": {
+ "bytes": 12405507,
+ "sha256": "6acb7ce130224bbc471794748c4eb965a85048f81fea3da2e34718e25a38b141"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/ep_04/episode_live.json": {
+ "bytes": 5914,
+ "sha256": "ee507b17aec243f7998bc10b190d178d347daa93f2eab9c54fc7bd2bd67e2485"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/ep_04/episode_live.npz": {
+ "bytes": 14110853,
+ "sha256": "3cf42ee9c7d670a22a8992da789a672456b601a66947cc64a10022e67e46696b"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/first_frames.npz": {
+ "bytes": 489497,
+ "sha256": "ff870f4a03f74750d2c7c6c3924bf1e3ff6559a2663e476b86211d89f242b919"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_202249/session.json": {
+ "bytes": 2381,
+ "sha256": "702c037749fe676f3c77dcc1da54c435a0b13bb17e09293509055d5d0ab2f27e"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/ep_01/episode_live.json": {
+ "bytes": 5849,
+ "sha256": "26f0960afc2e6cab5e41311e61648eed86b5b52e3492d7c193802fc2ec046f3f"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/ep_01/episode_live.npz": {
+ "bytes": 8859429,
+ "sha256": "f3c5bd796d702d934d4d4f4fbc8b73c9f23274a0f1be1b29acca3bf27486fbff"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/ep_02/episode_live.json": {
+ "bytes": 5907,
+ "sha256": "cef0d589b65cbca26410f22faf696297c17f01bc2186cdb529ae9c922e7c148f"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/ep_02/episode_live.npz": {
+ "bytes": 12951573,
+ "sha256": "40d5d5f2432d46a672a19370a761a8717aab365a5138b7f125175202b253d701"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/ep_03/episode_live.json": {
+ "bytes": 5870,
+ "sha256": "102e7a550d659abe99e59c3a8bbdedaef63813b7c01252c67dbee1f3b701bb67"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/ep_03/episode_live.npz": {
+ "bytes": 8724105,
+ "sha256": "094e7204639c241da66ddc512cb155397e481cbf2f95fb7fdb627d2167a88202"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/ep_04/episode_live.json": {
+ "bytes": 5867,
+ "sha256": "fb9c9baad3f6699b905d2b109665e57f7f9cae70e8c878ff671fb08d981d8fed"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/ep_04/episode_live.npz": {
+ "bytes": 13506287,
+ "sha256": "11c9c587f7ebf5fc80ec0e4a07553ff2004dcb019e43591644281197da450a3b"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/first_frames.npz": {
+ "bytes": 494551,
+ "sha256": "cf4102eb7fec63de91fd0b48314b0f60f46ac2326874f87c186284a69f2618c2"
+ },
+ "so101_pick_place/robot/logs/eval_20261024_205852/session.json": {
+ "bytes": 2320,
+ "sha256": "4d52f1848fc19ceded5d1cd56824d22d3fa06466269c0fc47e458e5722c74cba"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/ep_01/episode_live.json": {
+ "bytes": 5860,
+ "sha256": "55bcbb4b56b74c68f9d32696932b50f2d2c17f99bfe626a79a7273ba2f240bae"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/ep_01/episode_live.npz": {
+ "bytes": 8943184,
+ "sha256": "aec4506bdf59763137e39b4bed256b038be158b8e20880a621a674ceece82b42"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/ep_02/episode_live.json": {
+ "bytes": 5855,
+ "sha256": "c83c666a35a2f7117440043e4e51e3df1f46c88a30451590aa69787bdd464189"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/ep_02/episode_live.npz": {
+ "bytes": 10059822,
+ "sha256": "961f3ca8e77651b47c97f82f47fd00efda2f5544c5747cacbab07188aebc9827"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/ep_03/episode_live.json": {
+ "bytes": 5865,
+ "sha256": "cf9abe78bdb2cbb13725a914848f6300027b6c5224d1c5be4aa0816bce5e03e1"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/ep_03/episode_live.npz": {
+ "bytes": 12066755,
+ "sha256": "1ee1e4bc4d0ea87da98b2099b7a7d8139c29fe5420cff9d9885bc559410b7577"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/ep_04/episode_live.json": {
+ "bytes": 5862,
+ "sha256": "0c6598c1a3489149f449a9c4a8893d5869fa859367e169ad2bf06253c086cff5"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/ep_04/episode_live.npz": {
+ "bytes": 9276179,
+ "sha256": "2a6ae6fc326733226b6bcd1a7b70b18fa3ee64ffb5d4d85f5c4978e7855f83a4"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/first_frames.npz": {
+ "bytes": 494480,
+ "sha256": "d33f386faee29b5b6e5b9b61b19b1a72965e3f31207034cb049a2598c2ca5c23"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_192402/session.json": {
+ "bytes": 2267,
+ "sha256": "169813e68ad904b663473cef411dd63340d2baf67a3a4fa35ee82f68f135674d"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/ep_01/episode_live.json": {
+ "bytes": 5859,
+ "sha256": "122accf7dde3a3e70d150c6ba99ee03cc8500a372982b989eafee897ffc02b06"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/ep_01/episode_live.npz": {
+ "bytes": 9069784,
+ "sha256": "0f058962490d3e6281cab7744199a67351045326bea2da706228d78115d3fc45"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/ep_02/episode_live.json": {
+ "bytes": 5866,
+ "sha256": "e8e99c3bd81dce31f0f19e6cc1c64ddbb5acbea8a55594beb597643708b9db3a"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/ep_02/episode_live.npz": {
+ "bytes": 8150746,
+ "sha256": "e61ec3b9827515061cbff54d87d2d8223b58b5b56b811a039cd0ac98ac459d8b"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/ep_03/episode_live.json": {
+ "bytes": 5861,
+ "sha256": "65252d31a524ffc0040a9666cbda324f03747e3f84436a0374a3cce4ae7d3858"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/ep_03/episode_live.npz": {
+ "bytes": 9005282,
+ "sha256": "1cd7b034cbf475c022591d647975fdacf427237d1af6fe1186cae7552d8c1af3"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/ep_04/episode_live.json": {
+ "bytes": 5878,
+ "sha256": "acd187e675a2adf51ccb012d1ef8cb615459a8b4829690361a85d76ab716fc48"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/ep_04/episode_live.npz": {
+ "bytes": 9384059,
+ "sha256": "b01a1a4f60f04f0b153f215067d62c40af4f167ac78aa814b71d9922313714ed"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/first_frames.npz": {
+ "bytes": 503003,
+ "sha256": "bb76716f08517d209920bb93073434177d884d961722d0ab14dac73156a380e0"
+ },
+ "so101_pick_place/robot/logs/eval_20261025_194447/session.json": {
+ "bytes": 2283,
+ "sha256": "1415927e4c9fb139baf2985de0e47af545fbba3cc9f573d723920a77fce61c00"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/ep_01/episode_live.json": {
+ "bytes": 5859,
+ "sha256": "0c55c92fdce6c4a74cca3eda9838291578333aabb7af692d12939ec621b6049e"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/ep_01/episode_live.npz": {
+ "bytes": 9359107,
+ "sha256": "aae81155b818c033345c37f68c077362666aeb5d8485dda3100a3f262630f090"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/ep_02/episode_live.json": {
+ "bytes": 5862,
+ "sha256": "a31efa3825b4b3bfaef6cf8ac479ffc9f82414616a5f713a940006e79569a3fc"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/ep_02/episode_live.npz": {
+ "bytes": 9291215,
+ "sha256": "045328ec81593c5e8ca38d91ec0206c459fe89ec2a3e5a39591347e1e0ea6d23"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/ep_03/episode_live.json": {
+ "bytes": 5854,
+ "sha256": "9bc3e6c629818d68af8bb4e8edeeb5c25f14b341e6961417e14e3f1dbc79edc8"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/ep_03/episode_live.npz": {
+ "bytes": 9987339,
+ "sha256": "35a5c5e7b77bd174a7012b077c5d963adbed16013115a18d158a080b07bdb4e7"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/ep_04/episode_live.json": {
+ "bytes": 5864,
+ "sha256": "6e8a5a448160fe63851cdc0d4199fef088b570859fabdda43e97fda2b801f6d3"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/ep_04/episode_live.npz": {
+ "bytes": 13738852,
+ "sha256": "f7a50a7cdc5663e3175ee851e95e2165616cabb378984f5140af6a36e4369e63"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/first_frames.npz": {
+ "bytes": 511489,
+ "sha256": "d757a0aadda2b0e36e340fcd74872518a39ba767699c496f25aaa313332d4262"
+ },
+ "so101_pick_place/robot/logs/eval_20261026_131348/session.json": {
+ "bytes": 2276,
+ "sha256": "6115702eca3f5567c3a48809979188c7b2cee1bd4014ab98b266c055bac5b4e8"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/ep_01/episode_live.json": {
+ "bytes": 5862,
+ "sha256": "de8184225d2bb15d49e0bba036f9f05757d638ce2b765a81cfc54a780ef7db0b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/ep_01/episode_live.npz": {
+ "bytes": 14199576,
+ "sha256": "a828f9605e25246de5cd59ea1ee07dac49dce4b965bd2bd0dfbddc443836b4b5"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/ep_02/episode_live.json": {
+ "bytes": 5881,
+ "sha256": "283c8b68f5fed7e72d0fce616be0e7de692ece3e2324c8b66089dec085dcd203"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/ep_02/episode_live.npz": {
+ "bytes": 10511655,
+ "sha256": "1f4c2a42336ea34af6e0073ff7d27667c98fe2db466c567973757bdea2e8c3a8"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/ep_03/episode_live.json": {
+ "bytes": 5864,
+ "sha256": "27ba29bf3b2fd74dadfd9d01229f9e4b81f3c28326e3e8f3c600e33f48f42431"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/ep_03/episode_live.npz": {
+ "bytes": 8449644,
+ "sha256": "0a500eb1c067a7cda96ae23c0041cd522f24f44bf928b621193dc27331656665"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/ep_04/episode_live.json": {
+ "bytes": 5864,
+ "sha256": "41dcf9f262ccbb0510171c46f22f0d6fac14cbb4897fd89580e7a5f9a8facf74"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/ep_04/episode_live.npz": {
+ "bytes": 9031729,
+ "sha256": "e2151ab7944a5df975929d548643dc5694d5b646f3d5bfa13814a9a3325eb096"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/first_frames.npz": {
+ "bytes": 520157,
+ "sha256": "31a56134f3e28ae07e06fd3d510a4d7ed24698595d67c818f8d3523966b4b76d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133039/session.json": {
+ "bytes": 2307,
+ "sha256": "6ee0f38476c1e213be3312c3c2bc26fd38f9785bec6315ccfc89f6fe546e47f3"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/ep_01/episode_live.json": {
+ "bytes": 5843,
+ "sha256": "c75a8aefaa8d4d770d00ff034d979672f88d9028e2732fae318f4e915ae0305b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/ep_01/episode_live.npz": {
+ "bytes": 8096670,
+ "sha256": "954046310d616bd917573e5ac647f6a84915fc688659fac5a5b01edb87db7f0b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/ep_02/episode_live.json": {
+ "bytes": 5893,
+ "sha256": "95c883c764813dfef61c08fa34f05c89a9719404aa5198bbf5f4fa4d0f9c9271"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/ep_02/episode_live.npz": {
+ "bytes": 13833527,
+ "sha256": "a1176a38d7a395ff40d1ffb2058e9f9109e045a341805b2bdbe91b691249201b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/ep_03/episode_live.json": {
+ "bytes": 5894,
+ "sha256": "2f4dcebf6f75dd221f0a70ead5c7de0af0b98281d704a5e50ae203c8357a924d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/ep_03/episode_live.npz": {
+ "bytes": 11964826,
+ "sha256": "e8114423c10ee4c6bffa828a43713011c4bf44aa4c10a7c7d3cfaf99af59fed8"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/ep_04/episode_live.json": {
+ "bytes": 5858,
+ "sha256": "49a92795c1f22eea9f912d3b6e5825b71c5b4b364709a38f66a623cd919467db"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/ep_04/episode_live.npz": {
+ "bytes": 8777904,
+ "sha256": "e66ef7fc0e5bf31bc379d05404f8d470a4e29d3a0c9d80b76b806bd0ff063df2"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/first_frames.npz": {
+ "bytes": 508446,
+ "sha256": "8c808427c86c45c7a1de18fb908623099da9681806086bcdd67882283455a8a8"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133521/session.json": {
+ "bytes": 2345,
+ "sha256": "59009b97a6700d81703e4bcc3c758ce9383d6b93128af4a59d724160e5c05ed5"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/ep_01/episode_live.json": {
+ "bytes": 5864,
+ "sha256": "48cf9455b54e8dacbba1f294fd1dc9195ec6a87811742be748099074c8b2e5b8"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/ep_01/episode_live.npz": {
+ "bytes": 11460947,
+ "sha256": "d6b8fd36be3a66e3e8375a5497beed6f9cf4c9949dae0b6b1d36c37d70a173a2"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/ep_02/episode_live.json": {
+ "bytes": 5870,
+ "sha256": "ab20eb5a67bb81e0685ff2b65db349e619f88a59c06b52bfe687d512b98fecc3"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/ep_02/episode_live.npz": {
+ "bytes": 11378997,
+ "sha256": "71eb88c1e4b858ef80cb09529c602c0970013d49e8fd43e532b8e9e39ee3a8ee"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/ep_03/episode_live.json": {
+ "bytes": 5902,
+ "sha256": "41ee3323373a1bad791ff2bbaa82a4ec27857b2eb9fb7278fc2bbf19f6122b2f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/ep_03/episode_live.npz": {
+ "bytes": 9976320,
+ "sha256": "e2827de69b6fb0c1c68e336635ece41acaa01ac7473a9271ca2e9bf7a25da140"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/ep_04/episode_live.json": {
+ "bytes": 5861,
+ "sha256": "1fcd4a2012a906d156f43c08b474b1928002bf68518656632704f4939fcc11f3"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/ep_04/episode_live.npz": {
+ "bytes": 8672021,
+ "sha256": "06b6d35b37d6429073192fb79be4979ca6bf0459f16225703f44c33aae2f470d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/first_frames.npz": {
+ "bytes": 508294,
+ "sha256": "5f978b772cb570dbd50ec871792222db4beb92c779e403e922a27a0093ea0889"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_133953/session.json": {
+ "bytes": 2307,
+ "sha256": "927a30ec06089cd43867d20f896cabe70317f7e323c19ca952f7859c704dab3b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/ep_01/episode_live.json": {
+ "bytes": 6177,
+ "sha256": "1b0a7f5e509eee4ae8c3666e5dab761769e058a148815533044cc98beaa35e57"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/ep_01/episode_live.npz": {
+ "bytes": 5869280,
+ "sha256": "20a388c2dbc0d8ec23f25490e33f6187274239a117614ba1cd84ab3a2e4e9e13"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/ep_02/episode_live.json": {
+ "bytes": 6162,
+ "sha256": "d7fa18d371b3f4e242208d8f84ff48bd58a98fe7ddb04117531e30e9c52f12e9"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/ep_02/episode_live.npz": {
+ "bytes": 14820168,
+ "sha256": "5e9cfe5cdaa4b7968bb9881009a0c45d4b308f6c47688ee24253208e4755e096"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/ep_03/episode_live.json": {
+ "bytes": 6188,
+ "sha256": "ca45be35b41072c78a803e1ba3be21b57b51ab398b6cd140efaee678b073cfca"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/ep_03/episode_live.npz": {
+ "bytes": 8644779,
+ "sha256": "687898529300233c8bbc8e27763cd1d2f3abd690c691522e0d94e03ee6344749"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/ep_04/episode_live.json": {
+ "bytes": 6185,
+ "sha256": "d804ba92dd61c9686584fabe9c57ee5c8d0b6cb7db72f5cd381fb7ecdc38a2ed"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/ep_04/episode_live.npz": {
+ "bytes": 14794748,
+ "sha256": "6a32144a899f61b029d896cc26b8fb22391548c29f82d2f7dcbd00fa522efdc7"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/first_frames.npz": {
+ "bytes": 506761,
+ "sha256": "c8c2f979a2157c21c19f4c44a2d075349f28dd6ed655b48c09c046e54d2f1e5b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134411/session.json": {
+ "bytes": 2297,
+ "sha256": "48f8ddc1d01ab8bdfc0c6530cee512c1243d9a4dcbcefe39fbe641678bf1910d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/ep_01/episode_live.json": {
+ "bytes": 6137,
+ "sha256": "61f1526c107908dc060c27b3bb67c4f59207fbdd645c79375dbe7603b6d0fc7d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/ep_01/episode_live.npz": {
+ "bytes": 7090484,
+ "sha256": "3a8a45707a09403be51d36f6e8074240e570ab514532edf4b59af607f0f16390"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/ep_02/episode_live.json": {
+ "bytes": 6134,
+ "sha256": "2a55561ec1d05ae274a7ca4253337e6f6e3013eb68f26ed638c5bb117d9e2529"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/ep_02/episode_live.npz": {
+ "bytes": 7222084,
+ "sha256": "070a272d36c7556ed8ca91d43a218a983542457f0caf5a259659842f3018ffd9"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/ep_03/episode_live.json": {
+ "bytes": 6147,
+ "sha256": "b8db8d250a1ac2e8dfd8633296ababcf013fcc5ca0089dde704004f3b851627e"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/ep_03/episode_live.npz": {
+ "bytes": 10505955,
+ "sha256": "35c42fcf5f48661f8b0607693db28e2229638667f94d8caa0034e0454f9dfc08"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/ep_04/episode_live.json": {
+ "bytes": 6147,
+ "sha256": "8cc4b51fd65948fa4d3adeb4a06b7155b735e96d6d6d70f97a72f225cc5ecab9"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/ep_04/episode_live.npz": {
+ "bytes": 10607176,
+ "sha256": "dc33ab22b264771fbbf46197bc98d391932cf6cb0eb2108232d6687cd693900f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/first_frames.npz": {
+ "bytes": 517190,
+ "sha256": "86c7ffe48709528c99073b0c1f1a55a731b7eff227c5274b03b66c3c5e8f09a3"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_134903/session.json": {
+ "bytes": 2281,
+ "sha256": "7dd9ba457920963529a0c98a897541575bdfaf152f46659f33dedf8e9688c5ea"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/ep_01/episode_live.json": {
+ "bytes": 5876,
+ "sha256": "77f74f92df38a1e8d5484c805d743828237142ba3fcfced1662aec39771e5add"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/ep_01/episode_live.npz": {
+ "bytes": 9387924,
+ "sha256": "216eb8bf715ee1c01d9296503d31fe01609c92f83f7b3d76568411cfee904cb1"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/ep_02/episode_live.json": {
+ "bytes": 5858,
+ "sha256": "391a51cba7acd4848576496bc3270b92fa99c0adc1e2e9d0c3efa4eeb48478f7"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/ep_02/episode_live.npz": {
+ "bytes": 9607738,
+ "sha256": "2bbb9a7a0166d82a68ac2f48ff514bebdba9be9e06463d73cb12dea82f1d75a0"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/ep_03/episode_live.json": {
+ "bytes": 5867,
+ "sha256": "8c77ae7bb78c0752275ea2c21e95ffce0876cfe8d9cf5e25422756e486103b3f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/ep_03/episode_live.npz": {
+ "bytes": 9657203,
+ "sha256": "147efeaae8026d9736937c963451ac933bb7201424eb4117960bfe1457be922b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/ep_04/episode_live.json": {
+ "bytes": 5860,
+ "sha256": "527c3ed0abdcce120c847184655056231bb864bfdcaf7a9ca65a2b3915fe4ef1"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/ep_04/episode_live.npz": {
+ "bytes": 10010561,
+ "sha256": "778dca3a1964486907dd68d106a0f852e2ee935648e93ce42dbdd410424d0a54"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/first_frames.npz": {
+ "bytes": 520121,
+ "sha256": "3baa5419e9dd0d32b1efb3fa66928abfb017a1cfbab786e92974ff66baf17c96"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135259/session.json": {
+ "bytes": 2290,
+ "sha256": "032cbe65dac0dfa1c0ef9dcf45c12948238d916231fd1c8b741e4af7940f9ff9"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/ep_01/episode_live.json": {
+ "bytes": 6146,
+ "sha256": "0f82ece986d0b6e9914db3f2d701fe6044c5ec209dda1010a5d068da5427c8f5"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/ep_01/episode_live.npz": {
+ "bytes": 5296091,
+ "sha256": "4288da99e2ab527c9f0f71681b486c6295cde67bcf05df003899cd494b3902c3"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/ep_02/episode_live.json": {
+ "bytes": 6161,
+ "sha256": "17344ffc26263057f71ddb0528311da3cc35a5704c983a2e423e61e889b98097"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/ep_02/episode_live.npz": {
+ "bytes": 6108185,
+ "sha256": "4077a0014ecbf15ff0a2d593a4a8a221c4d90d70df745e1ef806b5c65e4d10a2"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/ep_03/episode_live.json": {
+ "bytes": 6163,
+ "sha256": "e801d332035c94b56757911f61a9b19c99aa965222e5b45705ba22d9d4951301"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/ep_03/episode_live.npz": {
+ "bytes": 6871913,
+ "sha256": "84ed4f65b1c4d55f3fb7d225609c05d53275af94122d8328e6460330ad31ed94"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/ep_04/episode_live.json": {
+ "bytes": 6153,
+ "sha256": "d1b1b9767625b193a4b3257a45c6a04a84214976428bf8c45195d64fc312c841"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/ep_04/episode_live.npz": {
+ "bytes": 8413669,
+ "sha256": "6dd618a69988709a97afb3c9bf52c51bb2190c2c4c195a2363a323a82df1d548"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/first_frames.npz": {
+ "bytes": 497017,
+ "sha256": "47fcb0e25477d7aa29bb5132159e7a033ae8249b6e366f03fccd7f8cd79e77ae"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_135657/session.json": {
+ "bytes": 2313,
+ "sha256": "115f4d594c90dcd1d7258cdd56e2fb756568cc33aa9109b0d15694113ec923ca"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/ep_01/episode_live.json": {
+ "bytes": 5865,
+ "sha256": "96c31ee685f7d0b7f66517a79133cafc51fa03ca1bd033b602d78f5449e38b8f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/ep_01/episode_live.npz": {
+ "bytes": 8262708,
+ "sha256": "03c3fb87752c29c42e3868e83b293fdb2ddc520fbaba83a5dbe7fac0dd36c217"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/ep_02/episode_live.json": {
+ "bytes": 5873,
+ "sha256": "0d1499f377584d77d594a626da110069fb449dfa56b5beb5d7a2d57c6a7c59b4"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/ep_02/episode_live.npz": {
+ "bytes": 9966683,
+ "sha256": "435baecb51ae091d15c89ff6560866e9225940ca2f682044856cb100a7be281a"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/ep_03/episode_live.json": {
+ "bytes": 5847,
+ "sha256": "769a36cc006c52f22f533ec5034e8577162fbbbca0d644902d1864cc59ae8575"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/ep_03/episode_live.npz": {
+ "bytes": 7517045,
+ "sha256": "1efa49a19281b6b111f98762b2cae073fe9128fbbe15692a7bc713e71d6795fa"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/ep_04/episode_live.json": {
+ "bytes": 5884,
+ "sha256": "03ec20101f88667db5e52d16f03c862e9d4033f13e55ca49c1d4634f387fa40b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/ep_04/episode_live.npz": {
+ "bytes": 14824560,
+ "sha256": "834833cfcb1bee6aaea415dcc7d8a0e0b60f6c5c2aa4dbc3a69f3e1c1761a293"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/first_frames.npz": {
+ "bytes": 500059,
+ "sha256": "3033786675a4c102d46940402640e5b8caecde87a69db7d902f11dca0fce0e6e"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_140036/session.json": {
+ "bytes": 2318,
+ "sha256": "dab313aa11679cd24b88d0711baf8e461afde9750ea2bd93594af6e0ee540d2b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_01/episode_live.json": {
+ "bytes": 6151,
+ "sha256": "c77f21963a47e40bf697f79ad6cbe5a549712313cdd56ca4ad656bb456a39b1f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_01/episode_live.npz": {
+ "bytes": 5944265,
+ "sha256": "02fd84a70e16c614f288a199f74939e2abf4995e9ce5643e09bd7e96b79426cf"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_02/episode_live.json": {
+ "bytes": 6145,
+ "sha256": "dd02f24eb23595415e134a4d4897ea3f771b720482addaedd972d8d9623da2e6"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_02/episode_live.npz": {
+ "bytes": 5688204,
+ "sha256": "cb1c8c72d7823109655d4e63ef4f46e1f691137106f84d2e22ca73fa6e15c567"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_03/episode_live.json": {
+ "bytes": 6162,
+ "sha256": "d5c20e6c96d60ae59bebbfb1a32db957a6847c757424782b8365efbbdc1b1841"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_03/episode_live.npz": {
+ "bytes": 7179763,
+ "sha256": "558618282a9d4c2699053b9811e79de7a8f84e493ffb16ef71f1f275376d8d73"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_04/episode_live.json": {
+ "bytes": 6152,
+ "sha256": "0a93a3b36d53ac019c3bdb40377769a23642182790f35f505a2c5de7ce7aa7ba"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_04/episode_live.npz": {
+ "bytes": 5599220,
+ "sha256": "319a1642dcb917f37bec5d8b0f0a2c21e376e2b13507823ab303aaf15137e3ed"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_05/episode_live.json": {
+ "bytes": 6223,
+ "sha256": "67fb9d82bf9fed30be35c5207ef85bfdd3e12b4bc71ad37a7decb738a157529e"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_05/episode_live.npz": {
+ "bytes": 8526892,
+ "sha256": "773de39e47c5b26a3f320b2e3ac2e7b4c0f2a6ef1a6404a895c0665b3372ac1f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_06/episode_live.json": {
+ "bytes": 6160,
+ "sha256": "60a5ba550b636de4584edcb8186bc73e64cefbea9827fdf0c61abbe4a4e34723"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_06/episode_live.npz": {
+ "bytes": 13121594,
+ "sha256": "caf191a5bdcb46974c09b51bbdb10a88c84572d4ad884c2e7cfd55021ded7f1b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_07/episode_live.json": {
+ "bytes": 6155,
+ "sha256": "9a6bf0194f098961aa07584feca8b8236f5ce569f14a0813eb648f381c7a69aa"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_07/episode_live.npz": {
+ "bytes": 8566840,
+ "sha256": "701dbe2a44e1405911ae6705bee0d5966066ebc8e21b1e24681cfe7241d9f425"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_08/episode_live.json": {
+ "bytes": 6154,
+ "sha256": "dfdbc412c8360f93918d696919d8b332f52557efcbfa0024e94d35e0eee1f1ef"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_08/episode_live.npz": {
+ "bytes": 5629984,
+ "sha256": "bd08265090504ef5c8eb7e1afcc8370a31cefaf00c71e16dd1a874d6c2795606"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_09/episode_live.json": {
+ "bytes": 6164,
+ "sha256": "78b4cd7a7ed53dc7d4afe2ddb2a0957ce24bf1a3c0e1fa70e1fee011ed033574"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_09/episode_live.npz": {
+ "bytes": 12091180,
+ "sha256": "92c563694be559db896778aaddbd67c5847752b5656e63c593bfca9c16e71f8a"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_10/episode_live.json": {
+ "bytes": 6157,
+ "sha256": "0f2d50cdb9e079a3e835687ddbc245423f0552fe2a4104944440e390e425c2b0"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/ep_10/episode_live.npz": {
+ "bytes": 6076766,
+ "sha256": "7b7c5aadc6fc095116d1f70675268750c812e6a1a20e837e3def56dbf0e37758"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/first_frames.npz": {
+ "bytes": 509168,
+ "sha256": "51ad998114e528adf5a283f0ea5c554de1caab64df4f7a3e67fc67779c10bc90"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_145520/session.json": {
+ "bytes": 3929,
+ "sha256": "19fbf1662a3fd078bf698054a3729cb76bb4fdf2a7b0432fcb26ede4ffcc4c62"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_150916/ep_01/episode_live.json": {
+ "bytes": 6165,
+ "sha256": "0efb46fd1e5a8c7773b865b1b46203a801e1a4e3b6397695fa0a947fbe17bd7d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_150916/ep_01/episode_live.npz": {
+ "bytes": 6062562,
+ "sha256": "2360fd5dce93cc5200c97bcd9a29a66bc7116b198cb45a3c5f83a325143506a7"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_150916/ep_02/episode_live.json": {
+ "bytes": 6161,
+ "sha256": "585ec5ff2b28ceb5e3aafc4ad1c3578e2ca195c153d833a2ab7d056d4bef2c77"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_150916/ep_02/episode_live.npz": {
+ "bytes": 5166469,
+ "sha256": "506ffc2f6c03c9523efd90a11b32962d16eeb6c3d7cc9cb33b474d6c9d0b3190"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_150916/ep_03/episode_live.json": {
+ "bytes": 4416,
+ "sha256": "403976cf835f32bc3424b711aeee644cf51da695a238ae2f0f5aba173e314c4d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_150916/ep_03/episode_live.npz": {
+ "bytes": 2482,
+ "sha256": "ca0c20af8871763c44cb47109aa39fb05c0b336db91f9843ac02fb20eb13fd42"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_150916/first_frames.npz": {
+ "bytes": 518667,
+ "sha256": "818b4f406efeedafa6c7f45c1c269b712af9c29ffcde0b767f49a5cd60c784cc"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_150916/session.json": {
+ "bytes": 1744,
+ "sha256": "dea539aa0a4152aa6609ae65d04a728d96181daaa3521fe4b4c7bee1d280ad0a"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_01/episode_live.json": {
+ "bytes": 6166,
+ "sha256": "1ec691a4d9bb3e3d1a4f26e0bd8cf2491c9a965d3d9d711628ab9ae79b027427"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_01/episode_live.npz": {
+ "bytes": 5745740,
+ "sha256": "38ae77f464c773acee3e5ce1e0eb610b8d1902468e1755a3b681cffa71f8bf68"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_02/episode_live.json": {
+ "bytes": 6156,
+ "sha256": "a87214f77dedfd65dc54f1e4af9d01fd8930a2a18095a22bdb0def7f07ef9943"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_02/episode_live.npz": {
+ "bytes": 5910204,
+ "sha256": "e735548dd38ab53a37c7709cfaad975107b3dc90ae142ba4f89530e2740b1c39"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_03/episode_live.json": {
+ "bytes": 6139,
+ "sha256": "b8c70e05f586b215990a870e6cbf2801d00690478897ddc01d8ac5d1d7b36d52"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_03/episode_live.npz": {
+ "bytes": 6317168,
+ "sha256": "e464796a71ba53348ba0e08f3900fb38e4b61816e129e0d03c1738b80f2c55ec"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_04/episode_live.json": {
+ "bytes": 6153,
+ "sha256": "1509256dfd104cdf692fd6cbfa05857f80b98f510add8fa913e671235b455e79"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_04/episode_live.npz": {
+ "bytes": 5887279,
+ "sha256": "249ce25c6010c931bbb74fe849286dd62408fe04bef79b55c4f76ff76df36fe3"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_05/episode_live.json": {
+ "bytes": 6163,
+ "sha256": "92fba5238b8051cf64e8325668a821b8a4e3d3807634ce05b7b4ff678d799075"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_05/episode_live.npz": {
+ "bytes": 13604404,
+ "sha256": "4668c595f44610d161a5f114f9a57a4f02b5c1e68ff298bd03d3b8ba54c45037"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_06/episode_live.json": {
+ "bytes": 6137,
+ "sha256": "ad359186e4ca46754ea3ddd6443e5738299fa4c660287526dcd757e56cdfee5d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_06/episode_live.npz": {
+ "bytes": 5288714,
+ "sha256": "a11cc59ca167d1fa76d1fec0a9774daca100c6982c028d5a1d934d1740effbe0"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_07/episode_live.json": {
+ "bytes": 6158,
+ "sha256": "ac4c64c842de0a79f3b95637f215cd923a24b6a56cc477849d1649c54c0448d4"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_07/episode_live.npz": {
+ "bytes": 14643435,
+ "sha256": "950ea6b15ea5920554829619ff4af138af4f9c08d88f9b325cbbb0670b747da5"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_08/episode_live.json": {
+ "bytes": 6172,
+ "sha256": "19056e263e5022093731e848061109c15f7e32ba8f4655f49896c31f6216c05b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/ep_08/episode_live.npz": {
+ "bytes": 13280264,
+ "sha256": "0bfe39cf3e45c1d94a8eff715463e43a9842788f53a206ed9f862e450556fee4"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/first_frames.npz": {
+ "bytes": 515632,
+ "sha256": "28a3b531cd0f60f596b9f412ff4222c2be8df71e607b625e6ff258bcb39cffd3"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151136/session.json": {
+ "bytes": 3331,
+ "sha256": "621ecbdedbe657a83dd3d68b39ad84e154711c28acab76165b1667c833db3dee"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_01/episode_live.json": {
+ "bytes": 6179,
+ "sha256": "0426c6b884ea5ca57eae36b51f6ff4be0d54812f7dec531d91c57dea9d899d5a"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_01/episode_live.npz": {
+ "bytes": 7001541,
+ "sha256": "9caf53fc7bccf4d41f19b885e408fbd262e5566f648e418a7f8dd62ede641963"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_02/episode_live.json": {
+ "bytes": 6160,
+ "sha256": "75624db4e11fc62c64f6167df7d8a2c0ba177241d13f79fa9a737a42787b0f8f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_02/episode_live.npz": {
+ "bytes": 5736934,
+ "sha256": "fbea3558af99a50ebebd98d9e55c0f558cb55dc07528e3a48f8ae3bc6aa78956"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_03/episode_live.json": {
+ "bytes": 6148,
+ "sha256": "af7b3ddb31016c5b73b2d70de3f3ef00c69d712c701186ee257c05c4c86577c8"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_03/episode_live.npz": {
+ "bytes": 6104888,
+ "sha256": "0965e405fac9fcb0703d60bee67dba61a11222361a6bd58e135ec6f97af7aba1"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_04/episode_live.json": {
+ "bytes": 6135,
+ "sha256": "372d8dfb91bf23a9022d7173f41769fb2f2d69c556ff553998143cabfe005128"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_04/episode_live.npz": {
+ "bytes": 14711339,
+ "sha256": "5ad92548b1d04cd962a799cf3acda08026c9f80b3d518ce948b6a2ccf0618f41"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_05/episode_live.json": {
+ "bytes": 6143,
+ "sha256": "a5511f01bbf55ff9d8e22b8ec410bfb8fa12caf7c95cb908d43dbc3b7d4796fb"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_05/episode_live.npz": {
+ "bytes": 6646022,
+ "sha256": "4aa0bc4e7a74618ed13de08f35a6e81c01accb0c125052bc606ff84e52247d4b"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_06/episode_live.json": {
+ "bytes": 6263,
+ "sha256": "1e28d6d79605909a87f933aa489649d0d1758b49b5f87d7dff2cf7467c278d9f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_06/episode_live.npz": {
+ "bytes": 13804156,
+ "sha256": "509b0180fd848a346f1c6880f75713d28a9324153630863cd5d8a5b5bb184e22"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_07/episode_live.json": {
+ "bytes": 6155,
+ "sha256": "b069e620ca362a73ca9a20c90718a1cd5a03b70928e662a5f33185cd94fce9a0"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_07/episode_live.npz": {
+ "bytes": 6103574,
+ "sha256": "f594a094e354f11bcc7c49cd2d40497b4771c240d298bbfb66974b9da1b8aef5"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_08/episode_live.json": {
+ "bytes": 6140,
+ "sha256": "c3060b992b94facdfa83efe8a3703c47e2af04861a1448762bee313ad19ea7a6"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_08/episode_live.npz": {
+ "bytes": 13634730,
+ "sha256": "95e4bf2bbea69f44eeb244ebc06f3a24bc849363abe1af0f302e8713b8fa51a5"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_09/episode_live.json": {
+ "bytes": 6176,
+ "sha256": "9c99ea926d6eec5e604ea9a3803562e5f0f848d625aa2c3bbb7f703c902a6bf7"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_09/episode_live.npz": {
+ "bytes": 10396322,
+ "sha256": "03024a938dc9bdf6c4fb729d635d91cba691ce8856dedc1032741a853338ac52"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_10/episode_live.json": {
+ "bytes": 6156,
+ "sha256": "6a7be6e19e37deefbce709d3569eafb067b7d216a0629138afffe148ea15c08a"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/ep_10/episode_live.npz": {
+ "bytes": 11223575,
+ "sha256": "fe5816fdce9600b1c5d72736a23cbda3808a1a016f8326c395208874a8ff3507"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/first_frames.npz": {
+ "bytes": 513581,
+ "sha256": "0e84435ff479a8935b40f1cb25c9d08cb929659d18dd088e630d8ca1bd6e679c"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_151953/session.json": {
+ "bytes": 3906,
+ "sha256": "3aeb6099a6a1b4d54851fee7d8bd7663695b643398cc528f7ec54042f9775b5d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_01/episode_live.json": {
+ "bytes": 6154,
+ "sha256": "65d97520b800db5444afef6cdf0e77513b847b2a67cb4b01714e50bd869850b5"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_01/episode_live.npz": {
+ "bytes": 6329535,
+ "sha256": "fa585552615e0c08b234235d7d721d65f71b5a5cf364e76e50e59aa90ad38e55"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_02/episode_live.json": {
+ "bytes": 6150,
+ "sha256": "eea0970e7c9837819d5f09dc7ab51eea0366f6b00cdf23f6f3a8a12226ffe860"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_02/episode_live.npz": {
+ "bytes": 5786878,
+ "sha256": "37246380aa9d553dfc2017599dd6659ee3b2d3dcf3ff5b157dd07e3a5140f3ac"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_03/episode_live.json": {
+ "bytes": 6156,
+ "sha256": "310320df332c1c95d93bbc12d7fac8ba8eca1a0f3b9de19a6906ae59cdd38e41"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_03/episode_live.npz": {
+ "bytes": 4873824,
+ "sha256": "f8c767535a70067e07f7a2db1fcaa79f9d454941f91631cb5b065947ec4abe49"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_04/episode_live.json": {
+ "bytes": 6148,
+ "sha256": "c76fbaff0b791fab7733d1a8bbf8586d9189942816aae185558034b6059e4cc7"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_04/episode_live.npz": {
+ "bytes": 8414107,
+ "sha256": "79fa062d29d7e04c9e7653a04af089d61d8b362720635e1d11510050b30e2306"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_05/episode_live.json": {
+ "bytes": 6150,
+ "sha256": "5af2c0f60b449e634bea0349a75ab09e01f924e46c19d5d5d360f06bdb3f7aa0"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_05/episode_live.npz": {
+ "bytes": 14361164,
+ "sha256": "2c50c7a41d0ec52b5a430b0ef372df72b6c02ddfb94829185aa058c744a1a52f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_06/episode_live.json": {
+ "bytes": 6140,
+ "sha256": "f2f6e960ee52ad6aa1d74f62e971252735f58cb2d3eca4f54157b05afbe21ee6"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_06/episode_live.npz": {
+ "bytes": 6357044,
+ "sha256": "1c15ad6972a0f265dd1eadc461978f1b39dac1f3a1d6ddc74bb4cb02cc66038d"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_07/episode_live.json": {
+ "bytes": 6138,
+ "sha256": "734d72cc7bea0b4c962255b433b36b448f5ba19cf8c5517f84548ef8f3248f96"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_07/episode_live.npz": {
+ "bytes": 7096209,
+ "sha256": "aab472092db30da77f6e50d75664415df5c39a5ed041b08451e596153ab2ba62"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_08/episode_live.json": {
+ "bytes": 6156,
+ "sha256": "06164d3eb64d9e0756d77cc82aa2cf53f1cc060e1653fd88a13aebccf97de575"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_08/episode_live.npz": {
+ "bytes": 11262499,
+ "sha256": "7159051f01a5eb350b3de2879516ed04e219c36c9854bf3bbaabad646dff7ab0"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_09/episode_live.json": {
+ "bytes": 6155,
+ "sha256": "a3af9a30167138e497d375f230b2907a7af36790b8f237227ab7107f22902b08"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_09/episode_live.npz": {
+ "bytes": 7038859,
+ "sha256": "83dc70f8dc86e4a60885efc90c35f37db8f19d1210a94560fa82d95289c28c7f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_10/episode_live.json": {
+ "bytes": 6169,
+ "sha256": "dabffd897905a3cd2b7eb62e8a282561edecd1fcf3123ccf88d152139821b7e4"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/ep_10/episode_live.npz": {
+ "bytes": 5952938,
+ "sha256": "4bfc64d2f686d986a5a2f7565145894a643def17f077a50bf726b01c2411f324"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/first_frames.npz": {
+ "bytes": 509859,
+ "sha256": "97cc64b193a773d7640c43514573500bb7afb71cd768b879918175471379e993"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153045/session.json": {
+ "bytes": 3845,
+ "sha256": "7c0b2282826912524fdb3acd2543896190335c2059a73ecf66e74b3457ac1159"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_01/episode_live.json": {
+ "bytes": 6159,
+ "sha256": "cb2e906479efeabcea1fefa60e066778827991ef308bd472704ec620d6ea83c5"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_01/episode_live.npz": {
+ "bytes": 5799074,
+ "sha256": "1cbf3d50a4581098d1fbca74f18cbfe4e8e484715bb912f86756976fe142d1db"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_02/episode_live.json": {
+ "bytes": 6152,
+ "sha256": "8abbeebcfbfb940d5628720e1a376129ffabbb55fa2041cb803246f94f294638"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_02/episode_live.npz": {
+ "bytes": 13822166,
+ "sha256": "8e63e25524f72420e57a9faad37e4addb438a94d0ff8cf99935010300f10e744"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_03/episode_live.json": {
+ "bytes": 6148,
+ "sha256": "9539abf071129ce5fe41579ed7b5a2894c2465552116963b5abdfd1bab9ba939"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_03/episode_live.npz": {
+ "bytes": 13807602,
+ "sha256": "6c64fbb86e7405648b2c85d8185874faf311dd21cf11b5f6df035bd84dd19b1a"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_04/episode_live.json": {
+ "bytes": 6158,
+ "sha256": "3122f145509b45012c5ef6413b6db22844a519973225dbab50ce49dbb80a6252"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_04/episode_live.npz": {
+ "bytes": 13756623,
+ "sha256": "a49ac0e2c57e0d299e03c97bb3f6bf417e135ea0a0a7fbbf29889710aceeca9e"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_05/episode_live.json": {
+ "bytes": 6174,
+ "sha256": "d10c2e0bb296beeaaf13af28fcef59ae6effa78e94dd91600dd12f25fe5379da"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_05/episode_live.npz": {
+ "bytes": 7530684,
+ "sha256": "5db071784d83aefd3014c88e8341c2e9a481f3e1d005eab0be328d934e5fb9b3"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_06/episode_live.json": {
+ "bytes": 6152,
+ "sha256": "003b8814655f4c684fd995faa299390a2c1c68114299646519fb29d529be6826"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_06/episode_live.npz": {
+ "bytes": 9423509,
+ "sha256": "c734ef866ba3251dee726cb9cdd6c975adb2aca3cf69efd98bab5d2da82d15ef"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_07/episode_live.json": {
+ "bytes": 6174,
+ "sha256": "222729b7abd014ead63c3d287d289d936a19beea6d0618c04a8e84c8de16fdad"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_07/episode_live.npz": {
+ "bytes": 6601580,
+ "sha256": "081ba7f1d084b419dc922e6b644130aac60d4ab8af08c1e67511df1d1072a636"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_08/episode_live.json": {
+ "bytes": 6170,
+ "sha256": "448aeefc9ce93f5edf59b8c7e6f966df317d52975e0b32f267867b742d6283de"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_08/episode_live.npz": {
+ "bytes": 14314305,
+ "sha256": "db775f0f6c924073f3f4b1ebe1feec0570c96ee6e4be91f3e674616113fc4769"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_09/episode_live.json": {
+ "bytes": 6135,
+ "sha256": "ac4c2a4400a53451dbb491732f1b5a9f0eb3a662d278d2551fee0eee9c945d08"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_09/episode_live.npz": {
+ "bytes": 5723215,
+ "sha256": "d64f1edefb1dedd01ece86a1eaee0c8733cf0e9f052512be87731c3d332543bb"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_10/episode_live.json": {
+ "bytes": 6152,
+ "sha256": "08b2b493caee3687dfad0a6164abef51feccfe7a1cbea17b69bda0496fbf199f"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/ep_10/episode_live.npz": {
+ "bytes": 6043293,
+ "sha256": "21a73bfd3ebb5b900148e1506bc626346906224c13ed7abe011ee15a154b5c2c"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/first_frames.npz": {
+ "bytes": 513967,
+ "sha256": "1b37ef5b44d4e2f2d6ae18dd97f85b3b9b5315b1b3c476008289f9a5ce6d812e"
+ },
+ "so101_pick_place/robot/logs/eval_20261027_153943/session.json": {
+ "bytes": 3813,
+ "sha256": "a0c42ba3d8e188a4f076750e0aa7e7b58b8e2da7f6054e6d0231df454efb6f9f"
+ },
+ "so101_pick_place/robot/videos/screening_20261027_4x.mp4": {
+ "bytes": 11445403,
+ "sha256": "10491bb1a85653428eff0509fe7a2a76c5259a7cb4a961decaf28e5103805b8a"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_01.mp4": {
+ "bytes": 585423,
+ "sha256": "9d4bce4c410a6fec4e26472b65e0e4b2b9a65750b6d1416d6c243995a10162fe"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_02.mp4": {
+ "bytes": 566372,
+ "sha256": "66f4787a5d9307c01be2ad98645ad52a64b2b9222ccf9e7e7869b5de442e7b6f"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_03.mp4": {
+ "bytes": 724641,
+ "sha256": "7ae10ca9283898bd2fbb2ab3d9c92ff316cdbeb87bab7c257a50548c07868dee"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_04.mp4": {
+ "bytes": 537116,
+ "sha256": "29fa7c7adb182f4eb70a0430f4f8fab94aff1f38bb53993ecbc8306da70f5c43"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_05.mp4": {
+ "bytes": 660453,
+ "sha256": "b35b6b1ff969e205f069d6aadc44f4e2fc4bd88b27965e37189257477c8db7af"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_06.mp4": {
+ "bytes": 1202626,
+ "sha256": "d9c466a493dc729c8dc6cd6b6561e1b79387944ef5c63bcee76dd00a7d693c7c"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_07.mp4": {
+ "bytes": 867803,
+ "sha256": "616d8d06f1c1b8ba2eff4e053380654f32101577e6b7aa7faf1571d0c944330d"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_08.mp4": {
+ "bytes": 546246,
+ "sha256": "a2b419ee3a120167fc4bb80ef55fbdcd43473941a426b87ec73bd2a7d6a64e2e"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_09.mp4": {
+ "bytes": 1047881,
+ "sha256": "272b6d0928c906547f2097b1511ff69d392e9fb0d3d416b3cee6e2f5207bb8c6"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_145520_ep_10.mp4": {
+ "bytes": 595166,
+ "sha256": "f648c731ca83df94383ca685e46ee8743a3777a228583fb175a336ec10cc50f7"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_150916_ep_01.mp4": {
+ "bytes": 609565,
+ "sha256": "a5304877894bdcb63a0962aab8b6826cd890312cd29efcc3bf3e9d06d06aba0b"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_150916_ep_02.mp4": {
+ "bytes": 510615,
+ "sha256": "25b53121b63de068468ce207a85342c474681c280f4c8e01fb9a5bba0ce81635"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151136_ep_01.mp4": {
+ "bytes": 542312,
+ "sha256": "12e66e3a3449a04c59f106ddf4c74b17a7933dbc7f5ac9497ba008d53593363f"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151136_ep_02.mp4": {
+ "bytes": 573450,
+ "sha256": "c0162e11cdcd8f084a1fea3f14c3740e35f92617da3e8b1df894be89c4f2c143"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151136_ep_03.mp4": {
+ "bytes": 641864,
+ "sha256": "bcb452d831173a712d0d2c5e9616916cde90e16d61d79dfc55b42bc97c0aa114"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151136_ep_04.mp4": {
+ "bytes": 587340,
+ "sha256": "370ef7b4e1b199634cc13a8ae608e17b981b78d90b3da0796d1bfe834942aa6f"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151136_ep_05.mp4": {
+ "bytes": 1018545,
+ "sha256": "b03670946d6f30a32f7956668a84df1578db1bfa936f30b5da6d8c6b2e9f21c3"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151136_ep_06.mp4": {
+ "bytes": 519939,
+ "sha256": "ec36ce228a6546488879c4c879a76da9b25e5acdcdd0823ae90bc350720aca0d"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151136_ep_07.mp4": {
+ "bytes": 1089975,
+ "sha256": "44dff0cede4c6ca8451fa8e494f1d8f28aa1bef58ddd9df290424fdde167b723"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151136_ep_08.mp4": {
+ "bytes": 740302,
+ "sha256": "8ed725fbaae1e2005f6987559a35e7d6a33090fc133c56fb87da548ded0f7fd0"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_01.mp4": {
+ "bytes": 650846,
+ "sha256": "442c739223d5cf42bcf66d0749c82095329325814e7427cac71bdc307d199e88"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_02.mp4": {
+ "bytes": 565355,
+ "sha256": "3e5d775fb1706530bc4589aed4c12845381adbc517890522d130855a9a2a22d1"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_03.mp4": {
+ "bytes": 645966,
+ "sha256": "967f69489c089601211cb428c5834b5cfa849b4581df0ec56d34c48758bac720"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_04.mp4": {
+ "bytes": 1027366,
+ "sha256": "e5d0309e9db4650ad78395d72044ed865f773d299015b96a0253cde250e9bf13"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_05.mp4": {
+ "bytes": 630670,
+ "sha256": "513509b31a79d3d3b2e9216fc89bd5b22c0bf3a3a6037a99d6df0a157cf63916"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_06.mp4": {
+ "bytes": 1059006,
+ "sha256": "723a9b0fba4b8907fe4bfe5795a246324d99511c3994b17d77d6865b3d6940aa"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_07.mp4": {
+ "bytes": 600255,
+ "sha256": "f7407cb60f7f1ad4d70382ebdfead845e0f57b61d7ecf2d36ec1c74b86b32b75"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_08.mp4": {
+ "bytes": 1175210,
+ "sha256": "4cc7ab7f9c653c111ddc8b6db55c1bb18d98ad0608f0b5fe795f1b942c0dbaa2"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_09.mp4": {
+ "bytes": 914004,
+ "sha256": "07c9091f5d51a25d80a69f3fdec06a544778c101d26b687e1462316e15b3be94"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_151953_ep_10.mp4": {
+ "bytes": 1087000,
+ "sha256": "1d69f7f44c1fa9eef5b8e17bb1b9ea141484987a9436b7190a28b83a5f85e547"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_01.mp4": {
+ "bytes": 639503,
+ "sha256": "704d7e4a71b08f32ec02bf4a03f80565969b416e1f250565fbb5105231397a12"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_02.mp4": {
+ "bytes": 576161,
+ "sha256": "8ea47a6cb3bdf31b1a0640937f76557636354aaf6a9edf470107ca076d2b63b6"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_03.mp4": {
+ "bytes": 493714,
+ "sha256": "a06aac70414148584905cd953b7fd30b8b96c372378b6e0897a14513305dc9c3"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_04.mp4": {
+ "bytes": 793105,
+ "sha256": "be609672f71aff74ffedd1aee18e737ba1a11b266384e81d82a6619d6ff6a80e"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_05.mp4": {
+ "bytes": 974745,
+ "sha256": "7e7720f86f0f1b536fd2ef98976d55da497ec27e15775b6228151b2917259afc"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_06.mp4": {
+ "bytes": 618853,
+ "sha256": "73b29bbb0ccda05eccc8092f0bf3f29e046aaa3a5cfb9bbaad7c49a91dea953e"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_07.mp4": {
+ "bytes": 715899,
+ "sha256": "b9250fd67a283fb9bd79f52ae7df1e8b6d306ab787cf4cba5619513e3293500e"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_08.mp4": {
+ "bytes": 1025536,
+ "sha256": "a76212aeb6ce172a5f322450850f20f98ffb8f456640860eae4ca24e779a50d8"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_09.mp4": {
+ "bytes": 689717,
+ "sha256": "a61e8f6454c09f006b584eba1776c78e2ac4256dbf762283f9e5040d6014ff64"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153045_ep_10.mp4": {
+ "bytes": 568890,
+ "sha256": "d57aa44ada14f9bf76bf12529ea74ed12e998dfd552a1d25db46cbcc4eca4262"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_01.mp4": {
+ "bytes": 550619,
+ "sha256": "f73768f2d66b618172e5a0c1b0fcf7fdf6c1cfdab174926533b7ccb8d76e3087"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_02.mp4": {
+ "bytes": 1132770,
+ "sha256": "6f38283e3cee3e7807de57a3107ac8538b1a121c20475f6e9e7ee4ca2f94bc73"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_03.mp4": {
+ "bytes": 954560,
+ "sha256": "1bbb426de553859b09cf8a2c0f7c577236a6f512f2f1861a45f90bd7eca0e1ba"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_04.mp4": {
+ "bytes": 915490,
+ "sha256": "26a2961e6a45a74b155a1b2cb8648270da8fef16ce420c9f166941857af48de5"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_05.mp4": {
+ "bytes": 727017,
+ "sha256": "4d03a147da075a8b582b54b9b8fa872bc769107282c3bef499b104f31898e3f9"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_06.mp4": {
+ "bytes": 931635,
+ "sha256": "763538f22eebff276e602620850d956bd0d1393f56c3436ba2b57a12b5cd9e07"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_07.mp4": {
+ "bytes": 651558,
+ "sha256": "9726bdb2bc243556eadc1607a8276491d60ae2b22356c9f530792041046efa10"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_08.mp4": {
+ "bytes": 880756,
+ "sha256": "de59aa8be4565b07d667efaec174a625b076b59c1a21fe6df6250a9aed5aeb5e"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_09.mp4": {
+ "bytes": 566377,
+ "sha256": "341e5918e9b83edce313727c9a91d656026717ac1ae27eedc066592f9d793ace"
+ },
+ "so101_pick_place/robot/videos/stress_tb10/eval_20261027_153943_ep_10.mp4": {
+ "bytes": 575450,
+ "sha256": "c77759bbe4484c3e51d15a1bf0d912d057c4788729b2cbad5e408378fe072d5a"
+ },
+ "so101_pick_place/robot/videos/tb10_stress_20261027_4x.mp4": {
+ "bytes": 15990495,
+ "sha256": "bdaf925dcb48fb68d451bc84341ae20733981d282334cacdcd1c07ceb2261750"
+ },
+ "so101_pick_place/scene_calib/calib_v1.json": {
+ "bytes": 39147,
+ "sha256": "3b7a2124d1b56bd6049a682a4eb29e9f4cef62818f4a420665171bbe31e0410f"
+ },
+ "so101_pick_place/scene_calib/dyn_fit_d2q.json": {
+ "bytes": 888,
+ "sha256": "68a96d77b506bc75d368a4e6412f89b7f7f2c22585281a7b764acda7661f6918"
+ },
+ "so101_pick_place/scene_calib/parts_override_v2.json": {
+ "bytes": 18479,
+ "sha256": "3840ca99745839ff693dca975f9853720176ab61b3b7d751a42995e0e5366217"
+ },
+ "so101_pick_place/scene_calib/real_scene_v2.json": {
+ "bytes": 8654,
+ "sha256": "4bce0b8dd6f22b5499b556275bca0bf248d1e96b1cd3babf169b34a8cb539d82"
+ },
+ "so101_pick_place/scene_calib/so101_follower_lerobot_calib.json": {
+ "bytes": 915,
+ "sha256": "c2b8953fadcc1af32fa7a96c6b5e7a8031fff3100868c1afc2f95ee19437afc2"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/args.json": {
+ "bytes": 1454,
+ "sha256": "1ea8f2aff0f301c7bdb4532325c7cd1f739225258a6c1a5f383c6feb8e3b11d0"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/progress.jsonl": {
+ "bytes": 6330,
+ "sha256": "d76fca6303c297c1ac3c9937181ae5f0c69c0e24637436ff7cd0b857dbeed958"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/r0/meta.json": {
+ "bytes": 2872,
+ "sha256": "5df1980c2dc9947f8789eaaf32f80eb44c12ddbd15d8d719eac887f53ee98d9f"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/r0/train_summary.json": {
+ "bytes": 144,
+ "sha256": "5b00c8aa8f062784ffeb86f4a1ab002bffbb02427cc2c93546f50ea0bb83c826"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/r1/meta.json": {
+ "bytes": 3013,
+ "sha256": "b97862146459e2a8252ef73baf18dfe6a377aa28c703c957963d5c0989bdfaf8"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/r1/train_summary.json": {
+ "bytes": 144,
+ "sha256": "60bd6b67ad84d24732a60b58f9741ac7bf4de2d85e30f6f6f4d663372a043f93"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/r2/last.pt": {
+ "bytes": 24544351,
+ "sha256": "3fe3fb5a05170e2911bbf4e59f960dde73c39e27f7d5aadeeafca6478e170595"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/r2/meta.json": {
+ "bytes": 3087,
+ "sha256": "1659610092c5c7da8e485e8abcf4e014c0d761a38de793e24b040dd6c5f3f376"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/r2/train_summary.json": {
+ "bytes": 142,
+ "sha256": "2b9bb2a67bb438abd2b6f0352d1fd2ca043626f9a6312f191512642b9190a6cb"
+ },
+ "so101_pick_place/student/s0_v2_start_s2/real_pin.json": {
+ "bytes": 366,
+ "sha256": "0e7cf9735966a8534be939f7b22310e704c7f570faeb3d4da6db55394230a426"
+ },
+ "so101_pick_place/student/s1_v2_online_s18/args.json": {
+ "bytes": 1332,
+ "sha256": "3583b2733796971d7c9fdcca1c7d9aa0b10c305dd639a3b32ed6a9aed7c06c24"
+ },
+ "so101_pick_place/student/s1_v2_online_s18/curve.csv": {
+ "bytes": 11658,
+ "sha256": "98b9d77f11f4202877ef5a274ad68debc95ad6a99bfa338cc8fbab7535e98ca5"
+ },
+ "so101_pick_place/student/s1_v2_online_s18/it_03000.pt": {
+ "bytes": 24555727,
+ "sha256": "8fe355c7afbc0ff1dd93af70dd0ab76ff68102f5ce538f4df2a1d01d7b060264"
+ },
+ "so101_pick_place/student/s1_v2_online_s18/meta.json": {
+ "bytes": 3307,
+ "sha256": "01e9791312d133115752a15752c466e33492812704dc91e5be553b62631353a1"
+ },
+ "so101_pick_place/student/s1_v2_online_s18/progress.jsonl": {
+ "bytes": 5363,
+ "sha256": "70610f6e53da467d83713da774557780fa648493f15f2468909a65f042e59f55"
+ },
+ "so101_pick_place/student/s2_v2_online2_s28/args.json": {
+ "bytes": 1341,
+ "sha256": "6dce4b1fc4203f2986b050e1736618126795e30f18680b3bb10c0326b38b1996"
+ },
+ "so101_pick_place/student/s2_v2_online2_s28/curve.csv": {
+ "bytes": 11695,
+ "sha256": "e77165dab958fa88702abef2c8bc43b6990faf398696ea6ecb1dbeedd701d058"
+ },
+ "so101_pick_place/student/s2_v2_online2_s28/it_03000.pt": {
+ "bytes": 24555727,
+ "sha256": "68d08d0ba9144b16d436a10bcc4cef4eb287f3fc40aebc55dbfbd3780fc8f7a0"
+ },
+ "so101_pick_place/student/s2_v2_online2_s28/meta.json": {
+ "bytes": 3324,
+ "sha256": "d8715bc039a79dc3345e5333f4284fc7df0e91de78a0e9da7616a50d009417be"
+ },
+ "so101_pick_place/student/s2_v2_online2_s28/progress.jsonl": {
+ "bytes": 5083,
+ "sha256": "83bbe61ce78c561dd9f7fb577150073979075adda22c099bfd92b1c03e9e86ca"
+ },
+ "so101_pick_place/student/s3_v4_relabel_s63/args.json": {
+ "bytes": 1371,
+ "sha256": "c9d5c63eac6c51cc43e151fe8405c934fe8e9052b2d1652415482bdf2a5b8bb1"
+ },
+ "so101_pick_place/student/s3_v4_relabel_s63/curve.csv": {
+ "bytes": 17715,
+ "sha256": "5f95797f80f6bba93d63ab198b7e60f769c3716166aaf795a15b438512631613"
+ },
+ "so101_pick_place/student/s3_v4_relabel_s63/it_02000.pt": {
+ "bytes": 24555727,
+ "sha256": "ceebbd2fc17aa3df8a14bebaf6dd9babd4ed3acf84536b470db420b1c638e06c"
+ },
+ "so101_pick_place/student/s3_v4_relabel_s63/meta.json": {
+ "bytes": 4361,
+ "sha256": "d97098e56a96058919e369ea5eedd15c247c7deb7b5aa1be81c3056a5d801002"
+ },
+ "so101_pick_place/student/s3_v4_relabel_s63/progress.jsonl": {
+ "bytes": 5205,
+ "sha256": "ca51473d9ccb659c33926ef892ca372e2a2bc94ab601747662415f953be71342"
+ },
+ "so101_pick_place/student/s4_v8_roll_s801/args.json": {
+ "bytes": 1472,
+ "sha256": "5b30a730f86ca32082cc232162767a3f885a813cc67798f06981b83fa1e0934e"
+ },
+ "so101_pick_place/student/s4_v8_roll_s801/curve.csv": {
+ "bytes": 12949,
+ "sha256": "296f54ac058b5285673278f949814db76e0b62de9709eae23109c8a9334608b7"
+ },
+ "so101_pick_place/student/s4_v8_roll_s801/it_02000.pt": {
+ "bytes": 24555727,
+ "sha256": "d9a35bfc23abde45472e05b1be3ed0de90108d17c3484e31511a669be5ab7a1b"
+ },
+ "so101_pick_place/student/s4_v8_roll_s801/meta.json": {
+ "bytes": 4797,
+ "sha256": "140a23de5302829a69cbf7e88aa1e814966e462897db934689621ed99cc77987"
+ },
+ "so101_pick_place/student/s4_v8_roll_s801/progress.jsonl": {
+ "bytes": 4026,
+ "sha256": "ed25d0cae4a8e3656b9b724862b4df47178797c53866822392cd299c6d4d7220"
+ },
+ "so101_pick_place/student/s5_v12_tb10_s1210/args.json": {
+ "bytes": 1594,
+ "sha256": "723cac29a47c7c195cab28d9d48119d50c0e88c27aabe5ea7022f744091e9797"
+ },
+ "so101_pick_place/student/s5_v12_tb10_s1210/curve.csv": {
+ "bytes": 12068,
+ "sha256": "1aad3b525f6ded507e420dd25d5e52b8c39db6893c142effd016be145b1281af"
+ },
+ "so101_pick_place/student/s5_v12_tb10_s1210/it_01000.pt": {
+ "bytes": 24555983,
+ "sha256": "6458a4f791d1052148bb8f7621413259342a7018757668fde244cfc098f99f5c"
+ },
+ "so101_pick_place/student/s5_v12_tb10_s1210/meta.json": {
+ "bytes": 5364,
+ "sha256": "c8a170dc83687d09fb7630aeaea779f06623fc7131fb94766d1a3a639fa48896"
+ },
+ "so101_pick_place/student/s5_v12_tb10_s1210/progress.jsonl": {
+ "bytes": 4095,
+ "sha256": "2aaf9526d5e190bf7d7b28a807768b0d046a173d6d2e58b5afb7a7a259bf56dd"
+ },
+ "so101_pick_place/teacher/t0_nC1_s62_b/curriculum.json": {
+ "bytes": 986,
+ "sha256": "f74d2a360f57b1f10e256aee36239018fd023844eb155c42e670388ab06aedac"
+ },
+ "so101_pick_place/teacher/t0_nC1_s62_b/done.json": {
+ "bytes": 1066,
+ "sha256": "77316f4b263968ad6b272d308d3133d1d4a74f4c96ba4b98c32b92297c02af36"
+ },
+ "so101_pick_place/teacher/t0_nC1_s62_b/env_cfg.json": {
+ "bytes": 1013,
+ "sha256": "753173eccf6feced3e1fb50bb7c27785000f70d6e540c0b8d55240f44eb9a71b"
+ },
+ "so101_pick_place/teacher/t0_nC1_s62_b/env_resolved.json": {
+ "bytes": 4806,
+ "sha256": "632f923ac3f1f650fb58160a6d3a39b7571087d877d58bc792dbdd586a8c87d0"
+ },
+ "so101_pick_place/teacher/t0_nC1_s62_b/learning_curve.csv": {
+ "bytes": 72854,
+ "sha256": "168cb13802ca5278f68e9c62a86c7914e03973f48cf41ed2eb788e33aac85c05"
+ },
+ "so101_pick_place/teacher/t0_nC1_s62_b/manifest.json": {
+ "bytes": 9450,
+ "sha256": "95f17c11069bfb78a3342600a070dc0615ace7f78b8af4bcfb0f42baa64d8ea8"
+ },
+ "so101_pick_place/teacher/t0_nC1_s62_b/model_00171.pt": {
+ "bytes": 5101045,
+ "sha256": "8069d5b39162931ee5ae3db874afed8899526ad92313746f207907766c973cc9"
+ },
+ "so101_pick_place/teacher/t0_nC1_s62_b/train_cfg.json": {
+ "bytes": 831,
+ "sha256": "5024a4665b61bdd7e49cdf9a39aa889d0dba0ea456512695432f3c32d84665b6"
+ },
+ "so101_pick_place/teacher/t0_nC1_s62_b/val_history.json": {
+ "bytes": 13390,
+ "sha256": "78dc86b34b2c43489d88947275c768bf33d964fce212e54b1d38fe7d2e81d269"
+ },
+ "so101_pick_place/teacher/t1_expert_data/e0_n1.npz": {
+ "bytes": 272580029,
+ "sha256": "14e19d1f849bd44a8adb22f83366e0eb40ca3acb62e33dc3f313c0c51a3cc708"
+ },
+ "so101_pick_place/teacher/t1_expert_data/e1_n2.npz": {
+ "bytes": 283795005,
+ "sha256": "55335841256cc06089d32e76d5d5bfd3e446f5a0e5d99e0a4e538ab880336dc9"
+ },
+ "so101_pick_place/teacher/t1_expert_data/e2_n15.npz": {
+ "bytes": 276651132,
+ "sha256": "ed5cdcc4bdf7d85458d741d754652305ce5b5851cc7b92967fe3d3474e1c939e"
+ },
+ "so101_pick_place/teacher/t2_bc_all/args.json": {
+ "bytes": 584,
+ "sha256": "aeaed90f1fc32c093784ab5ecedfa96fca2c0981d523a7f1dcd13bdbf04275f3"
+ },
+ "so101_pick_place/teacher/t2_bc_all/bc.pt": {
+ "bytes": 5670373,
+ "sha256": "95df5ff78c2632b38cb4bbe258c8c5283fa4abc511f4ff83caa8b25b2b7eb1cd"
+ },
+ "so101_pick_place/teacher/t2_bc_all/bc_curve.csv": {
+ "bytes": 3235,
+ "sha256": "30fc9506b129c28ff86c97b46acee0c449f104ad79d9883092b3c8d0c59390ca"
+ },
+ "so101_pick_place/teacher/t2_bc_all/codec.npz": {
+ "bytes": 788,
+ "sha256": "80d55b165de435c3b9f7df5203648db2d7cfebc0ef44613b96cdbccb7bf4e199"
+ },
+ "so101_pick_place/teacher/t3_jt_b140/args.json": {
+ "bytes": 877,
+ "sha256": "519a50c9e025ab27a529a5c873d0f9a0c5310f0c2563350fa6f307670e6a2769"
+ },
+ "so101_pick_place/teacher/t3_jt_b140/cmdline.txt": {
+ "bytes": 743,
+ "sha256": "df494967e3da3e8fdb8fb073302c0605e0740e5d15c5347cd8c6268d20abb6f3"
+ },
+ "so101_pick_place/teacher/t3_jt_b140/learning_curve.csv": {
+ "bytes": 96453,
+ "sha256": "f95cb2c78a3931f7d35e08628c4399ed30853502f5472016e64c93ed8f618cab"
+ },
+ "so101_pick_place/teacher/t3_jt_b140/model_00140.pt": {
+ "bytes": 17078389,
+ "sha256": "41693858e88b2607e2ae6cf1ab575e03f9f1682e55fa9599a298cd48589df992"
+ },
+ "so101_pick_place/teacher/t4_jt_h110/args.json": {
+ "bytes": 885,
+ "sha256": "a183efca0ad6f2207d45f11d4b80d171853cc783653868e80864ebdcac4bed1f"
+ },
+ "so101_pick_place/teacher/t4_jt_h110/cmdline.txt": {
+ "bytes": 751,
+ "sha256": "b2b26a9e3d8fb451dbbbe9471eb394f032ca5ab904ac477b0783143dd8a17bd8"
+ },
+ "so101_pick_place/teacher/t4_jt_h110/learning_curve.csv": {
+ "bytes": 43668,
+ "sha256": "76448b6377393fa34c3c0459a62032d48717c6aa6096dbe6a9b1e48525c34d3e"
+ },
+ "so101_pick_place/teacher/t4_jt_h110/model_00110.pt": {
+ "bytes": 17078453,
+ "sha256": "0c1b61428f829459cce0aa2a0dfd9bd69c08f2625f055b768875f2760c7a4b84"
+ },
+ "so101_pick_place/teacher/t5_tppo_roll_v8_s21/args.json": {
+ "bytes": 890,
+ "sha256": "d39784de3557c18ad37ac474fdf34653384eb2058cf58b3a0d50775e18753dbb"
+ },
+ "so101_pick_place/teacher/t5_tppo_roll_v8_s21/dev_evals.jsonl": {
+ "bytes": 7997,
+ "sha256": "feb0f009a4551f077c9ce217c0199f0ccaa74f06ae98353e97ca8a7d46585d85"
+ },
+ "so101_pick_place/teacher/t5_tppo_roll_v8_s21/learning_curve.csv": {
+ "bytes": 72248,
+ "sha256": "bf1fa2995747a96f028fdecbef9c87cc19367dbeb7fa2b63c65e470096e54baa"
+ },
+ "so101_pick_place/teacher/t5_tppo_roll_v8_s21/model_00200.pt": {
+ "bytes": 17078517,
+ "sha256": "c4ea842c94226300b48d52d5c7a49c995d31bc452c10b37a1e947ca787d55420"
+ },
+ "so101_pick_place/teacher/t6_tppo_v12_fr10_s122/args.json": {
+ "bytes": 997,
+ "sha256": "8be75f9e369e6ef726ef3c61ee773a11abe429ce309e727c3dc3bdac49f2fb64"
+ },
+ "so101_pick_place/teacher/t6_tppo_v12_fr10_s122/dev_evals.jsonl": {
+ "bytes": 15955,
+ "sha256": "98182bb5ba9255439b1e9e40872ea3b63132ad0c649acc13526094f6eaf6bf2e"
+ },
+ "so101_pick_place/teacher/t6_tppo_v12_fr10_s122/learning_curve.csv": {
+ "bytes": 72032,
+ "sha256": "08ab2cbde1210c8aa5db0d3b4f7b0d720c5c5ddd47f8354306495e34b7aaeab3"
+ },
+ "so101_pick_place/teacher/t6_tppo_v12_fr10_s122/model_00200.pt": {
+ "bytes": 17078581,
+ "sha256": "069cd8961217a29684a08683220a31a9af14bf5e97b7faf9aba9f4c905d06692"
+ }
+ }
+}
diff --git a/so101_pick_place/code/so101_pick_place/results/robot_results.md b/so101_pick_place/code/so101_pick_place/results/robot_results.md
new file mode 100644
index 0000000000000000000000000000000000000000..98ea806c2b595ce08dc4a35474b96713f9b62178
--- /dev/null
+++ b/so101_pick_place/code/so101_pick_place/results/robot_results.md
@@ -0,0 +1,154 @@
+# SO101 robot results (from the raw logs)
+
+Source: the session logs of the Hub folder `robot/logs//` (`session.json`: typed outcome; `ep_NN/episode_live.{json,npz}`), counted by `scripts/so101_pick_place/robot/build_results.py`. Place = the person at the robot typed `p` (cube on the plate). Cube / plate positions and directions: `results/robot/stress_episodes.json` (an image + kinematics estimate; the script that wrote it was not found and is not released).
+
+## Students
+
+| Label | Student | Bundle on the robot computer | Checkpoint on the Hub | student.pt sha256 (first 16) |
+|---|---|---|---|---|
+| tb10 | lower table 10 mm, 1,000 steps (released) | so101_hw_v13_tb10 | `student/s5_v12_tb10_s1210/it_01000.pt` | 6458a4f791d10521 |
+| D | previous robot student (released) | so101_hw_v8_roll801 | `student/s4_v8_roll_s801/it_02000.pt` | d9a35bfc23abde45 |
+| visR500 | visual fix, seed 1231, 500 steps | so101_hw_v13_visR500 | not released | 516eb659f6720066 |
+| visR_s1304_it750 | visual fix, seed 1304, 750 steps | so101_hw_v13q_visR_s1304_it750 | not released | 7485a7088b3be705 |
+| visRtb05_s1301_it500 | visual fix + 5 mm lower table, 500 steps | so101_hw_v13q_visRtb05_s1301_it500 | not released | 3886e4b90e18d24a |
+| tb05 | lower table 5 mm, 1,500 steps | so101_hw_v13_tb05 | not released | 2dea35124ca7a701 |
+| visR0_250 | real-look gripper, no randomisation, 250 steps | so101_hw_v13_visR0_250 | not released | 85a1983beb384021 |
+
+The logs do not record a checkpoint hash: the student of each session is known from the bundle folder named in the logs (`setup.kin_points`) and the study's local copy of that bundle; the files on the robot computer were not compared with `MANIFEST.txt`.
+
+## Totals
+
+| Student | Test | Places | Rate | 95 % (Wilson) |
+|---|---|---|---|---|
+| tb10 | stress 10-27 (6 sessions) | 36/50 | 72 % | 58-83 % |
+| tb10 | stress, R->L | 19/23 | 83 % | 63-93 % |
+| tb10 | stress, L->R | 17/27 | 63 % | 44-78 % |
+| tb10 | all 10-27 (screening + stress) | 40/54 | 74 % | 61-84 % |
+| D | all 10-24..10-27 (7 sessions) | 19/28 | 68 % | 49-82 % |
+| D | day 20261024 | 6/8 | 75 % | 41-93 % |
+| D | day 20261025 | 6/8 | 75 % | 41-93 % |
+| D | day 20261026 | 2/4 | 50 % | 15-85 % |
+| D | day 20261027 | 5/8 | 62 % | 31-86 % |
+| D | screening 10-27 | 5/8 | 62 % | 31-86 % |
+| tb10 | screening 10-27 | 4/4 | 100 % | 51-100 % |
+| visR500 | screening 10-27 | 2/4 | 50 % | 15-85 % |
+| visR_s1304_it750 | screening 10-27 | 3/4 | 75 % | 30-95 % |
+| visRtb05_s1301_it500 | screening 10-27 | 2/4 | 50 % | 15-85 % |
+| tb05 | screening 10-27 | 3/4 | 75 % | 30-95 % |
+| visR0_250 | screening 10-27 | 3/4 | 75 % | 30-95 % |
+| all 7 | screening 10-27 | 22/32 | 69 % | 51-82 % |
+
+## Independent recount of the stress test
+
+- session.json place flags, 6 sessions: **36/50** (report claim 36/50; agrees: True).
+- Per session: 145520 8/10, 150916 2/2, 151136 5/8, 151953 7/10, 153045 8/10, 153943 6/10
+- Typed code letters agree with the flags: True; ep_NN/episode_live.json outcome agrees: True; stress_episodes.json placed/typed agree: True; same 50 episode ids: True.
+- Direction label (stress_episodes.json `dir`) = sign of the arm-frame lateral offset plate y - cube y (y = r sin(deg)): 50/50 agree; |offset| < 15 mm (near ambiguous): eval_20261027_145520/ep_05, eval_20261027_151953/ep_02.
+- Excluded: eval_20261027_150916/ep_03 (aborted before the student loop (holding at HOME); not in session.json episodes[]; no policy step was run).
+
+## Episodes
+
+| Session | Ep | Group | Student | Typed | Place | Dir | Cube r mm / deg | End reason | Duration s |
+|---|---|---|---|---|---|---|---|---|---|
+| eval_20261027_145520 | ep_01 | stress_tb10 | tb10 | GLP NICE | 1 | R->L | 184 / -18 | user stop (key b' ') | 17.6 |
+| eval_20261027_145520 | ep_02 | stress_tb10 | tb10 | GLP NICE | 1 | R->L | 231 / -19 | user stop (key b' ') | 17.1 |
+| eval_20261027_145520 | ep_03 | stress_tb10 | tb10 | GLP NIE | 1 | R->L | 226 / -34 | user stop (key b' ') | 21.3 |
+| eval_20261027_145520 | ep_04 | stress_tb10 | tb10 | GLP NICE | 1 | R->L | 258 / +8 | user stop (key b' ') | 17.2 |
+| eval_20261027_145520 | ep_05 | stress_tb10 | tb10 | - FAILED GRASP, MIGHT BE OUTSIDE RANGE | 0 | L->R | 278 / +15 | user stop (key b' ') | 28.9 |
+| eval_20261027_145520 | ep_06 | stress_tb10 | tb10 | - FAILED GRASP | 0 | L->R | 260 / +28 | time limit | 40.0 |
+| eval_20261027_145520 | ep_07 | stress_tb10 | tb10 | GLP NICE | 1 | R->L | 248 / -45 | user stop (key b' ') | 25.4 |
+| eval_20261027_145520 | ep_08 | stress_tb10 | tb10 | GLP BIT OFF | 1 | R->L | 258 / +7 | user stop (key b' ') | 17.0 |
+| eval_20261027_145520 | ep_09 | stress_tb10 | tb10 | GLP BIT OFF | 1 | L->R | 228 / +37 | user stop (key b' ') | 35.9 |
+| eval_20261027_145520 | ep_10 | stress_tb10 | tb10 | GLP BIT OFF | 1 | R->L | 243 / -17 | user stop (key b' ') | 17.8 |
+| eval_20261027_150916 | ep_01 | stress_tb10 | tb10 | GLP NICE | 1 | R->L | 212 / -19 | user stop (key b' ') | 18.0 |
+| eval_20261027_150916 | ep_02 | stress_tb10 | tb10 | GLP NICE | 1 | R->L | 208 / -9 | user stop (key b' ') | 14.5 |
+| eval_20261027_151136 | ep_01 | stress_tb10 | tb10 | GLP BIT OFF | 1 | R->L | 208 / +8 | user stop (key b' ') | 15.9 |
+| eval_20261027_151136 | ep_02 | stress_tb10 | tb10 | GLP BIT OFF | 1 | R->L | 258 / +9 | user stop (key b' ') | 17.6 |
+| eval_20261027_151136 | ep_03 | stress_tb10 | tb10 | GLP | 1 | R->L | 215 / -24 | user stop (key b' ') | 18.4 |
+| eval_20261027_151136 | ep_04 | stress_tb10 | tb10 | GLP | 1 | R->L | 207 / -23 | user stop (key b' ') | 15.7 |
+| eval_20261027_151136 | ep_05 | stress_tb10 | tb10 | - FAILED GRASP | 0 | R->L | 214 / -12 | time limit | 40.0 |
+| eval_20261027_151136 | ep_06 | stress_tb10 | tb10 | GLP | 1 | R->L | 208 / -10 | user stop (key b' ') | 15.2 |
+| eval_20261027_151136 | ep_07 | stress_tb10 | tb10 | - FAILED GRASP | 0 | R->L | 189 / -32 | time limit | 40.0 |
+| eval_20261027_151136 | ep_08 | stress_tb10 | tb10 | - FAILED GRASP | 0 | R->L | 218 / -33 | user stop (key b' ') | 39.0 |
+| eval_20261027_151953 | ep_01 | stress_tb10 | tb10 | GL PLACE IS SHORT | 0 | L->R | 183 / +26 | user stop (key b' ') | 19.3 |
+| eval_20261027_151953 | ep_02 | stress_tb10 | tb10 | GLP BIT OFF | 1 | L->R | 250 / -11 | user stop (key b' ') | 17.3 |
+| eval_20261027_151953 | ep_03 | stress_tb10 | tb10 | GLP OFF | 1 | L->R | 207 / +12 | user stop (key b' ') | 18.2 |
+| eval_20261027_151953 | ep_04 | stress_tb10 | tb10 | GL | 0 | R->L | 185 / -45 | time limit | 40.0 |
+| eval_20261027_151953 | ep_05 | stress_tb10 | tb10 | GLP | 1 | L->R | 233 / +20 | user stop (key b' ') | 19.7 |
+| eval_20261027_151953 | ep_06 | stress_tb10 | tb10 | GL FAILED GRASP IN THE BEGINING AND TIME OUT DURING CARRY | 0 | L->R | 206 / +27 | time limit | 40.0 |
+| eval_20261027_151953 | ep_07 | stress_tb10 | tb10 | GLP | 1 | L->R | 235 / +25 | user stop (key b' ') | 18.0 |
+| eval_20261027_151953 | ep_08 | stress_tb10 | tb10 | GLP NICE | 1 | L->R | 265 / +11 | time limit | 40.0 |
+| eval_20261027_151953 | ep_09 | stress_tb10 | tb10 | GLP OFF | 1 | L->R | 215 / +34 | user stop (key b' ') | 29.9 |
+| eval_20261027_151953 | ep_10 | stress_tb10 | tb10 | GLP NICE | 1 | R->L | 289 / -27 | user stop (key b' ') | 33.9 |
+| eval_20261027_153045 | ep_01 | stress_tb10 | tb10 | GLP BIT OFF | 1 | L->R | 219 / +17 | user stop (key b' ') | 18.6 |
+| eval_20261027_153045 | ep_02 | stress_tb10 | tb10 | GLP NICE | 1 | L->R | 194 / +9 | user stop (key b' ') | 17.0 |
+| eval_20261027_153045 | ep_03 | stress_tb10 | tb10 | GLP BIT OFF | 1 | L->R | 202 / -8 | user stop (key b' ') | 14.4 |
+| eval_20261027_153045 | ep_04 | stress_tb10 | tb10 | GL SHORT | 0 | L->R | 181 / +33 | user stop (key b' ') | 24.0 |
+| eval_20261027_153045 | ep_05 | stress_tb10 | tb10 | GL NO DROP | 0 | L->R | 184 / +22 | time limit | 40.0 |
+| eval_20261027_153045 | ep_06 | stress_tb10 | tb10 | GLP | 1 | R->L | 205 / -47 | user stop (key b' ') | 18.7 |
+| eval_20261027_153045 | ep_07 | stress_tb10 | tb10 | GLP | 1 | L->R | 256 / +4 | user stop (key b' ') | 21.4 |
+| eval_20261027_153045 | ep_08 | stress_tb10 | tb10 | GLP NICE | 1 | L->R | 268 / -10 | user stop (key b' ') | 34.4 |
+| eval_20261027_153045 | ep_09 | stress_tb10 | tb10 | GLP BIT OFF | 1 | L->R | 240 / +26 | user stop (key b' ') | 20.9 |
+| eval_20261027_153045 | ep_10 | stress_tb10 | tb10 | GLP BIT OFF | 1 | L->R | 248 / -9 | user stop (key b' ') | 17.8 |
+| eval_20261027_153943 | ep_01 | stress_tb10 | tb10 | GLP | 1 | L->R | 213 / +20 | user stop (key b' ') | 17.2 |
+| eval_20261027_153943 | ep_02 | stress_tb10 | tb10 | GL SHORT | 0 | L->R | 249 / -1 | time limit | 40.0 |
+| eval_20261027_153943 | ep_03 | stress_tb10 | tb10 | GL STOP | 0 | L->R | 191 / +21 | time limit | 40.0 |
+| eval_20261027_153943 | ep_04 | stress_tb10 | tb10 | GL NO DROP | 0 | L->R | 218 / +40 | time limit | 40.0 |
+| eval_20261027_153943 | ep_05 | stress_tb10 | tb10 | GLP BIT OFF | 1 | L->R | 221 / +14 | user stop (key b' ') | 22.1 |
+| eval_20261027_153943 | ep_06 | stress_tb10 | tb10 | GLP OFF | 1 | R->L | 237 / -35 | user stop (key b' ') | 27.4 |
+| eval_20261027_153943 | ep_07 | stress_tb10 | tb10 | GLP BIT OFF | 1 | L->R | 212 / +16 | user stop (key b' ') | 19.2 |
+| eval_20261027_153943 | ep_08 | stress_tb10 | tb10 | GL NO DROP | 0 | L->R | 177 / +22 | time limit | 40.0 |
+| eval_20261027_153943 | ep_09 | stress_tb10 | tb10 | GLP | 1 | R->L | 201 / -21 | user stop (key b' ') | 16.6 |
+| eval_20261027_153943 | ep_10 | stress_tb10 | tb10 | GLP BIT OFF | 1 | R->L | 228 / -12 | user stop (key b' ') | 17.3 |
+| eval_20261027_133039 | ep_01 | screening_20261027 | D | gl place off mat | 0 | | | time limit | 40.0 |
+| eval_20261027_133039 | ep_02 | screening_20261027 | D | GLP PLACE OFF MAT | 1 | | | user stop (key b' ') | 30.3 |
+| eval_20261027_133039 | ep_03 | screening_20261027 | D | GL PLACE SHORT | 0 | | | user stop (key b' ') | 24.4 |
+| eval_20261027_133039 | ep_04 | screening_20261027 | D | GLP NICE | 1 | | | user stop (key b' ') | 26.6 |
+| eval_20261027_133521 | ep_01 | screening_20261027 | visR500 | GLP NICE | 1 | | | user stop (key b' ') | 23.2 |
+| eval_20261027_133521 | ep_02 | screening_20261027 | visR500 | GL FAILED DROP THE CUBE ABOVE MAT | 0 | | | time limit | 40.0 |
+| eval_20261027_133521 | ep_03 | screening_20261027 | visR500 | GL PLACE BUT OFF FROM MAT | 0 | | | user stop (key b' ') | 34.4 |
+| eval_20261027_133521 | ep_04 | screening_20261027 | visR500 | GLP NICE | 1 | | | user stop (key b' ') | 24.3 |
+| eval_20261027_133953 | ep_01 | screening_20261027 | visR_s1304_it750 | GLP NICE | 1 | | | user stop (key b' ') | 33.0 |
+| eval_20261027_133953 | ep_02 | screening_20261027 | visR_s1304_it750 | GLP BIT OFF | 1 | | | user stop (key b' ') | 31.7 |
+| eval_20261027_133953 | ep_03 | screening_20261027 | visR_s1304_it750 | GL PLACE IS OFF FROM MAT | 0 | | | user stop (key b' ') | 28.7 |
+| eval_20261027_133953 | ep_04 | screening_20261027 | visR_s1304_it750 | GLP NICE | 1 | | | user stop (key b' ') | 25.1 |
+| eval_20261027_134411 | ep_01 | screening_20261027 | visRtb05_s1301_it500 | GLP BIT OFF | 1 | | | user stop (key b' ') | 15.7 |
+| eval_20261027_134411 | ep_02 | screening_20261027 | visRtb05_s1301_it500 | GL STOP | 0 | | | time limit | 40.0 |
+| eval_20261027_134411 | ep_03 | screening_20261027 | visRtb05_s1301_it500 | GLP BIT OFF BUT GOOD | 1 | | | user stop (key b' ') | 22.1 |
+| eval_20261027_134411 | ep_04 | screening_20261027 | visRtb05_s1301_it500 | GL PLACE OFF | 0 | | | user stop (key b' ') | 39.5 |
+| eval_20261027_134903 | ep_01 | screening_20261027 | tb05 | glp bit off | 1 | | | user stop (key b' ') | 20.3 |
+| eval_20261027_134903 | ep_02 | screening_20261027 | tb05 | GLP NICE | 1 | | | user stop (key b' ') | 21.1 |
+| eval_20261027_134903 | ep_03 | screening_20261027 | tb05 | GL SHORT | 0 | | | user stop (key b' ') | 30.4 |
+| eval_20261027_134903 | ep_04 | screening_20261027 | tb05 | GLP BIT OFF | 1 | | | user stop (key b' ') | 31.1 |
+| eval_20261027_135259 | ep_01 | screening_20261027 | D | - FAILED GRASP | 0 | | | user stop (key b' ') | 26.6 |
+| eval_20261027_135259 | ep_02 | screening_20261027 | D | GLP BIT OFF | 1 | | | user stop (key b' ') | 24.9 |
+| eval_20261027_135259 | ep_03 | screening_20261027 | D | GLP NICE | 1 | | | user stop (key b' ') | 26.4 |
+| eval_20261027_135259 | ep_04 | screening_20261027 | D | GLP NICE | 1 | | | user stop (key b' ') | 28.5 |
+| eval_20261027_135657 | ep_01 | screening_20261027 | tb10 | GLP NICE | 1 | | | user stop (key b' ') | 15.4 |
+| eval_20261027_135657 | ep_02 | screening_20261027 | tb10 | GLP BIT OFF BUT GOOD | 1 | | | user stop (key b' ') | 17.6 |
+| eval_20261027_135657 | ep_03 | screening_20261027 | tb10 | GLP NO STOP BUT OFF | 1 | | | user stop (key b' ') | 19.5 |
+| eval_20261027_135657 | ep_04 | screening_20261027 | tb10 | GLP NICE | 1 | | | user stop (key b' ') | 24.9 |
+| eval_20261027_140036 | ep_01 | screening_20261027 | visR0_250 | GLP OFF CENTER | 1 | | | user stop (key b' ') | 24.1 |
+| eval_20261027_140036 | ep_02 | screening_20261027 | visR0_250 | - FAILED GRASP | 0 | | | user stop (key b' ') | 28.3 |
+| eval_20261027_140036 | ep_03 | screening_20261027 | visR0_250 | GLP NICE | 1 | | | user stop (key b' ') | 21.6 |
+| eval_20261027_140036 | ep_04 | screening_20261027 | visR0_250 | GLP OFF FROM CENTER | 1 | | | user stop (key b' ') | 39.8 |
+| eval_20261024_202249 | ep_01 | D_20261024_26 | D | GLP NICE | 1 | | | user stop (key b' ') | 23.1 |
+| eval_20261024_202249 | ep_02 | D_20261024_26 | D | GLP NICE | 1 | | | user stop (key b' ') | 27.9 |
+| eval_20261024_202249 | ep_03 | D_20261024_26 | D | GLP BUT BIT OFF FROM CENTER OF MAT | 1 | | | user stop (key b' ') | 36.4 |
+| eval_20261024_202249 | ep_04 | D_20261024_26 | D | GL SOMEHOW STUCK DURING TRANSPORTING TO MAT | 0 | | | time limit | 40.0 |
+| eval_20261024_205852 | ep_01 | D_20261024_26 | D | GLP NICE | 1 | | | user stop (key b' ') | 23.4 |
+| eval_20261024_205852 | ep_02 | D_20261024_26 | D | GLP BUT PLACE IN THE WRONG SPOT | 1 | | | user stop (key b' ') | 34.3 |
+| eval_20261024_205852 | ep_03 | D_20261024_26 | D | GLP NICE | 1 | | | user stop (key b' ') | 25.3 |
+| eval_20261024_205852 | ep_04 | D_20261024_26 | D | - FAILED GRASP | 0 | | | time limit | 40.0 |
+| eval_20261025_192402 | ep_01 | D_20261024_26 | D | GLP NICE | 1 | | | user stop (key b' ') | 26.1 |
+| eval_20261025_192402 | ep_02 | D_20261024_26 | D | GLP NICE | 1 | | | user stop (key b' ') | 27.4 |
+| eval_20261025_192402 | ep_03 | D_20261024_26 | D | GLP PASS | 1 | | | user stop (key b' ') | 35.7 |
+| eval_20261025_192402 | ep_04 | D_20261024_26 | D | GLP NICE | 1 | | | user stop (key b' ') | 26.8 |
+| eval_20261025_194447 | ep_01 | D_20261024_26 | D | GL STOP | 0 | | | user stop (key b' ') | 25.8 |
+| eval_20261025_194447 | ep_02 | D_20261024_26 | D | GL STOP | 0 | | | user stop (key b' ') | 22.4 |
+| eval_20261025_194447 | ep_03 | D_20261024_26 | D | GLP NICE | 1 | | | user stop (key b' ') | 26.3 |
+| eval_20261025_194447 | ep_04 | D_20261024_26 | D | GLP SLIGHTLY OFF | 1 | | | user stop (key b' ') | 26.8 |
+| eval_20261026_131348 | ep_01 | D_20261024_26 | D | GLP NICE | 1 | | | user stop (key b' ') | 26.9 |
+| eval_20261026_131348 | ep_02 | D_20261024_26 | D | GLP BIT OFF | 1 | | | user stop (key b' ') | 26.6 |
+| eval_20261026_131348 | ep_03 | D_20261024_26 | D | GL STOP | 0 | | | user stop (key b' ') | 28.4 |
+| eval_20261026_131348 | ep_04 | D_20261024_26 | D | - MISS GRASP | 0 | | | time limit | 40.0 |
diff --git a/so101_pick_place/code/source.tar.gz b/so101_pick_place/code/source.tar.gz
new file mode 100644
index 0000000000000000000000000000000000000000..60e19a7a581e1ae7f15a7349b9d93c992175897d
--- /dev/null
+++ b/so101_pick_place/code/source.tar.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2531bc3caf20ae213336f3fac184e5c16a09384e0e1c0246288ea8afefd8746f
+size 619041
diff --git a/so101_pick_place/code/source_manifest.json b/so101_pick_place/code/source_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..0c613e64d8c356da3e4afa7c95ff10a910496cb4
--- /dev/null
+++ b/so101_pick_place/code/source_manifest.json
@@ -0,0 +1,490 @@
+{
+ "schema": "nedm-so101-pick-place-source/1",
+ "repository": "https://github.com/uwsbel/NeDM",
+ "source_commit": "9363774e428a844540c525d3a6458beeb3e39e4d",
+ "base_commit": "dacc64968c006340393f60e7f1e15a2b65fc4aa7",
+ "layout": "Overlay all 95 files on a Git checkout of base_commit. This recreates the original PR source tree, including its full README and 503-file data manifest. No changes to implementation bytes.",
+ "historical_branch": "so101-pick-place-study",
+ "archive": {
+ "path": "so101_pick_place/code/source.tar.gz",
+ "bytes": 619041,
+ "sha256": "2531bc3caf20ae213336f3fac184e5c16a09384e0e1c0246288ea8afefd8746f"
+ },
+ "files": {
+ "README.md": {
+ "bytes": 14170,
+ "sha256": "8a9a6a513e57ff150a787d2bc39ba21ec77c38e06b8531387f687cbf914642ea",
+ "git_mode": "100644"
+ },
+ "configs/contact_nrd/collection/so101_grasp.json": {
+ "bytes": 9918,
+ "sha256": "60fcd1e757a9d249f2f58aa3bdbb6632a917c8adc6602d34f98a79a1f23c2816",
+ "git_mode": "100644"
+ },
+ "configs/so101_pick_place/calib_v1.json": {
+ "bytes": 39147,
+ "sha256": "3b7a2124d1b56bd6049a682a4eb29e9f4cef62818f4a420665171bbe31e0410f",
+ "git_mode": "100644"
+ },
+ "configs/so101_pick_place/dyn_fit_d2q.json": {
+ "bytes": 888,
+ "sha256": "68a96d77b506bc75d368a4e6412f89b7f7f2c22585281a7b764acda7661f6918",
+ "git_mode": "100644"
+ },
+ "configs/so101_pick_place/nrd/base_c0.json": {
+ "bytes": 1392,
+ "sha256": "1c04c0aa0fb167522996c656304b7373d473bcf6ccfdbe085ca9278a3ec2007b",
+ "git_mode": "100644"
+ },
+ "configs/so101_pick_place/nrd/ft_c1_s62.json": {
+ "bytes": 2215,
+ "sha256": "201cf90e21c7a060b49c92e70485c990e83851a73bede000fcfd768c64388a89",
+ "git_mode": "100644"
+ },
+ "configs/so101_pick_place/parts_override_v2.json": {
+ "bytes": 18479,
+ "sha256": "3840ca99745839ff693dca975f9853720176ab61b3b7d751a42995e0e5366217",
+ "git_mode": "100644"
+ },
+ "configs/so101_pick_place/real_scene_v2.json": {
+ "bytes": 8654,
+ "sha256": "4bce0b8dd6f22b5499b556275bca0bf248d1e96b1cd3babf169b34a8cb539d82",
+ "git_mode": "100644"
+ },
+ "configs/so101_pick_place/so101_follower_lerobot_calib.json": {
+ "bytes": 915,
+ "sha256": "c2b8953fadcc1af32fa7a96c6b5e7a8031fff3100868c1afc2f95ee19437afc2",
+ "git_mode": "100644"
+ },
+ "configs/so101_pick_place/teacher/env_jt_b140.json": {
+ "bytes": 76,
+ "sha256": "b5871053ef25c82471b0d64a295dfbaf9d74f1bc45c4a03c344a15d04f676673",
+ "git_mode": "100644"
+ },
+ "configs/so101_pick_place/teacher/env_jt_h110.json": {
+ "bytes": 185,
+ "sha256": "a9085211b71c4956bafb8ef96f3d440cc3e97cb3edd092c9098824ec69f423da",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/ppo/curriculum_tol_v3.json": {
+ "bytes": 902,
+ "sha256": "f32cf2d1d6a2dd35c2884c980c8070010f42f9f39706694385eda5316d82153c",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/ppo/env_v2.json": {
+ "bytes": 982,
+ "sha256": "ba0c9298d5fb328a89a29ac84b074a03f029c4ff78a1c260f0cbdad04217b172",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/ppo/joint_ppo_v3.json": {
+ "bytes": 640,
+ "sha256": "f13b4da19afd6fc196dcd2c57d531b302183e4afbf32bed520a197813ca8dca6",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/ppo/r2s/joint_ppo_v3_kl02.json": {
+ "bytes": 709,
+ "sha256": "85d7d401abbdc749b9f52d0c07a4d4a0adb5c04011f777325f7c75e1076eebf1",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/ppo/r2s/teacher_roll_v12_fr10.json": {
+ "bytes": 2746,
+ "sha256": "fe4344327259bcb4d39bbbf1c3832665b3fa65b92dc7dcf5d99870b29c69aef7",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/ppo/r2s/teacher_roll_v8.json": {
+ "bytes": 2810,
+ "sha256": "369725ad6f7f3c99cc26b5d72fca832675aa900f3e57be642fc6682f0db87989",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/ppo/train_v2.json": {
+ "bytes": 1118,
+ "sha256": "1c756e595b14cbe200e5f3704483c8fff72b37c59236a73e7e9fb59fc41d8324",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/vision/viral_r2s_home.json": {
+ "bytes": 841,
+ "sha256": "e6543ffe40f6296731a0b2bfece881e6967b85e42d930a85eb26ac78d49c2120",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/vision/viral_r2s_online_relabel_roll_v8.json": {
+ "bytes": 2543,
+ "sha256": "60698c373370fc97017167601d2e642b0f1896d18e3186453bc332c6a599df33",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/vision/viral_r2s_online_relabel_v4.json": {
+ "bytes": 1372,
+ "sha256": "5877a96570712a2a0a592cd59e015a52c9e323c0accc816a6b841e6d148c2d41",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/vision/viral_r2s_online_v1.json": {
+ "bytes": 754,
+ "sha256": "b3489b952a478e7bcc9dd5211690038acb1db709515f23c36989798e7dccee10",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/vision/viral_r2s_online_v12_tb10.json": {
+ "bytes": 3514,
+ "sha256": "b55e31fca136d16293eddf64b8704b718b72b6d74d11d6cae53b062357c761ff",
+ "git_mode": "100644"
+ },
+ "configs/so101_policy/vision/viral_r2s_v1.json": {
+ "bytes": 1927,
+ "sha256": "c182046bd21029bf099fffa9a26ec47849efbc40313cdcad72bdfe2a9e1f9701",
+ "git_mode": "100644"
+ },
+ "contact_nrd/so101_grasp/.gitignore": {
+ "bytes": 21,
+ "sha256": "b0e9ee2e09d9697566760f94f62331a7c4deda97d8e9da77a0b5c02dd2cbff57",
+ "git_mode": "100644"
+ },
+ "contact_nrd/so101_grasp/fetch_sources.py": {
+ "bytes": 2983,
+ "sha256": "2718b31e82083f6e20daa5d87f93126cfcbf49c6ad8eafaddf37be1becbdfdbc",
+ "git_mode": "100644"
+ },
+ "contact_nrd/so101_grasp/source_manifest.json": {
+ "bytes": 5816,
+ "sha256": "37f97751ee23d20f91a06c1e9796f1cf781df86c9eb1e64106c0cec1292e6a87",
+ "git_mode": "100644"
+ },
+ "docs/hf_dataset_card.md": {
+ "bytes": 76265,
+ "sha256": "fc8d156a3bad56cf0cc9bacf32982d78cd65313385862e7e02dfd1106d7f498d",
+ "git_mode": "100644"
+ },
+ "requirements-so101-pick-place.txt": {
+ "bytes": 2738,
+ "sha256": "ec1abb57eaa090720727714e3d4d6fdeb20f64fea828d29a662879b58cd032df",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/check/check_analyze.py": {
+ "bytes": 11355,
+ "sha256": "85f72e1f96bf6fa3314d285b31af948c58923e4fd28adf3ed4e27c91f91d35b9",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/check/check_eval.py": {
+ "bytes": 13617,
+ "sha256": "d71f85a1853c90469a807163c833013f6361cfd723c395af69a6dd3d26e45c15",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/check/gates_summary.py": {
+ "bytes": 15678,
+ "sha256": "3262a090349636cd57f310646e2d65e886580115bd9fa86a2c545616fa9e6201",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/check/run_gates.sh": {
+ "bytes": 6368,
+ "sha256": "f03776f8d9ee177a7edc053d35ddd376dcf1222a0590361c954644f116260ee4",
+ "git_mode": "100755"
+ },
+ "scripts/so101_pick_place/check/sel_rules.py": {
+ "bytes": 7061,
+ "sha256": "467b9588a72d4c4d1e0eaa0d890944288b7b8308c4bbaa2ee241aae2dc61a009",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/check/sim_eps.py": {
+ "bytes": 9170,
+ "sha256": "8523a5045e67cbc08392bee63400c1937779113e3f6e497719df05dae2dab11b",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/download.py": {
+ "bytes": 7672,
+ "sha256": "7aec223504af3cf2e56d64cfa1f60dafa2587774a4d8baed4798aec324f359f9",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/nrd/equiv.py": {
+ "bytes": 2579,
+ "sha256": "09d1def26019f73258c4f8f5cf374aa571e1671468e6606473045962915e6c0b",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/nrd/equiv_compare.py": {
+ "bytes": 2198,
+ "sha256": "53eccc1e18d676f45b0b92559aecb98595789a32fe512ecf834cfbaea7627f73",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/nrd/strip_ckpt.py": {
+ "bytes": 7081,
+ "sha256": "7e79a240c4a0872c8670069d9795f46a2441fa55c3a9fcf4deb51200d9cd2bc5",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/nrd/subsets.py": {
+ "bytes": 3538,
+ "sha256": "cf235a88435b301acfac08d9e5e2d7ec4ba01c7173824d308e2b75ceaed3bacb",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/nrd/summarize.py": {
+ "bytes": 4801,
+ "sha256": "75f2fc9b67286ad7b24128c01fe0ea0e65b1ec6fba7c4e124e9cfeff8607acc3",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/reproduce.sh": {
+ "bytes": 54890,
+ "sha256": "2c184546db586bc86fbd44d3524cc178af58c00266c851ad46cba712929502fb",
+ "git_mode": "100755"
+ },
+ "scripts/so101_pick_place/robot/build_results.py": {
+ "bytes": 18057,
+ "sha256": "74a20581ae0fd068d593f4fdc86759e1880207da1e2aa9cbab70fce15f25aefb",
+ "git_mode": "100644"
+ },
+ "scripts/so101_pick_place/robot/render_videos.py": {
+ "bytes": 9994,
+ "sha256": "31f8e5dd557107443b264438965225a99e1f55b281e7aef0f4d6a0760d62a299",
+ "git_mode": "100644"
+ },
+ "scripts/so101_policy/real2sim/hw/QDGAIN_TEST.md": {
+ "bytes": 6685,
+ "sha256": "0dbb6b1845c7716a4645e0cc439bd69ba4b0ecb81397ec63e65ef1286dcac04c",
+ "git_mode": "100644"
+ },
+ "scripts/so101_policy/real2sim/hw/README.md": {
+ "bytes": 21688,
+ "sha256": "959d7e485e15f37db6014ae60a95a4eb1d65bf2417d9656b524982dbd4601350",
+ "git_mode": "100644"
+ },
+ "scripts/so101_policy/real2sim/hw/hw_lib.py": {
+ "bytes": 66740,
+ "sha256": "8b52bf6ed13843b9ee69fb0b2b904804c73b4e73d6d86f6abd75ffe8640a0a68",
+ "git_mode": "100644"
+ },
+ "scripts/so101_policy/real2sim/hw/make_orin_bundle.sh": {
+ "bytes": 3751,
+ "sha256": "9fa7e207d131f26520973d54f562bb5ef260c300448eb318edab86b5ede2ee3e",
+ "git_mode": "100755"
+ },
+ "scripts/so101_policy/real2sim/hw/robot_test.sh": {
+ "bytes": 10556,
+ "sha256": "313e5d82a11f3a38dec96cdd052900d332dda7a87b427612cc0296159c4c46b4",
+ "git_mode": "100755"
+ },
+ "scripts/so101_policy/real2sim/hw/run_student_real.py": {
+ "bytes": 67050,
+ "sha256": "7b6d506cd6810513cea8c931cf707c01490b81038112e4d04e9eaba4ec84712b",
+ "git_mode": "100755"
+ },
+ "scripts/so101_policy/train_ppo.py": {
+ "bytes": 22342,
+ "sha256": "7bc69dc0cda6f0e371c1e282ad788807e366c63d1304d902e4e318a406952f3c",
+ "git_mode": "100644"
+ },
+ "scripts/so101_policy/vision_viral.py": {
+ "bytes": 55392,
+ "sha256": "3523bd9fc0168d440a5fef52e869fad739789d8400cbb86e56cc2b4371797b42",
+ "git_mode": "100644"
+ },
+ "scripts/so101_policy/vision_viral_teacher.py": {
+ "bytes": 27505,
+ "sha256": "f0e60b4ce3cb5529c942a64fe759326c3d86c60805a6e7514a114e5e916906b5",
+ "git_mode": "100644"
+ },
+ "so101_pick_place/README.md": {
+ "bytes": 40408,
+ "sha256": "7f06de569e46c70be15e563b6c33af7be1f8963648d40a2e1188694b5acd55d0",
+ "git_mode": "100644"
+ },
+ "so101_pick_place/release_manifest.json": {
+ "bytes": 90247,
+ "sha256": "77e6778afe7bfd2815e30349a143cd95cc7a33551e60fe284d2795a76d61625b",
+ "git_mode": "100644"
+ },
+ "so101_pick_place/results/robot_results.md": {
+ "bytes": 15487,
+ "sha256": "ec965c364942557c65f3d84d875b05d67180bcc4a9cbc9845ce55113aaf6f7dc",
+ "git_mode": "100644"
+ },
+ "src/nedm/contact_nrd/collect/__init__.py": {
+ "bytes": 324,
+ "sha256": "df386e217217304eefd3dd3d3d089752ec8cfbeb1b8360b68485a17bee234982",
+ "git_mode": "100644"
+ },
+ "src/nedm/contact_nrd/collect/export.py": {
+ "bytes": 16181,
+ "sha256": "f1895b08518e23dbdc204050adf078e0398ec5b24d427e201b5b7b51a5cc3890",
+ "git_mode": "100644"
+ },
+ "src/nedm/contact_nrd/collect/so101_grasp.py": {
+ "bytes": 115533,
+ "sha256": "c650e2d680ca51cc953e9d00b5f44b50c701d756ce063f3f0553d7f11e4d1f6b",
+ "git_mode": "100644"
+ },
+ "src/nedm/contact_nrd/collect/validate.py": {
+ "bytes": 16910,
+ "sha256": "19ce9c2243c0b70b5696b79d40ddd3c5173dcb498bc96a764dab0f495f520e81",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/__init__.py": {
+ "bytes": 1239,
+ "sha256": "571c34176d05a81c4f459ae4596b361477b1820a080956970568118b436adfba",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/backends/__init__.py": {
+ "bytes": 720,
+ "sha256": "b4836f4223eccf36b45dd5cb95b5f640440355395ae4264a59888a1e8afb41ec",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/backends/newton.py": {
+ "bytes": 15821,
+ "sha256": "0a82adf5a10589e91492e33c45fa248953bd9b64d9b478aa6ac143fef20f62c9",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/camera_fx.py": {
+ "bytes": 13360,
+ "sha256": "96cbe7e27a7ec8c605c747735e5c78d3eace3a01acacf1c5de40f80b1d1a74f6",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/cameras.py": {
+ "bytes": 17425,
+ "sha256": "4ca01daf70b7f3e7f9b5ff3fe9fc2002a4f043a9d033245270b6dae15f7ad1e7",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/poses.py": {
+ "bytes": 8147,
+ "sha256": "52e100403164e00eacc216347425c34d3ca4ad4e67af749d730af07b4c1c1433",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/renderer.py": {
+ "bytes": 5922,
+ "sha256": "3b7ec12fcde07fb23ee97562d17359ecc160f942f6476d32f8007ce6435372b5",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/scene.py": {
+ "bytes": 7508,
+ "sha256": "f45602c61fc445e88b2c6833ea384c607f9c86d64c297109e0fa2eb4d779ccf4",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/so101.py": {
+ "bytes": 132740,
+ "sha256": "3ce5cb795dc8938682a3d222b48f0cd7fa2dd9996e6dc2afc09aa1aba0319f03",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/student_view.py": {
+ "bytes": 5678,
+ "sha256": "1f2093327df62a87f0759bf19648ae088ccfd5ae9a16d2f6a053cd74c5223ba9",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/urdf.py": {
+ "bytes": 9566,
+ "sha256": "5ae66cc15023805c101269655b0521a4630d54ceb66cf1040afe710d4f8128eb",
+ "git_mode": "100644"
+ },
+ "src/nedm/render/video.py": {
+ "bytes": 1985,
+ "sha256": "faca5f7908d226635f3f04fd660a2061d5bd11ed546a42e8bf71d396f43821e9",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/__init__.py": {
+ "bytes": 123,
+ "sha256": "9f3d9faf9d8c2b7874f9b4f4cb80b05bf828a5ea6e83c2b3cf4a05bc9d3649f3",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/cube_symmetry.py": {
+ "bytes": 7224,
+ "sha256": "c2b3b99c67c8b91597d426fb0f5c6ef502b22e993def9f493032c13fd96c15c5",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/decoder.py": {
+ "bytes": 91166,
+ "sha256": "fddfa91c60ca78e937e3dddc48d0c43fefb7b304b4d32d61b2c5762025b90640",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/joint_env.py": {
+ "bytes": 125696,
+ "sha256": "3bc4a391207bcbbd5e43dd3f2782f69aafea730f0db2a40b2fe27242dd805a74",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/joint_teacher.py": {
+ "bytes": 34658,
+ "sha256": "4e4b439ddd6934d31fe23d23852923c2df41b64e83f15faf591e346ff3beba9e",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/kin.py": {
+ "bytes": 25198,
+ "sha256": "20388d992ffaf8f1e49b2a3e1bb1e6b0fadf39b0d292019c9aa3e945e4a44d4d",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/mujoco_env.py": {
+ "bytes": 50112,
+ "sha256": "5b0e600cf4e063cca9bef4098cae3db2051c436b7f88fc33580fccbee14b8278",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/npz_rows.py": {
+ "bytes": 2156,
+ "sha256": "1349f7a01890794924f9e67d4d8cb0fafef52090c9ec858a9a3dd6e904f618f1",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/nrd_sim.py": {
+ "bytes": 34351,
+ "sha256": "7f0eb1af35ce5d2e40c7509600a2e05f723d1e8adb49f7088e30c57d33e74df8",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/paths.py": {
+ "bytes": 1281,
+ "sha256": "eeb70027b4b4a5c0045b7fb5210b127953bf0040109ac065b753b39ee847bbd9",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/ppo.py": {
+ "bytes": 28858,
+ "sha256": "b026e361f0f285112000d6533770d5478b2e6a11a3885b65af4af8d9f41118be",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/table.py": {
+ "bytes": 7639,
+ "sha256": "9e8f1a316dfc404aa1e921e65031f09b282a7ebfbf199207161157872d08e638",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/table_bias.py": {
+ "bytes": 19848,
+ "sha256": "70eeb69db57d6c58fb2028e6f51aff214a17337dd11ef8bd86bf0dc45cb136c9",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/task.py": {
+ "bytes": 70956,
+ "sha256": "7201482c0bc78790abf598d737964b02e3c9f1c10e0602b5e396c63689cd8c2f",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/vec_env.py": {
+ "bytes": 40093,
+ "sha256": "01c66edd6069fd8802811f612c2d6dd2be9a14bc546b185a5b21c7ad6d7474a1",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/vision/__init__.py": {
+ "bytes": 359,
+ "sha256": "61fc1f756e386e006acf692806a94c828857754c43516ba6fa8c559a06bd04d0",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/vision/dataset.py": {
+ "bytes": 12523,
+ "sha256": "bd0bbbe89299d6560be3284da666e1c1c9ecbbc93703c2758521e4cc97d20087",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/vision/demos.py": {
+ "bytes": 13427,
+ "sha256": "a91d5896786403ff076f8b2e3332c0caf563d1ac9dd5aa5a3400a9c9ea26cde9",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/vision/perstep.py": {
+ "bytes": 21219,
+ "sha256": "76caa665585b33e83ed8baa69232e4cd5cc1d99ad2011f555250cda0c39dc7fb",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/vision/teacher.py": {
+ "bytes": 18106,
+ "sha256": "41b5827989f3b99e92bb42f2d7ccf3ccbaa97b8c004d4e72ab07bb6c3a08d53a",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/vision/tray.py": {
+ "bytes": 72059,
+ "sha256": "cf287fcb99422d161adbbd6c176cf5674515e7df91e027e59ca0bd55868925e1",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/vision/viral.py": {
+ "bytes": 179050,
+ "sha256": "c0708f0ad8a254badedb4ccb2a4af99c7515e3467327f7b2f63973a846fcb957",
+ "git_mode": "100644"
+ },
+ "src/nedm/so101_policy/world.py": {
+ "bytes": 2197,
+ "sha256": "8650e24eca6a19d2c0a578822b4ce0cd63daddcc216ebdd43e9f27742d44e576",
+ "git_mode": "100644"
+ }
+ }
+}
diff --git a/so101_pick_place/code/src/nedm/contact_nrd/collect/__init__.py b/so101_pick_place/code/src/nedm/contact_nrd/collect/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..206bf03baf6bec0f0dd3949f86f0a85f70e4cbf7
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/contact_nrd/collect/__init__.py
@@ -0,0 +1,5 @@
+"""Simulation collectors that write contact NRD training data (system.json + unified_data.npz).
+
+The collectors run MuJoCo on the CPU and need only numpy, mujoco and scipy; they do not import torch. The data contract is in contact_nrd/collection_contract.md. ``export`` writes a data directory,
+``validate`` checks one.
+"""
diff --git a/so101_pick_place/code/src/nedm/contact_nrd/collect/export.py b/so101_pick_place/code/src/nedm/contact_nrd/collect/export.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6b1a4ef7b5c701395d0a92e38bb2408dcec84fe
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/contact_nrd/collect/export.py
@@ -0,0 +1,320 @@
+"""Write a contact NRD data directory: system.json, unified_data.npz and manifest.json.
+
+The contract (array names, shapes, units, padding, contact labels) is in contact_nrd/collection_contract.md. A
+collector builds one dict per episode (see ``pack_episodes``), packs the episodes of a worker into a shard
+(``write_shard``), and the main process merges the shards and writes the directory (``merge_shards``,
+``write_dataset``). numpy only.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import platform
+import subprocess
+import sys
+import time
+from importlib import metadata
+from pathlib import Path
+
+import numpy as np
+
+STATE_TYPES = ("position", "quaternion", "angle", "velocity", "angular_velocity", "angular_rate")
+REPO_ROOT = Path(__file__).resolve().parents[4]
+
+
+# ---- rotations (quaternions wxyz) ---------------------------------------------------------------
+def quat_to_matrix(q):
+ """[..., 4] unit quaternions (w, x, y, z) -> [..., 3, 3] rotation matrices (body -> world)."""
+ q = np.asarray(q, np.float64)
+ w, x, y, z = np.moveaxis(q, -1, 0)
+ return np.stack((np.stack((1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)), -1),
+ np.stack((2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)), -1),
+ np.stack((2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)), -1)), -2)
+
+
+def body_to_world(q, v_body):
+ """Rotate body-frame vectors [..., 3] into the world frame with quaternions [..., 4] (MuJoCo free-joint qvel[3:6]
+ is the angular velocity in the body frame; the contract stores it in the world frame)."""
+ return np.einsum("...ij,...j->...i", quat_to_matrix(q), np.asarray(v_body, np.float64))
+
+
+def quat_continuous(q):
+ """[T, 4] quaternions of one episode -> unit length, w >= 0 at the first record, sign continuous along T."""
+ q = np.asarray(q, np.float64)
+ q = q / np.linalg.norm(q, axis=-1, keepdims=True)
+ out = q.copy()
+ if out[0, 0] < 0:
+ out[0] = -out[0]
+ for t in range(1, len(out)):
+ if np.dot(out[t - 1], out[t]) < 0:
+ out[t] = -out[t]
+ return out
+
+
+# ---- episodes -> padded arrays -------------------------------------------------------------------
+def pack_episodes(episodes, system):
+ """Pad a list of episodes to the system's records_per_episode and stack them.
+
+ Each episode is a dict:
+ states {moving body name: [L, state_dim]} (L valid records, L >= 2)
+ action [L, A] applied command of the interval that starts at each record (only if a body acts)
+ contacts [L-1, P] 0/1: pair p touched during record interval k (between records k and k+1)
+ per_record optional {name: [L, ...]} extra arrays at the records (e.g. teacher command)
+ per_interval optional {name: [L-1, ...]} extra arrays of the intervals (e.g. max normal force)
+ scalars optional {name: number} one value per episode (family, episode_id, seed, outcome, ...)
+ Padding: states, action and per-record arrays repeat their last valid record; contacts and per-interval arrays
+ are zero after the last valid interval. Returns {array name: stacked array} with lengths [N] (int32).
+ """
+ t_rec = int(system["records_per_episode"])
+ moving = [b for b in system["bodies"] if b["moving"]]
+ n_pairs = len(system["pairs"])
+ out = {b["name"]: [] for b in moving}
+ out.update(action=[], contacts=[], lengths=[])
+ extra_rec, extra_int, extra_sc = {}, {}, {}
+ acting = any(int(b.get("action_dim", 0)) for b in moving)
+ for ep in episodes:
+ length = len(ep["states"][moving[0]["name"]])
+ if not 2 <= length <= t_rec:
+ raise ValueError(f"episode length {length} outside [2, {t_rec}]")
+ for b in moving:
+ x = np.asarray(ep["states"][b["name"]], np.float32)
+ if x.shape != (length, int(b["state_dim"])):
+ raise ValueError(f"{b['name']}: shape {x.shape}, expected {(length, int(b['state_dim']))}")
+ out[b["name"]].append(_pad_repeat(x, t_rec))
+ if acting:
+ a = np.asarray(ep["action"], np.float32)
+ if len(a) != length:
+ raise ValueError(f"action has {len(a)} records, states {length}")
+ out["action"].append(_pad_repeat(a, t_rec))
+ c = np.asarray(ep["contacts"], np.uint8)
+ if c.shape != (length - 1, n_pairs):
+ raise ValueError(f"contacts shape {c.shape}, expected {(length - 1, n_pairs)}")
+ out["contacts"].append(_pad_zero(c, t_rec - 1))
+ out["lengths"].append(length)
+ for k, v in (ep.get("per_record") or {}).items():
+ extra_rec.setdefault(k, []).append(_pad_repeat(np.asarray(v), t_rec))
+ for k, v in (ep.get("per_interval") or {}).items():
+ extra_int.setdefault(k, []).append(_pad_zero(np.asarray(v), t_rec - 1))
+ for k, v in (ep.get("scalars") or {}).items():
+ extra_sc.setdefault(k, []).append(v)
+ arrays = {k: np.stack(v) for k, v in out.items() if v}
+ arrays["lengths"] = np.asarray(out["lengths"], np.int32)
+ for group in (extra_rec, extra_int):
+ for k, v in group.items():
+ if len(v) != len(episodes):
+ raise ValueError(f"extra array {k} missing in some episodes")
+ arrays[k] = np.stack(v)
+ for k, v in extra_sc.items():
+ if len(v) != len(episodes):
+ raise ValueError(f"scalar {k} missing in some episodes")
+ arrays[k] = np.asarray(v)
+ return arrays
+
+
+def _pad_repeat(x, n):
+ if len(x) == n:
+ return x
+ return np.concatenate((x, np.repeat(x[-1:], n - len(x), 0)), 0)
+
+
+def _pad_zero(x, n):
+ if len(x) == n:
+ return x
+ return np.concatenate((x, np.zeros((n - len(x),) + x.shape[1:], x.dtype)), 0)
+
+
+# ---- splits ---------------------------------------------------------------------------------------
+def assign_splits(families, groups, fractions=(0.9, 0.1), seed=0, split_ids=(0, 1)):
+ """Deterministic family-stratified split. families [N] family index, groups [N] group id (episodes of one
+ group, e.g. the branches of one parent trajectory, always share a split). Within each family the groups are
+ shuffled with the seed and cut by ``fractions``; returns splits [N] int8 with the values of ``split_ids``."""
+ families, groups = np.asarray(families), np.asarray(groups)
+ if abs(sum(fractions) - 1) > 1e-9 or len(fractions) != len(split_ids):
+ raise ValueError("fractions must sum to 1 and match split_ids")
+ splits = np.full(len(families), -1, np.int8)
+ for f in np.unique(families):
+ sel = families == f
+ uniq = np.unique(groups[sel])
+ rng = np.random.default_rng([int(seed), int(f)])
+ uniq = uniq[rng.permutation(len(uniq))]
+ cuts = np.round(np.cumsum(fractions)[:-1] * len(uniq)).astype(int)
+ for part, sid in zip(np.split(uniq, cuts), split_ids):
+ splits[sel & np.isin(groups, part)] = sid
+ return splits
+
+
+# ---- shards and the data directory --------------------------------------------------------------
+def write_shard(path, arrays):
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(path.name + ".tmp.npz")
+ np.savez(tmp, **arrays)
+ tmp.replace(path)
+
+
+def merge_shards(paths):
+ """Concatenate shard files (same array names) along the episode axis, in the given order."""
+ parts = []
+ for p in paths:
+ with np.load(p) as f:
+ parts.append({k: f[k] for k in f.files})
+ keys = list(parts[0])
+ for p, part in zip(paths, parts):
+ if list(part) != keys:
+ raise ValueError(f"shard {p} has arrays {list(part)}, expected {keys}")
+ return {k: np.concatenate([part[k] for part in parts], 0) for k in keys}
+
+
+def check_arrays(system, arrays):
+ """Shape and dtype checks of the arrays that contact NRD training reads (raises ValueError)."""
+ moving = [b for b in system["bodies"] if b["moving"]]
+ n = len(arrays["lengths"])
+ t_rec = int(system["records_per_episode"])
+ for b in moving:
+ s = int(b["state_dim"])
+ if len(b["channels"]) != s or len(b["channel_types"]) != s:
+ raise ValueError(f"{b['name']}: channels/channel_types length differs from state_dim {s}")
+ bad = set(b["channel_types"]) - set(STATE_TYPES)
+ if bad:
+ raise ValueError(f"{b['name']}: unknown channel types {bad}")
+ if "channel_mask" in b and len(b["channel_mask"]) != s:
+ raise ValueError(f"{b['name']}: channel_mask length differs from state_dim")
+ if arrays[b["name"]].shape != (n, t_rec, s):
+ raise ValueError(f"{b['name']}: shape {arrays[b['name']].shape}, expected {(n, t_rec, s)}")
+ acting = [b for b in moving if int(b.get("action_dim", 0))]
+ if len(acting) > 1:
+ raise ValueError("the loader supports one actuated body")
+ if acting:
+ a = int(acting[0]["action_dim"])
+ if arrays["action"].shape != (n, t_rec, a):
+ raise ValueError(f"action shape {arrays['action'].shape}, expected {(n, t_rec, a)}")
+ if arrays["contacts"].shape != (n, t_rec - 1, len(system["pairs"])):
+ raise ValueError(f"contacts shape {arrays['contacts'].shape}")
+ if arrays["splits"].shape != (n,) or not np.isin(arrays["splits"], (0, 1, 2)).all():
+ raise ValueError("splits must be [N] with values 0, 1, 2")
+ names = [b["name"] for b in system["bodies"]]
+ for i, j in system["pairs"]:
+ if not (0 <= i < len(names) and 0 <= j < len(names)) or not system["bodies"][i]["moving"]:
+ raise ValueError(f"pair {(i, j)}: the first body must be a moving body index")
+ if "pair_metadata" in system and len(system["pair_metadata"]) != len(system["pairs"]):
+ raise ValueError("pair_metadata must have one entry per pair")
+ check_evaluation_arrays(system, arrays)
+
+
+def check_evaluation_arrays(system, arrays):
+ """The per-record integer array that the evaluation block's timing_exclude names (SO101: phase) must exist."""
+ exclude = (system.get("evaluation") or {}).get("timing_exclude")
+ if not exclude:
+ return
+ n, t_rec = len(arrays["lengths"]), int(system["records_per_episode"])
+ x = arrays.get(exclude["array"])
+ if x is None or x.shape != (n, t_rec) or x.dtype.kind not in "iu":
+ raise ValueError(f"evaluation timing_exclude needs an integer array {exclude['array']!r} [N, T]")
+ names = exclude.get("names")
+ if names is not None and not set(exclude["values"]) <= set(system.get(names) or []):
+ raise ValueError(f"evaluation timing_exclude: system.json {names!r} must list {exclude['values']}")
+
+
+def write_dataset(out_dir, system, arrays, manifest=None):
+ """Write unified_data.npz, system.json and manifest.json (file hashes, environment, counts) into out_dir."""
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ spec = REPO_ROOT / "configs/contact_nrd/evaluation" / f"{system['name']}.json"
+ if "evaluation" not in system and spec.exists(): # the task metrics of training and test (see that folder)
+ system = {**system, "evaluation": json.loads(spec.read_text())}
+ arrays = dict(arrays)
+ arrays["lengths"] = np.asarray(arrays["lengths"], np.int32)
+ arrays["splits"] = np.asarray(arrays["splits"], np.int8)
+ arrays["contacts"] = np.asarray(arrays["contacts"], np.uint8)
+ check_arrays(system, arrays)
+ tmp = out / "unified_data.tmp.npz"
+ np.savez(tmp, **arrays)
+ tmp.replace(out / "unified_data.npz")
+ (out / "system.json").write_text(json.dumps(system, indent=1, allow_nan=False) + "\n")
+ info = dict(manifest or {})
+ info.setdefault("created_utc", time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
+ info.setdefault("environment", environment_info())
+ info.setdefault("code", git_info())
+ info["episodes"] = int(len(arrays["lengths"]))
+ info["valid_records"] = int(arrays["lengths"].sum())
+ info["split_counts"] = {str(s): int((arrays["splits"] == s).sum()) for s in (0, 1, 2)}
+ if "family" in arrays and "families" in system:
+ names = [f["name"] for f in system["families"]]
+ info["family_counts"] = {names[f]: {str(s): int(((arrays["family"] == f) & (arrays["splits"] == s)).sum())
+ for s in (0, 1, 2)} for f in range(len(names))}
+ info["arrays"] = {k: dict(shape=list(v.shape), dtype=str(v.dtype)) for k, v in arrays.items()}
+ info["files"] = {name: dict(bytes=(out / name).stat().st_size, sha256=sha256_file(out / name))
+ for name in ("unified_data.npz", "system.json")}
+ (out / "manifest.json").write_text(json.dumps(info, indent=1, allow_nan=False) + "\n")
+ return info
+
+
+# ---- provenance -----------------------------------------------------------------------------------
+def sha256_file(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as fh:
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def environment_info():
+ pkgs = {}
+ for name in ("mujoco", "numpy", "scipy", "onnxruntime"):
+ try:
+ pkgs[name] = metadata.version(name)
+ except metadata.PackageNotFoundError:
+ pass
+ return dict(python=sys.version.split()[0], platform=platform.platform(), host=platform.node(),
+ cpu_count=os.cpu_count(), packages=pkgs)
+
+
+def git_info(root=REPO_ROOT):
+ def run(*cmd):
+ try:
+ return subprocess.run(cmd, cwd=root, capture_output=True, text=True, check=True).stdout
+ except (OSError, subprocess.CalledProcessError):
+ return None
+ commit = run("git", "rev-parse", "HEAD")
+ if commit is None:
+ return {"commit": None}
+ status = run("git", "status", "--porcelain") or ""
+ diff = run("git", "diff", "HEAD") or ""
+ untracked = sorted((run("git", "ls-files", "--others", "--exclude-standard", "--", "src", "configs") or "").split())
+ h = hashlib.sha256(diff.encode())
+ for name in untracked: # new files are not in the diff: hash their names and contents too
+ h.update(name.encode())
+ h.update((Path(root) / name).read_bytes())
+ return dict(commit=commit.strip(), dirty=bool(status.strip()), untracked_files=len(untracked),
+ diff_sha256=h.hexdigest() if (diff or untracked) else None)
+
+
+def refresh_evaluation(data_dir):
+ """Replace the "evaluation" block of a data directory's system.json by the current
+ configs/contact_nrd/evaluation/.json and update the system.json hash in manifest.json. The arrays do not
+ change. Returns True if the block changed."""
+ root = Path(data_dir)
+ system = json.loads((root / "system.json").read_text())
+ spec = json.loads((REPO_ROOT / "configs/contact_nrd/evaluation" / f"{system['name']}.json").read_text())
+ if system.get("evaluation") == spec:
+ return False
+ system["evaluation"] = spec
+ if spec.get("timing_exclude"):
+ with np.load(root / "unified_data.npz") as f: # reads only the arrays asked for
+ check_evaluation_arrays(system, {"lengths": f["lengths"], spec["timing_exclude"]["array"]:
+ f[spec["timing_exclude"]["array"]] if spec["timing_exclude"]["array"] in f.files else None})
+ (root / "system.json").write_text(json.dumps(system, indent=1, allow_nan=False) + "\n")
+ info = json.loads((root / "manifest.json").read_text())
+ info["files"]["system.json"] = dict(bytes=(root / "system.json").stat().st_size, sha256=sha256_file(root / "system.json"))
+ info.setdefault("evaluation_refreshed_utc", []).append(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
+ (root / "manifest.json").write_text(json.dumps(info, indent=1, allow_nan=False) + "\n")
+ return True
+
+
+if __name__ == "__main__":
+ import argparse
+ parser = argparse.ArgumentParser(description="Refresh the evaluation block of data directories.")
+ parser.add_argument("refresh_evaluation", nargs="+", type=Path, metavar="DIR")
+ for d in parser.parse_args().refresh_evaluation:
+ print(d, "changed" if refresh_evaluation(d) else "unchanged")
diff --git a/so101_pick_place/code/src/nedm/contact_nrd/collect/so101_grasp.py b/so101_pick_place/code/src/nedm/contact_nrd/collect/so101_grasp.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8f47248388dbc14b13b00aadbc1974ec8754563
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/contact_nrd/collect/so101_grasp.py
@@ -0,0 +1,2113 @@
+"""SO101 cube grasping in CPU MuJoCo: scene, scripted motion, probes and the collector of the contact NRD data.
+
+ PYTHONPATH=src python -P -m nedm.contact_nrd.collect.so101_grasp collect --out DIR [--campaign pilot]
+ [--workers 6] [--chunk 16] [--scale S] [--probe-scale S] [--families ...]
+ PYTHONPATH=src python -P -m nedm.contact_nrd.collect.so101_grasp convergence --out DIR/convergence.json \
+ [--workers 6]
+ PYTHONPATH=src python -P -m nedm.contact_nrd.collect.so101_grasp report DIR
+ MUJOCO_GL=egl PYTHONPATH=src python -P -m nedm.contact_nrd.collect.so101_grasp render DIR --episodes 2 425 1462
+
+Contract (contact_nrd/collection_contract.md): body 0 ``arm`` (12 channels: the 6 joint angles, jaw included, then
+the 6 joint rates), body 1 ``cube`` (13: position, quaternion wxyz, world velocity, world angular velocity), body 2
+``table`` (fixed, top at z = 0). Pairs [0,1] fixed jaw-cube, [0,1] moving jaw-cube, [1,2] cube-table. A record
+every 10 ms; the 6 joint position targets (float32, the applied values, kept ``joint_target_margin_rad`` inside the
+joint limits) change every 20 ms and hold in between; the physics step divides 10 ms. A pair is on in a record
+interval if its summed normal force (mj_contactForce; elliptic cones: the first constraint force of each contact) in
+any physics step of the interval is above ``contact_threshold_n`` (MuJoCo computes the contacts and forces of a step
+from the state at its start). Any other contact above that threshold (arm-table, other arm links or the arm base
+with the cube, arm self-contact) ends the episode at the last record before that interval; so does the cube leaving
+the table top, and a record at which the cube overlaps the visual meshes of the gripper or the moving jaw by more
+than ``visual_overlap.threshold_m`` beyond the penetration of that body's collision geoms (parts of the real gripper
+without a collision shape; the episode ends at the record before). The arm is the MuJoCo Menagerie SO101 (pinned in
+contact_nrd/so101_grasp/source_manifest.json), loaded unchanged with MjSpec; the table, the cube, the options, names
+for the unnamed collision geoms and collision hulls of the base's visual meshes (the Menagerie base has no collision
+geoms) are added here. All physical parameters are fixed; only initial states and the scripted commands are random.
+Campaigns (pilot, production, test) have their own master seeds in the config. numpy, scipy (overlap grids) and
+mujoco only.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import math
+import multiprocessing as mp
+import os
+import shutil
+import time
+from concurrent.futures import ProcessPoolExecutor
+from pathlib import Path
+
+import mujoco
+import numpy as np
+
+from nedm.contact_nrd.collect import export, validate
+
+CONFIG = export.REPO_ROOT / "configs/contact_nrd/collection/so101_grasp.json"
+JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper")
+PAIRS = ("fixed_jaw_cube", "moving_jaw_cube", "cube_table")
+# contact classes after the three pairs (unsupported: they end the episode)
+TERMINAL = ("end", "arm_table", "cube_other_link", "arm_self", "cube_base", "cube_off_table", "cube_visual_overlap")
+PHASES = ("idle", "approach", "descend", "close", "grip", "lift", "hold", "move", "lower", "release", "retreat",
+ "free", "push", "open_drop", "shake", "rest", "throw", "tap", "swat", "loosen")
+OUTCOMES = ("probe", "missed", "lifted_held", "lifted_dropped")
+P = {name: k for k, name in enumerate(PHASES)}
+NONE, FIXED, MOVING, CUBE, TABLE, LINK, BASE = range(7)
+
+
+class PlanError(RuntimeError):
+ """A scripted pose is out of reach (the family samples again)."""
+
+
+def load_config(path=CONFIG):
+ return json.loads(Path(path).read_text())
+
+
+def vendor_model(cfg):
+ """Path of the pinned so101.xml and the source manifest."""
+ mpath = export.REPO_ROOT / cfg["source_manifest"]
+ manifest = json.loads(mpath.read_text())
+ path = mpath.parent / manifest["source"]["local_path"] / manifest["model"]["path"]
+ if not path.exists():
+ raise SystemExit(f"{path} is missing: run python -I contact_nrd/so101_grasp/fetch_sources.py")
+ return path, manifest
+
+
+def verify_assets(cfg):
+ """sha256 of every pinned vendor file against the manifest -> {path: sha256}."""
+ path, manifest = vendor_model(cfg)
+ root = (export.REPO_ROOT / cfg["source_manifest"]).parent / manifest["source"]["local_path"]
+ out = {}
+ for item in manifest["files"]:
+ digest = export.sha256_file(root / item["path"])
+ if digest != item["sha256"]:
+ raise SystemExit(f"vendor file {item['path']} differs from the manifest")
+ out[item["path"]] = digest
+ return out
+
+
+# ---- scene --------------------------------------------------------------------------------------------------
+def build_spec(cfg, physics=None):
+ """MjSpec of the scene: the unchanged Menagerie arm (base at the origin on the table top), the table, the cube."""
+ path, _ = vendor_model(cfg)
+ spec = mujoco.MjSpec.from_file(str(path))
+ ph = {**cfg["physics"], **(physics or {})}
+ o = spec.option
+ o.timestep = ph["timestep_s"]
+ o.integrator = getattr(mujoco.mjtIntegrator, "mjINT_" + ph["integrator"].upper())
+ o.cone = getattr(mujoco.mjtCone, "mjCONE_" + ph["cone"].upper())
+ o.solver = getattr(mujoco.mjtSolver, "mjSOL_" + ph["solver"].upper())
+ o.impratio, o.iterations, o.ls_iterations = ph["impratio"], ph["iterations"], ph["ls_iterations"]
+ o.tolerance, o.noslip_iterations = ph["tolerance"], ph["noslip_iterations"]
+ count = {}
+ for g in spec.geoms: # names for the unnamed collision geoms (pair metadata and reports); physics unchanged
+ if not g.name and (g.contype or g.conaffinity):
+ body = g.parent.name
+ g.name = f"{body}_collision{count.get(body, 0)}"
+ count[body] = count.get(body, 0) + 1
+ base = spec.body("base") # the Menagerie base is visual only: its meshes collide as convex hulls (mass 0)
+ for k, g in enumerate([g for g in spec.geoms if g.parent.name == "base" and g.type == mujoco.mjtGeom.mjGEOM_MESH]):
+ base.add_geom(name=f"base_hull{k}", type=g.type, meshname=g.meshname, pos=g.pos, quat=g.quat, group=3,
+ contype=1, conaffinity=1, condim=3, mass=0, rgba=[1, 0, 0, 1])
+ t, c = cfg["table"], cfg["cube"]
+ box = mujoco.mjtGeom.mjGEOM_BOX
+ hx, hy = 0.5 * np.asarray(t["size_xy_m"])
+ tab = spec.worldbody.add_geom(name="table", type=box, size=[hx, hy, 0.5 * t["thickness_m"]],
+ pos=[*t["center_xy_m"], -0.5 * t["thickness_m"]], rgba=[0.55, 0.5, 0.45, 1])
+ half = 0.5 * c["size_m"]
+ body = spec.worldbody.add_body(name="cube", pos=[*c["park_xy_m"], half])
+ body.add_freejoint(name="cube")
+ cube = body.add_geom(name="cube", type=box, size=[half] * 3, mass=c["mass_kg"], rgba=[0.15, 0.35, 0.85, 1])
+ for geom, p in ((tab, t), (cube, c)):
+ geom.friction, geom.condim, geom.solref, geom.solimp = p["friction"], p["condim"], p["solref"], p["solimp"]
+ spec.add_exclude(bodyname1="world", bodyname2="base")
+ # the base is welded to the world, so MuJoCo's parent-child filter skips it: the shoulder turns inside its hulls
+ spec.add_exclude(bodyname1="base", bodyname2="shoulder")
+ spec.worldbody.add_light(pos=[0.3, -0.3, 1.2], dir=[-0.2, 0.2, -1], type=mujoco.mjtLightType.mjLIGHT_DIRECTIONAL)
+ return spec
+
+
+def topdown(yaw):
+ """Gripper orientation for a top-down grasp: gripper z up (fingertips down), closing axis x at the yaw."""
+ c, s = math.cos(yaw), math.sin(yaw)
+ return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])
+
+
+def mat_quat(r):
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.ascontiguousarray(r, dtype=np.float64).ravel())
+ return q
+
+
+def quat_mat(q):
+ r = np.zeros(9)
+ mujoco.mju_quat2Mat(r, np.asarray(q, np.float64))
+ return r.reshape(3, 3)
+
+
+def rotvec(r):
+ """Rotation vector of a rotation matrix."""
+ q = mat_quat(r)
+ v = np.zeros(3)
+ mujoco.mju_quat2Vel(v, q if q[0] >= 0 else -q, 1.0)
+ return v
+
+
+def slerp(r0, r1, a):
+ q0, q1 = mat_quat(r0), mat_quat(r1)
+ if np.dot(q0, q1) < 0:
+ q1 = -q1
+ dot = min(1.0, float(np.dot(q0, q1)))
+ if dot > 0.9995:
+ q = q0 + a * (q1 - q0)
+ else:
+ th = math.acos(dot)
+ q = (math.sin((1 - a) * th) * q0 + math.sin(a * th) * q1) / math.sin(th)
+ return quat_mat(q / np.linalg.norm(q))
+
+
+def minjerk(n):
+ s = np.linspace(0.0, 1.0, n + 1)[1:]
+ return 10 * s ** 3 - 15 * s ** 4 + 6 * s ** 5
+
+
+def wrap(a):
+ return (a + math.pi) % (2 * math.pi) - math.pi
+
+
+def random_quat(rng):
+ q = rng.normal(size=4)
+ q /= np.linalg.norm(q)
+ return q if q[0] >= 0 else -q
+
+
+def geom_points(m, g):
+ """Local points whose convex hull (plus the radius) bounds a collision geom: (points [k, 3], radius)."""
+ t, size = int(m.geom_type[g]), m.geom_size[g]
+ if t == mujoco.mjtGeom.mjGEOM_BOX:
+ return np.array([[a, b, c] for a in (-1, 1) for b in (-1, 1) for c in (-1, 1)]) * size, 0.0
+ if t == mujoco.mjtGeom.mjGEOM_SPHERE:
+ return np.zeros((1, 3)), float(size[0])
+ if t in (mujoco.mjtGeom.mjGEOM_CAPSULE, mujoco.mjtGeom.mjGEOM_CYLINDER):
+ return np.array([[0, 0, -size[1]], [0, 0, size[1]]]), float(size[0])
+ if t == mujoco.mjtGeom.mjGEOM_MESH:
+ k = m.geom_dataid[g]
+ return m.mesh_vert[m.mesh_vertadr[k]: m.mesh_vertadr[k] + m.mesh_vertnum[k]].astype(float), 0.0
+ raise ValueError(f"geom type {t}")
+
+
+# ---- overlap of the cube with the visual meshes -----------------------------------------------------------------
+def mesh_triangles(m, g):
+ """Triangles [k, 3, 3] of a mesh geom in the frame of its body."""
+ k = m.geom_dataid[g]
+ v = m.mesh_vert[m.mesh_vertadr[k]: m.mesh_vertadr[k] + m.mesh_vertnum[k]].astype(float)
+ f = m.mesh_face[m.mesh_faceadr[k]: m.mesh_faceadr[k] + m.mesh_facenum[k]]
+ return (v @ quat_mat(m.geom_quat[g]).T + m.geom_pos[g])[f]
+
+
+def parity_inside(tris, lo, h, shape, axis):
+ """Cells of a grid (centres lo + h (i + 0.5)) inside a closed triangle mesh: odd number of mesh crossings of the
+ grid line along ``axis`` before the cell centre."""
+ a, b = [x for x in range(3) if x != axis]
+ p, x = tris[:, :, [a, b]], tris[:, :, axis]
+ first = np.maximum(np.ceil((p.min(1) - lo[[a, b]]) / h - 0.5).astype(int), 0)
+ last = np.minimum(np.floor((p.max(1) - lo[[a, b]]) / h - 0.5).astype(int), np.array([shape[a], shape[b]]) - 1)
+ n = np.maximum(last - first + 1, 0)
+ count = n[:, 0] * n[:, 1]
+ tri = np.repeat(np.arange(len(tris)), count) # every (triangle, grid line) pair of the triangle's bounding box
+ off = np.arange(count.sum()) - np.repeat(np.cumsum(count) - count, count)
+ j, k = first[tri, 0] + off // n[tri, 1], first[tri, 1] + off % n[tri, 1]
+ ya, yb = lo[a] + h * (j + 0.5), lo[b] + h * (k + 0.5)
+ p0, p1, p2 = p[tri, 0], p[tri, 1], p[tri, 2]
+ det = (p1[:, 0] - p0[:, 0]) * (p2[:, 1] - p0[:, 1]) - (p2[:, 0] - p0[:, 0]) * (p1[:, 1] - p0[:, 1])
+ ok = np.abs(det) > 1e-18
+ det = np.where(ok, det, 1.0)
+ w1 = ((ya - p0[:, 0]) * (p2[:, 1] - p0[:, 1]) - (p2[:, 0] - p0[:, 0]) * (yb - p0[:, 1])) / det
+ w2 = ((p1[:, 0] - p0[:, 0]) * (yb - p0[:, 1]) - (ya - p0[:, 0]) * (p1[:, 1] - p0[:, 1])) / det
+ ok &= (w1 >= 0) & (w2 >= 0) & (w1 + w2 <= 1)
+ cross = (1 - w1 - w2) * x[tri, 0] + w1 * x[tri, 1] + w2 * x[tri, 2]
+ i = np.maximum(np.ceil((cross - lo[axis]) / h - 0.5).astype(int), 0) # first cell centre after the crossing
+ ok &= i < shape[axis]
+ toggles = np.zeros(shape, np.int32)
+ index = [None] * 3
+ index[axis], index[a], index[b] = i[ok], j[ok], k[ok]
+ np.add.at(toggles, tuple(index), 1)
+ return np.cumsum(toggles, axis=axis) % 2 == 1
+
+
+def surface_points(tris, spacing):
+ """Vertices of the triangles plus points spread over the triangles larger than ``spacing``."""
+ pts = [tris.reshape(-1, 3)]
+ n = np.ceil(np.linalg.norm(tris[:, [1, 2, 0]] - tris, axis=-1).max(1) / spacing).astype(int)
+ for k in np.unique(n[n > 1]):
+ i, j = np.meshgrid(np.arange(k + 1), np.arange(k + 1), indexing="ij")
+ keep = i + j <= k
+ a, b = i[keep] / k, j[keep] / k
+ pts.append(np.einsum("sk,tkd->tsd", np.stack((1 - a - b, a, b), 1), tris[n == k]).reshape(-1, 3))
+ return np.concatenate(pts)
+
+
+def box_surface(half, n):
+ """Points on the surface of a cube (an n x n grid on each face, corners and edges included), cube frame."""
+ s = np.linspace(-half, half, n)
+ u, v = (x.ravel() for x in np.meshgrid(s, s, indexing="ij"))
+ out = []
+ for axis in range(3):
+ for sign in (-1.0, 1.0):
+ p = np.zeros((len(u), 3))
+ p[:, axis] = sign * half
+ p[:, [x for x in range(3) if x != axis]] = np.stack((u, v), 1)
+ out.append(p)
+ return np.unique(np.round(np.concatenate(out), 9), axis=0)
+
+
+class VisualOverlap:
+ """Overlap of the cube with the visual meshes of one arm body (the gripper or the moving jaw; the parts the real
+ cube cannot enter), measured two ways in the body frame: (a) mesh surface points (the vertices and points 2 mm
+ apart on large triangles, one per 0.5 mm cell) below the cube surface, (b) points on the cube surface below the
+ mesh surface (a signed distance grid of the solid meshes, 0.5 mm cells, inside by majority of the crossing
+ parities along x, y and z; ``parity_disagreements`` counts the cells where the three differ: 0 for closed
+ meshes). The depth of an overlap is the larger of the two."""
+
+ def __init__(self, m, body, h=0.0005, spacing=0.002, cell=0.008):
+ from scipy import ndimage
+ self.map = ndimage.map_coordinates
+ geoms = [g for g in np.flatnonzero(m.geom_bodyid == body) if m.geom_type[g] == mujoco.mjtGeom.mjGEOM_MESH
+ and not (m.geom_contype[g] or m.geom_conaffinity[g])]
+ tris = np.concatenate([mesh_triangles(m, g) for g in geoms])
+ v = tris.reshape(-1, 3)
+ self.lo, self.hi, self.h = v.min(0) - 2 * h, v.max(0) + 2 * h, h
+ shape = tuple(np.ceil((self.hi - self.lo) / h).astype(int))
+ votes = sum(parity_inside(tris, self.lo, h, shape, a).astype(np.int8) for a in range(3))
+ inside = votes >= 2
+ self.parity_disagreements = int(((votes == 1) | (votes == 2)).sum())
+ self.sdf = np.where(inside, ndimage.distance_transform_edt(inside) * h - h / 2,
+ h / 2 - ndimage.distance_transform_edt(~inside) * h).astype(np.float32)
+ pts = surface_points(tris, spacing)
+ _, keep = np.unique(np.floor((pts - self.lo) / h).astype(np.int64), axis=0, return_index=True)
+ pts = pts[np.sort(keep)]
+ key = np.floor((pts - self.lo) / cell).astype(np.int64)
+ self.cell, self.ncell = cell, key.max(0) + 1
+ flat = np.ravel_multi_index(key.T, self.ncell)
+ order = np.argsort(flat, kind="stable")
+ self.points = pts[order]
+ self.start = np.searchsorted(flat[order], np.arange(np.prod(self.ncell) + 1))
+ self.meshes = [m.mesh(m.geom_dataid[g]).name for g in geoms]
+
+ def depth(self, rb, pb, rc, c, half, samples):
+ """Overlap depth (m) of a cube (centre c, rotation rc, half size) with the meshes of the body at (pb, rb)."""
+ r_bc, cb = rb.T @ rc, (c - pb) @ rb # cube rotation and centre in the body frame
+ ext = half * np.abs(r_bc).sum(1) # half extents of the cube's bounding box in the body frame
+ if ((cb + ext) < self.lo).any() or ((cb - ext) > self.hi).any():
+ return 0.0
+ first = np.maximum(np.floor((cb - ext - self.lo) / self.cell).astype(int), 0)
+ last = np.minimum(np.floor((cb + ext - self.lo) / self.cell).astype(int), self.ncell - 1)
+ out = 0.0
+ if (first <= last).all():
+ parts = []
+ for i in range(first[0], last[0] + 1):
+ for j in range(first[1], last[1] + 1):
+ a = np.ravel_multi_index((i, j, first[2]), self.ncell)
+ parts.append(self.points[self.start[a]: self.start[a + last[2] - first[2] + 1]])
+ p = np.concatenate(parts)
+ if len(p):
+ out = float((half - np.abs((p - cb) @ r_bc)).min(1).max())
+ u = ((samples @ r_bc.T + cb) - self.lo) / self.h - 0.5
+ return max(out, float(self.map(self.sdf, u.T, order=1, mode="nearest").max()), 0.0)
+
+
+class Scene:
+ """One simulation (MjData ``d``) and one kinematics workspace (``dk``, for IK and planning)."""
+
+ def __init__(self, cfg, physics=None):
+ self.cfg = cfg
+ self.spec = build_spec(cfg, physics)
+ self.m = m = self.spec.compile()
+ self.d, self.dk = mujoco.MjData(m), mujoco.MjData(m)
+ self.qadr = np.array([m.jnt_qposadr[m.joint(j).id] for j in JOINTS])
+ self.vadr = np.array([m.jnt_dofadr[m.joint(j).id] for j in JOINTS])
+ self.act = np.array([m.actuator(j).id for j in JOINTS])
+ self.lo, self.hi = m.actuator_ctrlrange[self.act].T
+ self.jlo, self.jhi = m.jnt_range[[m.joint(j).id for j in JOINTS]].T
+ # scripted targets stay this far inside the joint limits (a servo that overshoots a target at the limit
+ # runs into the soft joint-limit constraint)
+ margin = float(cfg["joint_target_margin_rad"])
+ self.tlo, self.thi = np.maximum(self.jlo + margin, self.lo), np.minimum(self.jhi - margin, self.hi)
+ self.cq = m.jnt_qposadr[m.joint("cube").id]
+ self.cv = m.jnt_dofadr[m.joint("cube").id]
+ self.cube_body, self.gripper = m.body("cube").id, m.body("gripper").id
+ self.jaw_body = m.body("moving_jaw_so101_v1").id
+ self.half = 0.5 * cfg["cube"]["size_m"]
+ self.grasp_point = np.asarray(cfg["grasp_point_m"], float)
+ if m.opt.cone != mujoco.mjtCone.mjCONE_ELLIPTIC:
+ raise ValueError("the contact labels read the normal force of elliptic cones")
+ dt = m.opt.timestep
+ self.nsub = round(cfg["record_step_s"] / dt)
+ if abs(self.nsub * dt - cfg["record_step_s"]) > 1e-9:
+ raise ValueError("the physics step must divide the record step")
+ self.per_ctrl = round(cfg["control_step_s"] / cfg["record_step_s"])
+ self.thr = float(cfg["contact_threshold_n"])
+ cls = np.zeros(m.ngeom, np.int64)
+ for g in range(m.ngeom):
+ if not (m.geom_contype[g] or m.geom_conaffinity[g]):
+ continue
+ b = m.geom_bodyid[g]
+ cls[g] = {self.gripper: FIXED, self.jaw_body: MOVING, self.cube_body: CUBE, 0: TABLE,
+ m.body("base").id: BASE}.get(b, LINK)
+ self.cls = cls
+ self.palm = np.zeros(m.ngeom, bool) # palm, servo and hinge blocks of the jaws (inside pairs 0 and 1)
+ self.palm[[m.geom(g).id for g in cfg["palm_geoms"]]] = True
+ # contact class of two geom classes: 0-2 the pairs, 3 arm-table, 4 cube-other link, 5 arm self, 6 cube-base,
+ # -1 none (base-table and base-shoulder are excluded)
+ kind = np.full((7, 7), -1, np.int64)
+ for a in (FIXED, MOVING, LINK, BASE):
+ kind[a, TABLE] = kind[TABLE, a] = 3
+ for b in (FIXED, MOVING, LINK, BASE):
+ kind[a, b] = 5
+ kind[LINK, CUBE] = kind[CUBE, LINK] = 4
+ kind[BASE, CUBE] = kind[CUBE, BASE] = 6
+ kind[FIXED, CUBE] = kind[CUBE, FIXED] = 0
+ kind[MOVING, CUBE] = kind[CUBE, MOVING] = 1
+ kind[CUBE, TABLE] = kind[TABLE, CUBE] = 2
+ self.kind = kind
+ t = cfg["table"]
+ self.table_lo = np.asarray(t["center_xy_m"]) - 0.5 * np.asarray(t["size_xy_m"]) + t["edge_margin_m"]
+ self.table_hi = np.asarray(t["center_xy_m"]) + 0.5 * np.asarray(t["size_xy_m"]) - t["edge_margin_m"]
+ self.park = np.array([*cfg["cube"]["park_xy_m"], self.half])
+ # the shoulder turns about the vertical pan axis only: its boxes stay 24 mm above the table
+ self.arm_geoms = np.flatnonzero(np.isin(cls, (FIXED, MOVING, LINK)) & (m.geom_bodyid != m.body("shoulder").id))
+ self.points = [geom_points(m, g) for g in self.arm_geoms]
+ th = cfg["throw_region"]
+ self.throw_lo, self.throw_hi = np.array([th["x_m"][0], th["y_m"][0]]), np.array([th["x_m"][1], th["y_m"][1]])
+ ov = cfg["visual_overlap"]
+ self.overlap_thr = float(ov["threshold_m"])
+ self.overlap_bodies = (self.gripper, self.jaw_body)
+ self.cube_points = box_surface(self.half, int(ov["cube_points_per_edge"]))
+ self._overlap = None
+
+ @property
+ def overlap(self):
+ """{body: VisualOverlap} of the gripper and the moving jaw (built on first use, about 1.5 s)."""
+ if self._overlap is None:
+ ov = self.cfg["visual_overlap"]
+ self._overlap = {b: VisualOverlap(self.m, b, ov["grid_m"], ov["point_spacing_m"])
+ for b in self.overlap_bodies}
+ return self._overlap
+
+ def visual_overlap(self, d):
+ """Overlap (m) of the cube with the visual meshes of the gripper and of the moving jaw beyond the deepest
+ penetration of that body's collision geoms into the cube (MuJoCo contacts), the larger of the two. ``d`` holds
+ the kinematics and the contacts of one state (after mj_step: of the state at the start of that step)."""
+ c, rc = d.xpos[self.cube_body], d.xmat[self.cube_body].reshape(3, 3)
+ n = d.ncon
+ g1, g2, dist = d.contact.geom1[:n], d.contact.geom2[:n], d.contact.dist[:n]
+ out = 0.0
+ for b, cls in zip(self.overlap_bodies, (FIXED, MOVING)):
+ depth = self.overlap[b].depth(d.xmat[b].reshape(3, 3), d.xpos[b], rc, c, self.half, self.cube_points)
+ if depth <= out:
+ continue
+ k =((self.cls[g1] == cls) & (self.cls[g2] == CUBE)) | ((self.cls[g2] == cls) & (self.cls[g1] == CUBE))
+ out = max(out, depth - max(0.0, float(-dist[k].min())) if k.any() else depth)
+ return out
+
+ def overlap_at(self, qpos):
+ """visual_overlap of a full qpos (kinematics and collision in the planning workspace)."""
+ dk = self.dk
+ dk.qpos[:] = qpos
+ mujoco.mj_kinematics(self.m, dk)
+ mujoco.mj_collision(self.m, dk)
+ return self.visual_overlap(dk)
+
+ # ---- contacts and state ------------------------------------------------------------------------------
+ def contact_forces(self, d=None):
+ """Contacts of the last physics step (MuJoCo computes them from the state at the start of the step) ->
+ summed normal force [9] by class (the 3 pairs, arm-table, cube-link, self, cube-base, then the palm blocks
+ of pairs 0 and 1) and the deepest penetration [3] of the 3 pairs (m)."""
+ d = self.d if d is None else d
+ n = d.ncon
+ out, depth = np.zeros(9), np.zeros(3)
+ if not n:
+ return out, depth
+ c = d.contact
+ a = c.efc_address[:n]
+ f = np.where(a >= 0, d.efc_force[np.maximum(a, 0)], 0.0)
+ g1, g2 = c.geom1[:n], c.geom2[:n]
+ k = self.kind[self.cls[g1], self.cls[g2]]
+ ok = k >= 0
+ out[:7] = np.bincount(k[ok], weights=f[ok], minlength=7)
+ palm = ok & (k <= 1) & (self.palm[g1] | self.palm[g2])
+ out[7:] = np.bincount(k[palm], weights=f[palm], minlength=2)
+ pair = ok & (k <= 2) & (f > 0)
+ np.maximum.at(depth, k[pair], -c.dist[:n][pair])
+ return out, depth
+
+ def state(self):
+ """(arm [12], cube [13]) of the simulation; the cube angular velocity rotated to the world frame."""
+ d, cq, cv = self.d, self.cq, self.cv
+ q = d.qpos[cq + 3: cq + 7]
+ w = quat_mat(q) @ d.qvel[cv + 3: cv + 6]
+ arm = np.concatenate((d.qpos[self.qadr], d.qvel[self.vadr]))
+ return arm, np.concatenate((d.qpos[cq: cq + 3], q, d.qvel[cv: cv + 3], w))
+
+ def cube_in_gripper(self):
+ """Cube centre in the grasp frame (gripper frame, origin at the grasp point) of the simulation state."""
+ dk = self.dk
+ dk.qpos[:] = self.d.qpos
+ mujoco.mj_kinematics(self.m, dk)
+ r = dk.xmat[self.gripper].reshape(3, 3)
+ return r.T @ (dk.xpos[self.cube_body] - dk.xpos[self.gripper]) - self.grasp_point
+
+ def reset(self, q_arm, cube_pos, cube_quat, cube_vel=None, cube_omega=None, spawn=False):
+ """Arm at q_arm (targets = q_arm) and the cube resting at its start (or parked, for a spawn) for the
+ warm-up; a spawned cube is then placed with its world velocity and angular velocity. Time starts at 0."""
+ m, d, cq, cv = self.m, self.d, self.cq, self.cv
+ mujoco.mj_resetData(m, d)
+ d.qpos[self.qadr] = q_arm
+ d.ctrl[self.act] = np.clip(q_arm, self.tlo, self.thi).astype(np.float32)
+ d.qpos[cq: cq + 3] = self.park if spawn else cube_pos
+ d.qpos[cq + 3: cq + 7] = [1, 0, 0, 0] if spawn else cube_quat
+ for _ in range(round(self.cfg["warmup_s"] / m.opt.timestep)):
+ mujoco.mj_step(m, d)
+ if spawn:
+ d.qpos[cq: cq + 3], d.qpos[cq + 3: cq + 7] = cube_pos, cube_quat
+ d.qvel[cv: cv + 3] = cube_vel
+ d.qvel[cv + 3: cv + 6] = quat_mat(cube_quat).T @ np.asarray(cube_omega, float)
+ d.time = 0.0
+ mujoco.mj_forward(m, d)
+
+ # ---- kinematics -----------------------------------------------------------------------------------------
+ def fk(self, q, cube=None):
+ dk = self.dk
+ dk.qpos[self.qadr] = q
+ dk.qpos[self.cq: self.cq + 3] = self.park if cube is None else cube
+ dk.qpos[self.cq + 3: self.cq + 7] = [1, 0, 0, 0]
+ mujoco.mj_kinematics(self.m, dk)
+ mujoco.mj_comPos(self.m, dk)
+ return dk
+
+ def grasp_pose(self, q):
+ dk = self.fk(q)
+ r = dk.xmat[self.gripper].reshape(3, 3).copy()
+ return dk.xpos[self.gripper] + r @ self.grasp_point, r
+
+ def ik(self, q0, pos, rot=None, body=None, point=None, w_rot=0.1, iters=150):
+ """Damped least squares (mj_jac) on the 5 arm joints; the jaw stays at q0[5]. Target: the world position of
+ ``point`` (body frame of ``body``; default the grasp point of the gripper) and the gripper orientation
+ ``rot``; the rotation weight w_rot (m/rad) trades orientation against position.
+ -> (q, position error m, angle error rad)."""
+ m = self.m
+ body = self.gripper if body is None else body
+ point = self.grasp_point if point is None else np.asarray(point, float)
+ q = np.array(q0, float)
+ jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv))
+ cols = self.vadr[:5]
+ lo, hi = self.tlo[:5], self.thi[:5]
+
+ def error():
+ dk = self.fk(q)
+ r = dk.xmat[self.gripper].reshape(3, 3)
+ rb = dk.xmat[body].reshape(3, 3)
+ p = dk.xpos[body] + rb @ point
+ er = rotvec(rot @ r.T) if rot is not None else np.zeros(3)
+ return pos - p, er, p
+
+ last = np.inf
+ for it in range(iters):
+ ep, er, p = error()
+ err = np.linalg.norm(ep) + w_rot * np.linalg.norm(er)
+ if np.linalg.norm(ep) < 1e-6 and np.linalg.norm(er) < 1e-5:
+ break
+ if it % 10 == 0: # stop when 10 iterations gain less than 10 %
+ if err > 0.9 * last:
+ break
+ last = err
+ mujoco.mj_jac(m, self.dk, jp, jr, p, body)
+ jac = np.vstack((jp[:, cols], w_rot * jr[:, cols]))
+ dq = jac.T @ np.linalg.solve(jac @ jac.T + 1e-4 * np.eye(6), np.concatenate((ep, w_rot * er)))
+ q[:5] = np.clip(q[:5] + dq, lo, hi)
+ ep, er, _ = error()
+ return q, float(np.linalg.norm(ep)), float(np.linalg.norm(er))
+
+ def pose_ik(self, q0, pos, rot, max_tilt=None):
+ """The gripper at (pos, rot) within the IK tolerances; if that is out of reach and max_tilt (rad) is given,
+ the position exactly and the orientation within max_tilt (the wrist-flex limit allows a vertical gripper
+ only up to a grasp-point height of about 7 cm). -> (q, angle error) or None."""
+ tol_p, tol_a = self.cfg["ik"]["position_tol_m"], math.radians(self.cfg["ik"]["angle_tol_deg"])
+ q, ep, ea = self.ik(q0, pos, rot=rot)
+ if ep < tol_p and ea < tol_a:
+ return q, ea
+ if max_tilt is not None:
+ q, ep, ea = self.ik(q, pos, rot=rot, w_rot=0.001, iters=600)
+ if ep < tol_p and ea < max_tilt:
+ return q, ea
+ return None
+
+ def solve(self, pos, rot, jaw, hint=None, max_tilt=None):
+ """IK with a few starting guesses; raises PlanError if the pose is out of reach."""
+ px, py = self.cfg["workspace"]["pan_axis_xy_m"]
+ pan = math.atan2(pos[1] - py, pos[0] - px)
+ yaw = math.atan2(rot[1, 0], rot[0, 0])
+ guesses = [] if hint is None else [np.array(hint, float)]
+ guesses += [np.array([pan, lift, 0.6, 1.1, wrap(yaw - pan), jaw]) for lift in (0.0, -0.6, 0.6)]
+ for tilt in ((None,) if max_tilt is None else (None, max_tilt)):
+ for g in guesses:
+ g[5] = jaw
+ out = self.pose_ik(g, pos, rot, tilt)
+ if out is not None:
+ return out[0]
+ raise PlanError("pose out of reach")
+
+ def lowest(self, dk, which=None):
+ """Lowest world z of the arm collision geoms (or of the geoms of one body) in a kinematics workspace."""
+ low = np.inf
+ for g, (pts, rad) in zip(self.arm_geoms, self.points):
+ if which is None or self.m.geom_bodyid[g] == which:
+ low = min(low, float((pts @ dk.geom_xmat[g].reshape(3, 3).T)[:, 2].min() + dk.geom_xpos[g, 2] - rad))
+ return low
+
+ def clearance(self, q, cube=None):
+ """Lowest point of the arm collision geoms above the table and arm self-contact at q."""
+ dk = self.fk(q, cube)
+ mujoco.mj_collision(self.m, dk)
+ n = dk.ncon
+ k = self.kind[self.cls[dk.contact.geom1[:n]], self.cls[dk.contact.geom2[:n]]] if n else np.zeros(0, int)
+ return self.lowest(dk), bool((k == 5).any())
+
+ def cube_touches(self, q, pos, quat):
+ """True if a cube placed at (pos, quat) would touch the arm or the table at q, or overlap the visual meshes of
+ the gripper or the moving jaw."""
+ dk = self.fk(q, pos)
+ dk.qpos[self.cq + 3: self.cq + 7] = quat
+ mujoco.mj_kinematics(self.m, dk)
+ mujoco.mj_collision(self.m, dk)
+ n = dk.ncon
+ if n and ((self.cls[dk.contact.geom1[:n]] == CUBE) | (self.cls[dk.contact.geom2[:n]] == CUBE)).any():
+ return True
+ return self.visual_overlap(dk) > 0
+
+ def jaw_profile(self, theta, band=0.03):
+ """Grasp-frame geometry of both jaws at a jaw angle (gripper top-down): for each jaw the (x, z) of its
+ lowest collision point and the x range of its collision points within ``band`` above the lowest point of
+ the gripper (the height of a cube on the table under the fingertips)."""
+ q = np.zeros(6)
+ q[5] = theta
+ dk = self.fk(q)
+ r, x0 = dk.xmat[self.gripper].reshape(3, 3), dk.xpos[self.gripper]
+ pts = {}
+ for g, (p, rad) in zip(self.arm_geoms, self.points):
+ b = self.m.geom_bodyid[g]
+ if b in (self.gripper, self.jaw_body):
+ local = ((p @ dk.geom_xmat[g].reshape(3, 3).T + dk.geom_xpos[g]) - x0) @ r - self.grasp_point
+ local[:, 2] -= rad
+ pts.setdefault("fixed" if b == self.gripper else "moving", []).append(local)
+ pts = {k: np.concatenate(v) for k, v in pts.items()}
+ z0 = min(v[:, 2].min() for v in pts.values())
+ out = {}
+ for k, v in pts.items():
+ low = v[np.argmin(v[:, 2])]
+ inband = v[v[:, 2] < z0 + band]
+ out[k] = dict(x_low=float(low[0]), z_low=float(low[2]), x_min=float(inband[:, 0].min()),
+ x_max=float(inband[:, 0].max()))
+ out["z_low"] = float(z0)
+ return out
+
+ # ---- sampling ----------------------------------------------------------------------------------------
+ def sample_cube(self, rng):
+ ws = self.cfg["workspace"]
+ r, a = rng.uniform(*ws["r_m"]), math.radians(rng.uniform(*ws["angle_deg"]))
+ px, py = ws["pan_axis_xy_m"]
+ return np.array([px + r * math.cos(a), py + r * math.sin(a), self.half]), rng.uniform(0, math.pi / 2)
+
+ def grasp_yaw(self, pos, cube_yaw, rng):
+ """A closing axis along a cube face normal, near the radial direction (wrist roll near 0) or a quarter turn
+ or a half turn from it (other wrist rolls)."""
+ px, py = self.cfg["workspace"]["pan_axis_xy_m"]
+ a = math.atan2(pos[1] - py, pos[0] - px)
+ base = cube_yaw + round((a - cube_yaw) / (math.pi / 2)) * math.pi / 2
+ yaws = [wrap(base + j * math.pi / 2) for j in (-1, 0, 1, 2)]
+ p = np.array([0.2, 0.4, 0.2, 0.2]) * [abs(wrap(y - a)) < 2.5 for y in yaws] # wrist roll within range
+ return yaws[rng.choice(4, p=p / p.sum())]
+
+ def sample_above(self, rng, z=(0.08, 0.2), r=(0.12, 0.27), angle=(-80, 80), jaw=(0.0, 1.2)):
+ """A collision-free top-down pose above the table (start poses, free moves)."""
+ px, py = self.cfg["workspace"]["pan_axis_xy_m"]
+ for _ in range(50):
+ rr, a = rng.uniform(*r), math.radians(rng.uniform(*angle))
+ pos = np.array([px + rr * math.cos(a), py + rr * math.sin(a), rng.uniform(*z)])
+ try:
+ q = self.solve(pos, topdown(a + rng.uniform(-1.2, 1.2)), rng.uniform(*jaw), max_tilt=math.radians(60))
+ except PlanError:
+ continue
+ low, self_hit = self.clearance(q)
+ if low > 0.02 and not self_hit:
+ return q
+ raise PlanError("no start pose")
+
+ def sample_free(self, rng, shrink=0.85, low_m=0.03):
+ """A random joint configuration (ranges shrunk about their centre) clear of the table and of self-contact."""
+ mid, span = 0.5 * (self.jlo + self.jhi), 0.5 * (self.jhi - self.jlo) * shrink
+ for _ in range(200):
+ q = mid + span * rng.uniform(-1, 1, 6)
+ low, self_hit = self.clearance(q)
+ if low > low_m and not self_hit:
+ return q
+ raise PlanError("no free pose")
+
+ def path_clear(self, q0, q1, low_m=0.015, n=8):
+ for a in np.linspace(0, 1, n + 1)[1:]:
+ low, self_hit = self.clearance(q0 + (q1 - q0) * a)
+ if low < low_m or self_hit:
+ return False
+ return True
+
+
+# ---- scripted plans ---------------------------------------------------------------------------------------
+class Plan:
+ """Joint targets on the 20 ms control grid, with a phase per control step."""
+
+ def __init__(self, scene, q, rng):
+ self.s, self.rng = scene, rng
+ self.q = np.array(q, float)
+ self.rows, self.phases = [], []
+ self.dt = scene.cfg["control_step_s"]
+ sp = scene.cfg["speed_rad_s"]
+ self.arm_max, self.jaw_speed = sp["arm_max"], sp["jaw"]
+
+ def steps(self, seconds):
+ return max(1, int(round(seconds / self.dt)))
+
+ def __len__(self):
+ return len(self.phases)
+
+ def add(self, qs, phase):
+ qs = np.asarray(qs, float)
+ self.rows.append(qs)
+ self.phases += [P[phase]] * len(qs)
+ self.q = qs[-1].copy()
+
+ def hold(self, seconds, phase):
+ if seconds > 0.5 * self.dt:
+ self.add(np.repeat(self.q[None], self.steps(seconds), 0), phase)
+
+ def joint(self, q1, phase, speed=None, tmin=0.2):
+ """Minimum-jerk joint-space move; the duration keeps the peak arm joint speed at ``speed`` (rad/s)."""
+ q1 = np.array(q1, float)
+ speed = self.rng.uniform(*self.s.cfg["speed_rad_s"]["arm"]) if speed is None else speed
+ dq = np.abs(q1 - self.q)
+ t = max(tmin, 1.875 * dq[:5].max() / speed, 1.875 * dq[5] / self.jaw_speed)
+ s = minjerk(self.steps(t))
+ self.add(self.q + (q1 - self.q) * s[:, None], phase)
+
+ def jaw(self, theta, phase, seconds):
+ q1 = self.q.copy()
+ q1[5] = theta
+ s = minjerk(self.steps(max(seconds, 1.875 * abs(theta - self.q[5]) / self.jaw_speed)))
+ self.add(self.q + (q1 - self.q) * s[:, None], phase)
+
+ def cart(self, pos, rot, phase, seconds, max_tilt=math.radians(45)):
+ """Straight line of the grasp point (orientation by slerp; tilted up to max_tilt where the wrist cannot keep
+ it), minimum-jerk timing, IK at every control step; slower if a joint would pass the arm speed limit."""
+ p0, r0 = self.s.grasp_pose(self.q)
+ pos = np.asarray(pos, float)
+ for _ in range(6):
+ rows, q = [], self.q.copy()
+ for a in minjerk(self.steps(seconds)):
+ out = self.s.pose_ik(q, p0 + (pos - p0) * a, slerp(r0, rot, a), max_tilt)
+ if out is None:
+ raise PlanError("path out of reach")
+ q = out[0]
+ rows.append(q.copy())
+ rows = np.array(rows)
+ speed = np.abs(np.diff(np.vstack((self.q[None], rows)), axis=0)[:, :5]).max() / self.dt
+ if speed <= self.arm_max:
+ self.add(rows, phase)
+ return
+ seconds *= 1.3
+ raise PlanError("path too fast")
+
+ def fill(self, n, rng, free=True):
+ """Free moves above the table (or holds) until n control steps."""
+ tries = 0
+ while free and n - len(self) > self.steps(0.8) and tries < 20:
+ tries += 1
+ try:
+ q1 = self.s.sample_above(rng, z=(0.06, 0.22))
+ except PlanError:
+ break
+ if not self.s.path_clear(self.q, q1):
+ continue
+ self.joint(q1, "free")
+ self.hold(rng.uniform(0, 0.3), "idle")
+ if len(self) < n:
+ self.hold((n - len(self)) * self.dt, "idle")
+
+ def targets(self, n=None):
+ rows = np.concatenate(self.rows) if self.rows else np.zeros((0, 6))
+ return rows[:n], np.asarray(self.phases[:n], np.int8)
+
+ def play(self, n=None):
+ rows, phases = self.targets(n)
+ for q, ph in zip(rows, phases):
+ yield q, ph
+
+
+def grasp_approach(plan, s, rng, target, rot, theta_open, speed=None):
+ """Approach above ``target`` (grasp point) with the jaw open, then descend in a straight line."""
+ pre = target + [0, 0, rng.uniform(0.04, 0.08)]
+ q_pre = s.solve(pre, rot, theta_open, hint=plan.q, max_tilt=math.radians(30))
+ if not s.path_clear(plan.q, q_pre, low_m=0.03):
+ raise PlanError("approach path")
+ plan.joint(q_pre, "approach", speed=speed)
+ plan.cart(target, rot, "descend", rng.uniform(0.25, 0.5))
+
+
+def carry_and_place(plan, s, rng, grasp, rot, h, theta_open, n, move_prob=0.5, lift_s=(0.4, 1.0)):
+ """From a grasp at grasp point ``grasp``: lift by h, hold, move while holding (move_prob, if its drawn durations
+ fit in the n control steps), lower, release, retreat."""
+ plan.cart(grasp + [0, 0, h], rot, "lift", rng.uniform(*lift_s))
+ move = rng.random() < move_prob
+ hold1, move_s, hold2 = rng.uniform(0.2, 0.5), rng.uniform(0.5, 0.9), rng.uniform(0.1, 0.3)
+ rest = [rng.uniform(0.35, 0.7), rng.uniform(0.15, 0.35), rng.uniform(0.25, 0.5)] # lower, release, retreat
+ rest[1] = max(rest[1], 1.875 * abs(theta_open - plan.q[5]) / plan.jaw_speed)
+ if not (move and len(plan) + plan.steps(hold1 + move_s + hold2 + sum(rest)) <= n):
+ move, hold1 = False, rng.uniform(0.3, 1.0)
+ plan.hold(hold1, "hold")
+ place, rot2 = grasp, rot
+ for _ in range(5 if move else 0): # a reachable place for the move (else no move)
+ target = s.sample_cube(rng)[0] + [0, 0, grasp[2] - s.half]
+ turn = topdown(math.atan2(rot[1, 0], rot[0, 0]) + rng.uniform(-0.6, 0.6))
+ try:
+ s.solve(target, turn, plan.q[5], hint=plan.q)
+ plan.cart(target + [0, 0, h], turn, "move", move_s)
+ except PlanError:
+ continue
+ place, rot2 = target, turn
+ plan.hold(hold2, "hold")
+ break
+ plan.cart(place + [0, 0, rng.uniform(0.0, 0.003)], rot2, "lower", rest[0])
+ plan.jaw(theta_open, "release", rest[1])
+ plan.cart(place + [0, 0, rng.uniform(0.04, 0.1)], rot2, "retreat", rest[2])
+
+
+def task_start(s, rng, spread_deg=60):
+ """A cube on the table and a start pose above the table within spread_deg of pan from it."""
+ cube, cyaw = s.sample_cube(rng)
+ px, py = s.cfg["workspace"]["pan_axis_xy_m"]
+ a = math.degrees(math.atan2(cube[1] - py, cube[0] - px))
+ q0 = s.sample_above(rng, angle=(a - spread_deg, a + spread_deg))
+ return cube, cyaw, q0, Plan(s, q0, rng)
+
+
+def resting_cube(cube, cyaw):
+ return dict(pos=cube, quat=np.array([math.cos(cyaw / 2), 0, 0, math.sin(cyaw / 2)]), spawn=False)
+
+
+def finish(plan, rng, n, q0, cube, cyaw, **meta):
+ if len(plan) > n:
+ raise PlanError("too long")
+ plan.fill(n, rng)
+ return dict(q0=q0, cube=resting_cube(cube, cyaw), script=plan.play(n), meta=meta)
+
+
+def fam_nominal(s, rng, n):
+ cube, cyaw, q0, plan = task_start(s, rng, spread_deg=40)
+ plan.hold(rng.uniform(0, 0.2), "idle")
+ rot = topdown(s.grasp_yaw(cube, cyaw, rng))
+ theta_open = rng.uniform(0.55, 0.9)
+ grasp = cube + [0, 0, rng.uniform(0, 0.002)]
+ grasp_approach(plan, s, rng, grasp, rot, theta_open, speed=rng.uniform(1.2, 2.4))
+ plan.hold(rng.uniform(0, 0.15), "descend")
+ plan.jaw(rng.uniform(s.tlo[5], 0.05), "close", rng.uniform(0.2, 0.4))
+ plan.hold(rng.uniform(0.1, 0.25), "grip")
+ carry_and_place(plan, s, rng, grasp, rot, rng.uniform(0.03, 0.12), theta_open, n, lift_s=(0.35, 0.8))
+ return finish(plan, rng, n, q0, cube, cyaw)
+
+
+def fam_off_centre(s, rng, n):
+ """The cube sits off the grasp point: along the jaw width (4-12 mm), the closing axis (+-3 mm) and lower in the
+ jaws (the gripper 0-12 mm higher)."""
+ cube, cyaw, q0, plan = task_start(s, rng)
+ rot = topdown(s.grasp_yaw(cube, cyaw, rng))
+ off = np.array([rng.uniform(-0.003, 0.003), rng.choice([-1, 1]) * rng.uniform(0.004, 0.012), 0.0])
+ grasp = cube - rot @ off + [0, 0, rng.uniform(0.0, 0.012)]
+ theta_open = rng.uniform(0.6, 0.9)
+ grasp_approach(plan, s, rng, grasp, rot, theta_open)
+ plan.jaw(rng.uniform(s.tlo[5], 0.05), "close", rng.uniform(0.2, 0.4))
+ plan.hold(rng.uniform(0.1, 0.3), "grip")
+ carry_and_place(plan, s, rng, grasp, rot, rng.uniform(0.05, 0.12), theta_open, n, move_prob=0.3,
+ lift_s=(0.3, 0.7))
+ return finish(plan, rng, n, q0, cube, cyaw, offset_m=(grasp - cube).tolist())
+
+
+def fam_one_sided(s, rng, n):
+ """One jaw touches the cube on the table: a push with the fixed jaw's outer face, a swat of the moving jaw's
+ outer face (the jaw opens into the cube) or a fingertip tap on the top face."""
+ cube, cyaw, q0, plan = task_start(s, rng)
+ rot = topdown(s.grasp_yaw(cube, cyaw, rng))
+ ex = rot[:, 0]
+ kind = str(rng.choice(["push", "swat", "tap"]))
+ if kind == "push": # the cube outside the fixed jaw; the gripper moves along -x into it
+ jp = s.jaw_profile(rng.uniform(0.0, 0.3))
+ gap = rng.uniform(0.003, 0.012)
+ start = cube - ex * (jp["fixed"]["x_min"] - s.half - gap)
+ start[2] = -jp["z_low"] + rng.uniform(0.002, 0.006)
+ grasp_approach(plan, s, rng, start, rot, rng.uniform(0.0, 0.3))
+ plan.cart(start - ex * (gap + rng.uniform(0.02, 0.06)), rot, "push", rng.uniform(0.5, 1.2))
+ elif kind == "swat": # the cube outside the nearly closed moving jaw; the jaw opens into it
+ jp = s.jaw_profile(0.1)
+ gap = rng.uniform(0.002, 0.015)
+ start = cube - ex * (jp["moving"]["x_max"] + s.half + gap)
+ start[2] = -jp["z_low"] + rng.uniform(0.002, 0.006)
+ grasp_approach(plan, s, rng, start, rot, 0.1)
+ plan.jaw(rng.uniform(0.8, 1.5), "swat", rng.uniform(0.15, 0.4))
+ else: # one jaw's fingertips pressed 0-3 mm onto the top face; the other jaw clear of the cube
+ which = "fixed" if rng.random() < 0.5 else "moving"
+ theta = rng.uniform(0.3, 0.6) if which == "fixed" else 0.4
+ tip = s.jaw_profile(theta)[which]
+ top = cube - ex * tip["x_low"] + ex * rng.uniform(-0.008, 0.008)
+ top[2] = 2 * s.half - tip["z_low"] - rng.uniform(0.0, 0.003)
+ grasp_approach(plan, s, rng, top + [0, 0, 0.004], rot, theta)
+ plan.cart(top, rot, "tap", rng.uniform(0.15, 0.4))
+ plan.hold(rng.uniform(0.1, 0.5), "tap")
+ kind = f"tap_{which}"
+ p, _ = s.grasp_pose(plan.q)
+ plan.cart(p + [0, 0, rng.uniform(0.04, 0.1)], rot, "retreat", rng.uniform(0.3, 0.6))
+ return finish(plan, rng, n, q0, cube, cyaw, kind=kind)
+
+
+def fam_near_miss(s, rng, n):
+ """The jaws close 15-30 mm beside the cube centre along the jaw width, or 22-35 mm along the closing axis."""
+ cube, cyaw, q0, plan = task_start(s, rng)
+ rot = topdown(s.grasp_yaw(cube, cyaw, rng))
+ if rng.random() < 0.7:
+ off = np.array([rng.uniform(-0.004, 0.004), rng.choice([-1, 1]) * rng.uniform(0.015, 0.03), 0.0])
+ else:
+ off = np.array([rng.choice([-1, 1]) * rng.uniform(0.022, 0.035), rng.uniform(-0.004, 0.004), 0.0])
+ grasp = cube - rot @ off + [0, 0, rng.uniform(0, 0.003)]
+ grasp_approach(plan, s, rng, grasp, rot, rng.uniform(0.6, 0.9))
+ plan.jaw(rng.uniform(s.tlo[5], 0.05), "close", rng.uniform(0.2, 0.4))
+ plan.hold(rng.uniform(0.1, 0.3), "grip")
+ h = rng.uniform(0.04, 0.10)
+ plan.cart(grasp + [0, 0, h], rot, "lift", rng.uniform(0.4, 0.8))
+ plan.hold(rng.uniform(0.2, 0.6), "hold")
+ plan.cart(grasp + [0, 0, rng.uniform(0.0, 0.003)], rot, "lower", rng.uniform(0.4, 0.8))
+ plan.jaw(rng.uniform(0.6, 0.9), "release", rng.uniform(0.15, 0.4))
+ plan.cart(grasp + [0, 0, h], rot, "retreat", rng.uniform(0.3, 0.6))
+ return finish(plan, rng, n, q0, cube, cyaw, offset_m=(grasp - cube).tolist())
+
+
+def fam_weak_closure(s, rng, n):
+ """Slow closing until both jaws carry load, then the jaw target at the measured jaw angle plus a small opening
+ (-2..+4 mrad); a fast lift, a hold, a slow opening of the jaw target (50 %, 2-20 mrad/s for 0.4-1 s: the grip
+ fades and the cube slips out) and a wrist shake (60 %) when they fit in the episode, lowering and release."""
+ cube, cyaw, q0, plan = task_start(s, rng, spread_deg=30)
+ rot = topdown(s.grasp_yaw(cube, cyaw, rng))
+ theta_open = rng.uniform(0.55, 0.8)
+ grasp = cube + [0, 0, rng.uniform(0, 0.004)]
+ grasp_approach(plan, s, rng, grasp, rot, theta_open)
+ head, q_grasp = len(plan), plan.q.copy()
+ delta, close_speed = rng.uniform(-0.002, 0.004), rng.uniform(0.3, 0.6)
+ max_close = plan.steps((theta_open - 0.1) / close_speed) # contact comes near jaw angle 0.19
+ after = Plan(s, q_grasp, rng)
+ after.hold(rng.uniform(0.1, 0.3), "grip")
+ after.cart(grasp + [0, 0, rng.uniform(0.05, 0.12)], rot, "lift", rng.uniform(0.25, 0.5))
+ after.hold(rng.uniform(0.2, 0.6), "hold")
+ spare = n - head - max_close - len(after) - plan.steps(1.6) # lowering, release and retreat
+ shake, loosen = rng.random() < 0.6, rng.random() < 0.5
+ dur, freq, amp = rng.uniform(0.5, 1.0), rng.uniform(1.5, 3.0), rng.uniform(0.1, 0.3)
+ loosen_s, loosen = rng.uniform(0.4, 1.0), rng.uniform(0.002, 0.02) if loosen else 0.0
+ if loosen and after.steps(loosen_s) > spare:
+ loosen = 0.0
+ if shake and after.steps(dur) + (after.steps(loosen_s) if loosen else 0) <= spare: # tapered wrist shake
+ t = np.arange(1, after.steps(dur) + 1) * after.dt
+ rows = np.repeat(after.q[None], len(t), 0)
+ rows[:, 3] += amp * np.sin(2 * math.pi * freq * t) * np.clip((dur - t) / 0.2, 0, 1)
+ after.add(rows, "shake")
+ if loosen:
+ after.hold(loosen_s, "loosen")
+ after.cart(grasp + [0, 0, rng.uniform(0.0, 0.003)], rot, "lower", rng.uniform(0.4, 0.8))
+ after.hold(rng.uniform(0.15, 0.3), "release")
+ after.cart(grasp + [0, 0, 0.06], rot, "retreat", 0.4)
+ rows, phases = after.targets()
+ if head + max_close + len(rows) > n:
+ raise PlanError("too long")
+ release = np.flatnonzero(phases == P["release"])
+ carry = np.isin(phases, [P[x] for x in ("grip", "lift", "hold", "shake", "lower")])
+ opening = np.cumsum(phases == P["loosen"]) * loosen * plan.dt # jaw target opening during and after loosen
+ dt = plan.dt
+
+ def script():
+ sent = 0
+ for q, ph in plan.play(head):
+ obs = yield q, ph
+ sent += 1
+ q = q_grasp.copy()
+ for _ in range(max_close): # close at close_speed until both jaws carry load
+ if obs["force"][0] > s.thr and obs["force"][1] > s.thr:
+ break
+ q[5] = max(q[5] - close_speed * dt, s.tlo[5])
+ obs = yield q.copy(), P["close"]
+ sent += 1
+ target = min(float(obs["q"][5]) + delta, theta_open)
+ jaw = np.where(carry | (phases == P["loosen"]), target + opening, theta_open)
+ start = target + opening[release[0]]
+ jaw[release] = start + (theta_open - start) * minjerk(len(release))
+ out = rows.copy()
+ out[:, 5] = jaw
+ for row, ph in zip(out, phases):
+ obs = yield row, ph
+ sent += 1
+ tail = Plan(s, out[-1], rng)
+ tail.fill(n - sent, rng)
+ yield from tail.play()
+
+ return dict(q0=q0, cube=resting_cube(cube, cyaw), script=script(),
+ meta=dict(delta_rad=float(delta), close_speed=float(close_speed), loosen_rad_s=float(loosen)))
+
+
+def fam_drop(s, rng, n):
+ """Grasp and lift 5-15 cm, then the jaw opens in 60-200 ms: the cube falls and hits the table."""
+ cube, cyaw, q0, plan = task_start(s, rng)
+ rot = topdown(s.grasp_yaw(cube, cyaw, rng))
+ grasp = cube + [0, 0, rng.uniform(0, 0.002)]
+ grasp_approach(plan, s, rng, grasp, rot, rng.uniform(0.55, 0.9))
+ plan.jaw(rng.uniform(s.tlo[5], 0.05), "close", rng.uniform(0.2, 0.45))
+ plan.hold(rng.uniform(0.1, 0.3), "grip")
+ h = rng.uniform(0.05, 0.15)
+ plan.cart(grasp + [0, 0, h], rot, "lift", rng.uniform(0.4, 0.9))
+ plan.hold(rng.uniform(0.1, 0.5), "hold")
+ if rng.random() < 0.5 and len(plan) + plan.steps(2.6) <= n:
+ plan.cart(s.sample_cube(rng)[0] + [0, 0, h], rot, "move", rng.uniform(0.5, 1.0))
+ plan.jaw(rng.uniform(0.6, 1.5), "open_drop", rng.uniform(0.06, 0.2))
+ plan.hold(rng.uniform(0.2, 0.5), "rest")
+ p, _ = s.grasp_pose(plan.q)
+ plan.cart(p + [0, 0, rng.uniform(0.03, 0.08)], rot, "retreat", rng.uniform(0.3, 0.6))
+ return finish(plan, rng, n, q0, cube, cyaw, height_m=float(h))
+
+
+def fam_push(s, rng, n):
+ """Closed jaws, fingertips 2-6 mm above the table, pushed 6-12 cm through the cube position."""
+ cube, cyaw, q0, plan = task_start(s, rng)
+ phi = rng.uniform(-math.pi, math.pi)
+ u = np.array([math.cos(phi), math.sin(phi), 0.0])
+ theta = rng.uniform(s.tlo[5], 0.15)
+ rot = topdown(rng.uniform(-math.pi, math.pi))
+ start = cube - u * rng.uniform(0.04, 0.06)
+ start[2] = -s.jaw_profile(theta)["z_low"] + rng.uniform(0.002, 0.006)
+ grasp_approach(plan, s, rng, start, rot, theta)
+ end = start + u * rng.uniform(0.06, 0.12)
+ plan.cart(end, rot, "push", rng.uniform(0.6, 1.5))
+ plan.cart(end + [0, 0, rng.uniform(0.04, 0.1)], rot, "retreat", rng.uniform(0.3, 0.6))
+ return finish(plan, rng, n, q0, cube, cyaw, direction_rad=float(phi))
+
+
+# ---- policy-like commands (campaign noisy_v1; 2026-10-11, SO101 policy study) ------------------------------------
+def fam_policy_grasp(s, rng, n, offset_m=(0.0, 0.0), move_prob=0.5):
+ """The nominal script with a policy's imprecision at the grasp: the grasp-point target off the cube centre by
+ U(offset_m) metres in a uniformly random horizontal direction (any direction relative to the jaws) and 0-2 mm
+ higher (as nominal); the move while holding is drawn with move_prob (carry-and-place: 1)."""
+ cube, cyaw, q0, plan = task_start(s, rng, spread_deg=40)
+ plan.hold(rng.uniform(0, 0.2), "idle")
+ rot = topdown(s.grasp_yaw(cube, cyaw, rng))
+ theta_open = rng.uniform(0.55, 0.9)
+ r, a = rng.uniform(*offset_m), rng.uniform(-math.pi, math.pi)
+ grasp = cube + [r * math.cos(a), r * math.sin(a), rng.uniform(0, 0.002)]
+ grasp_approach(plan, s, rng, grasp, rot, theta_open, speed=rng.uniform(1.2, 2.4))
+ plan.hold(rng.uniform(0, 0.15), "descend")
+ plan.jaw(rng.uniform(s.tlo[5], 0.05), "close", rng.uniform(0.2, 0.4))
+ plan.hold(rng.uniform(0.1, 0.25), "grip")
+ carry_and_place(plan, s, rng, grasp, rot, rng.uniform(0.03, 0.12), theta_open, n, move_prob=move_prob,
+ lift_s=(0.35, 0.8))
+ return finish(plan, rng, n, q0, cube, cyaw, offset_m=(grasp - cube).tolist())
+
+
+def ou_noise(rng, n, dims, std, tau, dt):
+ """[n, dims] independent Ornstein-Uhlenbeck sequences that start at 0: stationary std ``std``, time constant
+ ``tau`` (s), step ``dt`` (s)."""
+ a = math.exp(-dt / tau)
+ kick = rng.normal(size=(n, dims)) * std * math.sqrt(1.0 - a * a)
+ x = np.zeros((n, dims))
+ for k in range(1, n):
+ x[k] = a * x[k - 1] + kick[k]
+ return x
+
+
+def play(rows, phases):
+ """A fixed command sequence as the script generator of run_episode (observations are ignored)."""
+ for q, ph in zip(rows, phases):
+ yield q, ph
+
+
+def noisy_commands(s, rng, ep, std=(0.005, 0.02), tau=(0.1, 0.4), jaw_offset=(-0.03, 0.03), floor_m=0.003,
+ near_m=0.05):
+ """Policy-like commands from a planned open-loop episode, after planning: OU noise (ou_noise) on the 5 arm targets
+ with one stationary std (rad) and one time constant (s) per episode, drawn uniformly from ``std`` and ``tau``,
+ independent per joint; a constant jaw-target offset (rad) drawn from ``jaw_offset``. The noisy targets are clipped
+ to the target range and rate-limited like the scripted data (at most speed_rad_s.arm_max x control step on an arm
+ joint and speed_rad_s.jaw x control step on the jaw per control step, from the warm-up command q0). Table guard
+ (a policy's command decoder keeps the commanded gripper above the table): where the plan's grasp point is below
+ ``near_m``, the arm noise of a step is halved (1, 1/2, 1/4, then none) until the lowest collision point of the
+ commanded pose (Scene.lowest) is at least min(the plan's own lowest point, ``floor_m``). The phases are the
+ plan's. -> the episode with these targets; meta gets the noise, the guarded steps and kind = "stj" (the data's variant)."""
+ rows, phases = zip(*ep["script"])
+ rows = np.array(rows)
+ sd, tc, dj = rng.uniform(*std), rng.uniform(*tau), rng.uniform(*jaw_offset)
+ dt, sp = s.cfg["control_step_s"], s.cfg["speed_rad_s"]
+ noise = np.zeros_like(rows)
+ noise[:, :5] = ou_noise(rng, len(rows), 5, sd, tc, dt)
+ noise[:, 5] = dj
+ lim = np.r_[[sp["arm_max"] * dt] * 5, sp["jaw"] * dt]
+ out, prev = np.empty_like(rows), np.clip(np.asarray(ep["q0"], float), s.tlo, s.thi)
+ guarded = 0
+ for k, row in enumerate(rows):
+ near = s.grasp_pose(row)[0][2] < near_m
+ floor = min(s.lowest(s.fk(row)), floor_m) if near else None
+ for lam in (1.0, 0.5, 0.25, 0.0):
+ w = np.clip(row + noise[k] * np.r_[[lam] * 5, 1.0], s.tlo, s.thi)
+ q = prev + np.clip(w - prev, -lim, lim)
+ if not near or lam == 0.0 or s.lowest(s.fk(q)) >= floor:
+ break
+ guarded += lam < 1.0
+ prev = out[k] = q
+ meta = {**ep["meta"], "ou_std_rad": float(sd), "ou_tau_s": float(tc), "jaw_offset_rad": float(dj),
+ "guarded_steps": int(guarded), "kind": f"s{sd * 1e3:.0f}t{tc * 1e2:.0f}j{dj * 1e3:+.0f}"}
+ return dict(ep, script=play(out, phases), meta=meta)
+
+
+def fam_noisy(base, **kw):
+ """A family: the base family's plan with policy-like commands (noisy_commands)."""
+ def family(s, rng, n):
+ return noisy_commands(s, rng, base(s, rng, n, **kw))
+ return family
+
+
+# ---- probes -------------------------------------------------------------------------------------------------
+def free_motion(s, rng, q0, n, speed=(0.8, 3.0)):
+ """Random joint-space moves between collision-free configurations (jaw included), with short holds."""
+ plan = Plan(s, q0, rng)
+ tries = 0
+ while len(plan) < n and tries < 50:
+ tries += 1
+ try:
+ q1 = s.sample_free(rng)
+ except PlanError:
+ break
+ if not s.path_clear(plan.q, q1):
+ continue
+ plan.joint(q1, "free", speed=rng.uniform(*speed))
+ plan.hold(rng.uniform(0, 0.3), "idle")
+ plan.fill(n, rng, free=False)
+ return plan
+
+
+def fam_step_arm(s, rng, n):
+ """Step commands (servo saturation, no contact): the joint target jumps and is held 0.1-0.6 s. Half of the steps
+ move only the jaw, to any angle of its range (also closing from rest at any angle); the others move 1-5 arm joints
+ by up to 0.6 rad between collision-free poses (and the jaw with probability 0.5). The cube rests out of reach. The
+ task scripts command smooth profiles, so without this probe the core never sees a joint far from its target
+ without a contact (e.g. a jaw that a false contact stopped and that must close again)."""
+ q0 = s.sample_free(rng)
+ plan = Plan(s, q0, rng)
+ tries = 0
+ while len(plan) < n and tries < 200:
+ tries += 1
+ q1 = plan.q.copy()
+ lo, hi = s.jlo + 0.12, s.jhi - 0.12 # a saturated step overshoots its target: stay 0.12 rad inside the limits
+ if rng.uniform() < 0.5:
+ q1[5] = rng.uniform(lo[5], hi[5])
+ else:
+ q1[:5] = q1[:5] + rng.uniform(-0.6, 0.6, 5) * (rng.uniform(size=5) < 0.6)
+ if rng.uniform() < 0.5:
+ q1[5] = rng.uniform(lo[5], hi[5])
+ q1 = np.clip(q1, lo, hi)
+ low, self_hit = s.clearance(q1)
+ if low < 0.03 or self_hit or not s.path_clear(plan.q, q1):
+ continue
+ plan.add(np.repeat(q1[None], plan.steps(rng.uniform(0.1, 0.6)), 0), "free")
+ plan.fill(n, rng, free=False)
+ return dict(q0=q0, cube=dict(pos=s.park.copy(), quat=np.array([1.0, 0, 0, 0]), spawn=False),
+ script=plan.play(n), meta={})
+
+
+def fam_free_arm(s, rng, n):
+ q0 = s.sample_free(rng)
+ return dict(q0=q0, cube=dict(pos=s.park.copy(), quat=np.array([1.0, 0, 0, 0]), spawn=False),
+ script=free_motion(s, rng, q0, n).play(n), meta={})
+
+
+def thrown_cube(s, rng, q0, clearance, vz, vxy, spin=25.0):
+ """A cube in the throw region: random orientation, its lowest corner ``clearance`` above the table."""
+ for _ in range(100):
+ quat = random_quat(rng)
+ extent = np.abs(quat_mat(quat)[2]).sum() * s.half
+ pos = np.r_[rng.uniform(s.throw_lo, s.throw_hi), extent + rng.uniform(*clearance)]
+ if not s.cube_touches(q0, pos, quat):
+ break
+ a = rng.uniform(-math.pi, math.pi)
+ vel = np.array([math.cos(a), math.sin(a), 0.0]) * rng.uniform(*vxy) + [0, 0, rng.uniform(*vz)]
+ w = rng.normal(size=3)
+ return dict(pos=pos, quat=quat, vel=vel, omega=w / np.linalg.norm(w) * rng.uniform(0, spin), spawn=True)
+
+
+def fam_cube_flight(s, rng, n):
+ q0 = s.sample_free(rng)
+ cube = thrown_cube(s, rng, q0, clearance=(0.005, 0.10), vz=(1.0, 2.2), vxy=(0.0, 0.5))
+ return dict(q0=q0, cube=cube, script=free_motion(s, rng, q0, n).play(n), meta={})
+
+
+def fam_cube_table(s, rng, n):
+ q0 = s.sample_free(rng)
+ cube = thrown_cube(s, rng, q0, clearance=(0.001, 0.02), vz=(-0.3, 0.3), vxy=(0.1, 1.0))
+ return dict(q0=q0, cube=cube, script=free_motion(s, rng, q0, n, speed=(0.5, 1.5)).play(n), meta={})
+
+
+# Inner faces of the jaws, gripper frame at jaw angle 0: a pad point near the tips, the face normal and the
+# direction along the finger from the tip towards its base.
+JAW_FACES = {
+ "fixed": (np.array([-0.0090, 0.0, -0.0950]), np.array([0.994, 0.0, 0.110]), np.array([-0.110, 0.0, 0.994])),
+ "moving": (np.array([0.0090, 0.0, -0.0950]), np.array([-0.997, 0.0, 0.070]), np.array([0.070, 0.0, 0.997]))}
+
+
+def jaw_face(s, which, along):
+ """A point on a jaw's inner face ``along`` metres from the tip pad towards the finger base, and the face frame
+ (columns: along the finger, across, normal), in the frame of the jaw's body (the gripper for the fixed jaw)."""
+ point, normal, axis = JAW_FACES[which]
+ frame = np.stack((axis, np.cross(normal, axis), normal), 1)
+ point = point + axis * along
+ if which == "fixed":
+ return s.gripper, point, frame
+ dk = s.fk(np.zeros(6))
+ r_g, r_j = dk.xmat[s.gripper].reshape(3, 3), dk.xmat[s.jaw_body].reshape(3, 3)
+ return s.jaw_body, r_j.T @ (dk.xpos[s.gripper] + r_g @ point - dk.xpos[s.jaw_body]), r_j.T @ r_g @ frame
+
+
+def fam_jaw(which):
+ def family(s, rng, n):
+ """The jaw's inner face held up, 10-20 cm above the table, with a slope of -25..25 degrees along the finger
+ (none across it), the other jaw open out of the way. The cube, its faces parallel to the jaw face, is
+ released 1-12 mm above it: it lands, rests or slides along the finger; after 0.2-0.8 s a fast turn of one
+ arm joint (1.2-2 rad) tips the face over. The cube falls to the table (or onto the arm base, which ends the
+ episode) or stays on the gripper against a palm block."""
+ px, py = s.cfg["workspace"]["pan_axis_xy_m"]
+ for _ in range(200):
+ r, a = rng.uniform(0.15, 0.27), math.radians(rng.uniform(-70, 70))
+ pos = np.array([px + r * math.cos(a), py + r * math.sin(a), rng.uniform(0.10, 0.20)])
+ theta = rng.uniform(1.3, s.thi[5]) if which == "fixed" else rng.uniform(0.9, 1.4)
+ body, point, frame = jaw_face(s, which, rng.uniform(0.0, 0.03))
+ beta, psi = math.radians(rng.uniform(-25, 25)), rng.uniform(-math.pi, math.pi)
+ along = np.array([math.cos(beta) * math.cos(psi), math.cos(beta) * math.sin(psi), math.sin(beta)])
+ normal = np.array([-math.sin(beta) * math.cos(psi), -math.sin(beta) * math.sin(psi), math.cos(beta)])
+ face_w = np.stack((along, np.cross(normal, along), normal), 1)
+ q = np.array([math.atan2(pos[1] - py, pos[0] - px), rng.uniform(-0.5, 0.5), rng.uniform(0, 1.2),
+ rng.uniform(-1.2, 1.2), rng.uniform(-2.5, 2.5), theta])
+ dk = s.fk(q)
+ r_body_in_g = dk.xmat[s.gripper].reshape(3, 3).T @ dk.xmat[body].reshape(3, 3)
+ rot = face_w @ frame.T @ r_body_in_g.T # gripper orientation that puts the face frame at face_w
+ q, ep, ea = s.ik(q, pos, rot=rot, body=body, point=point, w_rot=0.02, iters=400)
+ if ep > 0.003 or ea > math.radians(25):
+ continue
+ low, self_hit = s.clearance(q)
+ if low < 0.04 or self_hit:
+ continue
+ dk = s.fk(q)
+ rb = dk.xmat[body].reshape(3, 3)
+ face_p, face_r = dk.xpos[body] + rb @ point, rb @ frame
+ if face_r[2, 2] < math.cos(math.radians(40)):
+ continue
+ yaw = rng.uniform(-0.35, 0.35)
+ quat = mat_quat(face_r @ topdown(yaw)) # cube faces parallel to the jaw face, turned by yaw
+ centre = face_p + face_r[:, 2] * (s.half + 0.0005) + [0, 0, rng.uniform(0.001, 0.012)]
+ if s.cube_touches(q, centre, quat) or not drop_hits(s, q, centre, body):
+ continue
+ # the throw: the joint (shoulder lift, wrist flex or roll) whose axis is most perpendicular to the face
+ # normal turns 1.2-2 rad towards its larger range and tips the face over
+ axes = dk.xaxis[[s.m.joint(JOINTS[j]).id for j in (1, 3, 4)]]
+ j = (1, 3, 4)[int(np.argmin(np.abs(axes @ face_r[:, 2])))]
+ room = (s.thi[j] - q[j], s.tlo[j] - q[j])
+ q1 = q.copy()
+ q1[j] = np.clip(q[j] + max(room, key=abs) / abs(max(room, key=abs)) * rng.uniform(1.2, 2.0),
+ s.tlo[j], s.thi[j])
+ if abs(q1[j] - q[j]) < 0.8 or not s.path_clear(q, q1, low_m=0.03):
+ continue
+ w = rng.normal(size=3)
+ cube = dict(pos=centre, quat=quat if quat[0] >= 0 else -quat, vel=np.zeros(3),
+ omega=w / np.linalg.norm(w) * rng.uniform(0, 1), spawn=True)
+ plan = Plan(s, q, rng)
+ plan.hold(rng.uniform(0.2, 0.8), "rest")
+ plan.joint(q1, "throw", speed=rng.uniform(2.0, 3.0))
+ plan.hold(rng.uniform(0.2, 0.5), "rest")
+ plan.fill(n, rng, free=False)
+ return dict(q0=q, cube=cube, script=plan.play(n),
+ meta=dict(kind=which, slope_deg=round(math.degrees(beta), 1)))
+ raise PlanError("no jaw pose")
+ return family
+
+
+def drop_hits(s, q, centre, body):
+ """A vertical ray from the cube centre: the first arm or table geom below it is on ``body``, within 5 cm."""
+ dk = s.fk(q)
+ geom = np.zeros(1, np.int32)
+ dist = mujoco.mj_ray(s.m, dk, np.asarray(centre, float), np.array([0.0, 0.0, -1.0]),
+ np.array([1, 0, 0, 1, 1, 0], np.uint8), 1, s.cube_body, geom)
+ return dist >= 0 and s.m.geom_bodyid[geom[0]] == body and dist < 0.05
+
+
+FAMILIES = {"nominal": fam_nominal, "off_centre": fam_off_centre, "one_sided": fam_one_sided,
+ "near_miss": fam_near_miss, "weak_closure": fam_weak_closure, "drop": fam_drop, "push": fam_push,
+ "free_arm": fam_free_arm, "cube_flight": fam_cube_flight, "cube_table": fam_cube_table,
+ "jaw_fixed": fam_jaw("fixed"), "jaw_moving": fam_jaw("moving"), "step_arm": fam_step_arm,
+ "noisy_nominal": fam_noisy(fam_nominal), "noisy_off_centre": fam_noisy(fam_off_centre),
+ "noisy_carry": fam_noisy(fam_policy_grasp, move_prob=1.0),
+ "noisy_offset": fam_noisy(fam_policy_grasp, offset_m=(0.001, 0.008))}
+
+
+# ---- one episode ----------------------------------------------------------------------------------------------
+def run_episode(s, ep, n_rec):
+ """Simulate a planned episode -> arrays of the contract plus diagnostics (or None after a numerical failure)."""
+ m, d = s.m, s.d
+ c = ep["cube"]
+ s.reset(ep["q0"], c["pos"], c["quat"], c.get("vel"), c.get("omega"), c["spawn"])
+ arm = np.zeros((n_rec, 12))
+ cube = np.zeros((n_rec, 13))
+ action = np.zeros((n_rec, 6))
+ phase = np.zeros(n_rec, np.int8)
+ rel = np.zeros((n_rec, 3))
+ force = np.zeros((n_rec - 1, 3))
+ impulse = np.zeros((n_rec - 1, 3))
+ palm = np.zeros((n_rec - 1, 2))
+ depth = np.zeros((n_rec - 1, 3))
+ overlap = np.zeros(n_rec)
+ other = np.zeros(4) # largest unsupported force by kind in the recorded intervals (below the threshold)
+ script = ep["script"]
+ obs = None
+ target, ph = next(script)
+ terminal, length = 0, n_rec
+ dt = m.opt.timestep
+ ctrl_force = np.zeros(3)
+ for k in range(n_rec):
+ arm[k], cube[k] = s.state()
+ rel[k] = s.cube_in_gripper()
+ if k % s.per_ctrl == 0 and k > 0:
+ obs = dict(q=arm[k, :6], cube=cube[k], force=ctrl_force)
+ try:
+ target, ph = script.send(obs)
+ except StopIteration:
+ ph = P["idle"]
+ ctrl_force = np.zeros(3)
+ u = np.clip(target, s.tlo, s.thi).astype(np.float32) # stored and applied: the same float32 values
+ action[k], phase[k] = u, ph
+ if k == n_rec - 1:
+ overlap[k] = s.overlap_at(d.qpos)
+ if overlap[k] > s.overlap_thr:
+ terminal, length = TERMINAL.index("cube_visual_overlap"), k
+ break
+ d.ctrl[s.act] = u
+ fmax, bad = np.zeros(3), np.zeros(4)
+ for j in range(s.nsub):
+ mujoco.mj_step(m, d)
+ if j == 0: # d holds the kinematics and contacts of record k
+ overlap[k] = s.visual_overlap(d)
+ if overlap[k] > s.overlap_thr:
+ break
+ f, pen = s.contact_forces()
+ fmax = np.maximum(fmax, f[:3])
+ impulse[k] += f[:3] * dt
+ bad = np.maximum(bad, f[3:7])
+ palm[k] = np.maximum(palm[k], f[7:])
+ depth[k] = np.maximum(depth[k], pen)
+ if overlap[k] > s.overlap_thr: # the cube inside a gripper or jaw part: end at the record before
+ terminal, length = TERMINAL.index("cube_visual_overlap"), k
+ break
+ if d.warning[mujoco.mjtWarning.mjWARN_BADQACC].number or not np.isfinite(d.qpos).all():
+ return None
+ if (bad > s.thr).any():
+ terminal, length = 1 + int(np.argmax(bad > s.thr)), k + 1
+ break
+ other = np.maximum(other, bad)
+ p = d.qpos[s.cq: s.cq + 3]
+ if (p[:2] < s.table_lo).any() or (p[:2] > s.table_hi).any() or p[2] < -0.01:
+ terminal, length = TERMINAL.index("cube_off_table"), k + 1
+ break
+ force[k] = fmax
+ ctrl_force = np.maximum(ctrl_force, fmax)
+ script.close()
+ L = length
+ if L < 2: # ended at the start: the family plans again
+ return "replan"
+ cube[:L, 3:7] = export.quat_continuous(cube[:L, 3:7])
+ out = dict(states={"arm": arm[:L], "cube": cube[:L]}, action=action[:L],
+ contacts=(force[:L - 1] > s.thr).astype(np.uint8),
+ per_record=dict(phase=phase[:L], cube_in_grasp=rel[:L].astype(np.float32),
+ visual_overlap=overlap[:L].astype(np.float32)),
+ per_interval=dict(contact_force=force[:L - 1].astype(np.float32),
+ contact_impulse=impulse[:L - 1].astype(np.float32),
+ palm_force=palm[:L - 1].astype(np.float32),
+ contact_depth=depth[:L - 1].astype(np.float32)),
+ terminal=terminal, other_force=other)
+ return out
+
+
+def outcome(ep, half, family_group):
+ """Task outcome from the records: lifted (both jaws on, cube bottom 10 mm above the table, no table contact),
+ dropped (after lifting, no jaw contact while the cube is up, before the planned release), slip in the grasp."""
+ if family_group == "probe":
+ return dict(outcome=0, max_lift_m=0.0, hold_slip_mm=np.nan, carry_slip_mm=np.nan)
+ c = ep["contacts"].astype(bool)
+ z = ep["states"]["cube"][1:, 2] - half
+ ph = ep["per_record"]["phase"][1:]
+ gripped = c[:, 0] & c[:, 1] & ~c[:, 2]
+ up = gripped & (z > 0.010)
+ max_lift = float(z[gripped].max()) if gripped.any() else 0.0
+ if not up.any():
+ return dict(outcome=1, max_lift_m=max_lift, hold_slip_mm=np.nan, carry_slip_mm=np.nan)
+ first = int(np.argmax(up))
+ carrying = np.isin(ph, [P[x] for x in ("lift", "hold", "move", "shake", "loosen", "lower")])
+ lost = (~c[:, 0] & ~c[:, 1]) & (z > 0.010) & carrying
+ lost[:first] = False
+ rel = ep["per_record"]["cube_in_grasp"][1:]
+ hold = np.flatnonzero((ph == P["hold"]) & gripped)
+ if len(hold) > 1: # the first continuous hold after lifting
+ hold = hold[: int(np.argmax(np.diff(hold) > 1)) + 1] if (np.diff(hold) > 1).any() else hold
+ hold_slip = float(np.linalg.norm(rel[hold[-1]] - rel[hold[0]]) * 1000) if len(hold) > 1 else np.nan
+ carry = np.flatnonzero(carrying & gripped & (np.arange(len(z)) >= first))
+ carry_slip = float(np.linalg.norm(rel[carry] - rel[carry[0]], axis=1).max() * 1000) if len(carry) else np.nan
+ return dict(outcome=3 if lost.any() else 2, max_lift_m=max_lift, hold_slip_mm=hold_slip, carry_slip_mm=carry_slip)
+
+
+# ---- the collector ---------------------------------------------------------------------------------------------
+_SCENE = None
+
+
+def _worker_init(cfg_path):
+ global _SCENE
+ s = Scene(load_config(cfg_path))
+ _SCENE = s, system_json(s, s.cfg)
+
+
+def episode_seed(master, family, index):
+ return int(np.random.SeedSequence([int(master), int(family), int(index)]).generate_state(2, np.uint64)[0] >> 1)
+
+
+def campaign_counts(cfg, campaign, scale=None, probe_scale=None, families=None):
+ """Episodes per family of a campaign -> [(family index, count)]: the pilot counts of the config times the
+ campaign's task_scale and probe_scale. ``scale`` replaces both factors, ``probe_scale`` the probe factor. A campaign
+ with a "families" list runs only those (``families`` overrides it)."""
+ c = cfg["campaigns"][campaign]
+ families = families or c.get("families")
+ tasks = c["task_scale"] if scale is None else scale
+ probes = probe_scale if probe_scale is not None else (c["probe_scale"] if scale is None else scale)
+ return [(f, max(1, int(round(fam["episodes"] * (probes if fam["group"] == "probe" else tasks)))))
+ for f, fam in enumerate(cfg["families"]) if (not families or fam["name"] in families)
+ and campaign in fam.get("campaigns", [campaign])] # a family with "campaigns" runs only in those
+
+
+def check_seeds(cfg, campaign, counts):
+ """The master seeds of the campaigns and of the convergence check differ, and the episode seeds of this run
+ overlap neither each other nor those of the other campaigns (at their configured counts) or of the convergence
+ check. -> number of episode seeds of this run."""
+ masters = {name: c["master_seed"] for name, c in cfg["campaigns"].items()}
+ masters["convergence"] = cfg["convergence"]["master_seed"]
+ if len(set(masters.values())) != len(masters):
+ raise SystemExit(f"the master seeds must differ: {masters}")
+ names = [f["name"] for f in cfg["families"]]
+
+ def seeds(master, counts):
+ return [episode_seed(master, f, i) for f, n in counts for i in range(n)]
+ mine = seeds(masters[campaign], counts)
+ if len(set(mine)) != len(mine):
+ raise SystemExit(f"repeated episode seeds in campaign {campaign}")
+ others = {name: seeds(masters[name], campaign_counts(cfg, name)) for name in cfg["campaigns"] if name != campaign}
+ others["convergence"] = seeds(masters["convergence"], [(names.index(k), n) for k, n in
+ cfg["convergence"]["episodes"].items()])
+ for name, other in others.items():
+ if set(mine) & set(other):
+ raise SystemExit(f"episode seeds of campaign {campaign} overlap with {name}")
+ return len(mine)
+
+
+def make_episode(s, fam_index, index, master):
+ """Plan and simulate one episode (planning samples again until the poses are reachable)."""
+ cfg = s.cfg
+ fam = cfg["families"][fam_index]
+ seed = episode_seed(master, fam_index, index)
+ rng = np.random.default_rng(seed)
+ n_rec = int(fam["records"])
+ n_ctrl = (n_rec - 1) // s.per_ctrl + 1
+ tries = 0
+ while True:
+ tries += 1
+ try:
+ plan = FAMILIES[fam["name"]](s, rng, n_ctrl)
+ except PlanError:
+ if tries > 200:
+ raise
+ continue
+ out = run_episode(s, plan, n_rec)
+ if out is None:
+ return dict(rejected=True, family=fam_index, index=index, seed=seed)
+ if isinstance(out, str): # ended before the second record
+ if tries > 200:
+ raise PlanError("episodes end at the start")
+ continue
+ out["meta"] = plan["meta"]
+ out["seed"], out["plan_tries"] = seed, tries
+ return out
+
+
+def _work(args):
+ """Simulate a chunk of jobs [(family, index, master seed)] and pack them into one shard file -> statistics."""
+ k, (jobs, shard) = args
+ s, system = _SCENE
+ fams = s.cfg["families"]
+ episodes, rejected, cpu, wall = [], [], {}, {}
+ for fam_index, index, master in jobs:
+ t0, c0 = time.perf_counter(), time.process_time()
+ r = make_episode(s, fam_index, index, master)
+ name = fams[fam_index]["name"]
+ cpu[name] = cpu.get(name, 0.0) + time.process_time() - c0
+ wall[name] = wall.get(name, 0.0) + time.perf_counter() - t0
+ if r.get("rejected"):
+ rejected.append(dict(family=name, index=index, seed=r["seed"]))
+ continue
+ o = outcome(r, s.half, fams[fam_index]["group"])
+ episodes.append(dict(states=r["states"], action=r["action"], contacts=r["contacts"],
+ per_record=r["per_record"], per_interval=r["per_interval"],
+ scalars=dict(family=np.int16(fam_index), episode_id=np.int64(-1), group_id=np.int64(-1),
+ seed=np.int64(r["seed"]), terminal_reason=np.int8(r["terminal"]),
+ outcome=np.int8(o["outcome"]), max_lift_m=np.float32(o["max_lift_m"]),
+ hold_slip_mm=np.float32(o["hold_slip_mm"]),
+ carry_slip_mm=np.float32(o["carry_slip_mm"]),
+ family_index=np.int64(index), plan_tries=np.int16(r["plan_tries"]),
+ unsupported_max_n=np.float32(r["other_force"].max()),
+ variant=str(r["meta"].get("kind", r["meta"].get("jaw", ""))))))
+ if episodes:
+ export.write_shard(shard, export.pack_episodes(episodes, system))
+ return k, dict(shard=str(shard) if episodes else None, episodes=len(episodes), rejected=rejected, cpu_s=cpu,
+ wall_s=wall, records=int(sum(len(e["action"]) for e in episodes)))
+
+
+def _plain(x):
+ return x.item() if hasattr(x, "item") else str(x)
+
+
+def source_hashes():
+ """sha256 of the collector's own source files (git_info covers tracked files only)."""
+ here = Path(__file__).resolve().parent
+ return {str(f.relative_to(export.REPO_ROOT)): export.sha256_file(f)
+ for f in (here / "so101_grasp.py", here / "export.py", here / "validate.py", here / "__init__.py")}
+
+
+def system_json(s, cfg):
+ """system.json of the contract: bodies, pairs with their geoms, the label rule, families and the physics."""
+ m = s.m
+ arm_links = ["base", "shoulder", "upper_arm", "lower_arm", "wrist", "gripper", "camera_mount",
+ "moving_jaw_so101_v1"]
+
+ def names(c):
+ return [m.geom(g).name for g in np.flatnonzero(s.cls == c)]
+ jid = [m.joint(j).id for j in JOINTS]
+ blocks = set(cfg["palm_geoms"])
+ ph = cfg["physics"]
+ gripper_geom = m.geom("fixed_jaw_box4").id
+ return {
+ "name": cfg["name"], "record_step_s": cfg["record_step_s"], "model_step_s": cfg["model_step_s"],
+ "control_step_s": cfg["control_step_s"], "target_time_s": cfg["target_time_s"],
+ "records_per_episode": cfg["records_per_episode"],
+ "frame": "world z up, table top at z = 0, arm base frame = world frame (base at the origin), SI units, "
+ "radians, quaternions wxyz (unit, w >= 0 at the first record, sign continuous)",
+ "bodies": [
+ {"name": "arm", "kind": "articulated", "moving": True, "state_dim": 12,
+ "channels": [f"q_{j}" for j in JOINTS] + [f"qd_{j}" for j in JOINTS],
+ "channel_types": ["angle"] * 6 + ["angular_rate"] * 6, "channel_mask": [1] * 12,
+ "action_dim": 6, "action_channels": [f"qcmd_{j}" for j in JOINTS], "joint_names": list(JOINTS),
+ "links": arm_links,
+ "actuators": {"type": "position", "kp": float(m.actuator_gainprm[s.act[0], 0]),
+ "kv": float(-m.actuator_biasprm[s.act[0], 2]),
+ "force_range_nm": m.actuator_forcerange[s.act[0]].tolist(),
+ "ctrl_range_rad": m.actuator_ctrlrange[s.act].tolist()},
+ "joints": {"range_rad": m.jnt_range[jid].tolist(), "damping": m.dof_damping[s.vadr].tolist(),
+ "armature": m.dof_armature[s.vadr].tolist(),
+ "frictionloss": m.dof_frictionloss[s.vadr].tolist()},
+ "grasp_point_m": cfg["grasp_point_m"],
+ "note": "jaw = joint 'gripper' (the moving jaw); the fixed jaw is part of link 'gripper'. Action = the "
+ "applied position targets of the 6 Menagerie actuators (float32, the same values in d.ctrl), "
+ "kept physics_config.joint_limits.scripted_target_margin_rad inside the joint ranges"},
+ {"name": "cube", "kind": "rigid", "moving": True, "state_dim": 13,
+ "channels": ["x", "y", "z", "qw", "qx", "qy", "qz", "vx", "vy", "vz", "wx", "wy", "wz"],
+ "channel_types": ["position"] * 3 + ["quaternion"] * 4 + ["velocity"] * 3 + ["angular_velocity"] * 3,
+ "channel_mask": [1] * 13,
+ "geometry": {"size_m": cfg["cube"]["size_m"], "mass_kg": float(m.body_mass[s.cube_body]),
+ "inertia_diag_kgm2": m.body_inertia[s.cube_body].tolist()},
+ "note": "centre of the cube (= centre of mass); velocity and angular velocity in the world frame"},
+ {"name": "table", "kind": "fixed", "moving": False, "top_z_m": 0.0,
+ "size_xy_m": cfg["table"]["size_xy_m"], "center_xy_m": cfg["table"]["center_xy_m"]},
+ ],
+ "pairs": [[0, 1], [0, 1], [1, 2]],
+ "pair_metadata": [
+ {"name": PAIRS[0], "geoms": [names(FIXED), ["cube"]],
+ "regions": {"fixed_finger": [g for g in names(FIXED) if g not in blocks],
+ "palm_blocks": [g for g in names(FIXED) if g in blocks and g != "gripper_collision0"],
+ "wrist_servo_box": ["gripper_collision0"]},
+ "note": "all collision geoms of link 'gripper' against the cube: the fixed finger (pads, tips, finger "
+ "hull), the two palm blocks at the finger base and the wrist-servo box. One pair code for all "
+ "three regions; the per-interval palm_force array gives the palm-block and servo-box share"},
+ {"name": PAIRS[1], "geoms": [names(MOVING), ["cube"]],
+ "regions": {"moving_finger": [g for g in names(MOVING) if g not in blocks],
+ "hinge_block": [g for g in names(MOVING) if g in blocks]},
+ "note": "the moving jaw against the cube: its finger (pads, tips, hulls) and the hinge block at its base "
+ "(palm_force, second column)"},
+ {"name": PAIRS[2], "geoms": [["cube"], ["table"]], "note": "cube against the table top"},
+ ],
+ "target_body": 1,
+ "contact_rule": {
+ "threshold_n": s.thr,
+ "rule": "pair on in record interval k if, in any physics step inside it, the summed mj_contactForce "
+ "normal force of the pair's contacts is above threshold_n (MuJoCo computes the contacts and "
+ "forces of a step from the state at the start of that step)",
+ "force": "elliptic cones: the first constraint force of each contact (= mj_contactForce normal)",
+ "physics_steps_per_record": s.nsub,
+ "unsupported": "any other contact above threshold_n (arm-table, other arm links, the camera mount or the "
+ "arm base with the cube, arm self-contact) ends the episode at the last record before that "
+ "interval; an overlap of the cube with the visual meshes of the gripper or the moving jaw "
+ "(visual_overlap) ends it at the record before the overlap",
+ "unsupported_geoms": {"other_arm_links": names(LINK), "arm_base": names(BASE)},
+ "visual_overlap": {
+ "threshold_m": s.overlap_thr,
+ "bodies": [m.body(b).name for b in s.overlap_bodies],
+ "meshes": {m.body(b).name: s.overlap[b].meshes for b in s.overlap_bodies},
+ "rule": "at every record (the state at the start of the first physics step of the interval, with the "
+ "contacts MuJoCo computes from it): overlap = the larger of (a) the deepest visual-mesh "
+ "surface point of the body below the cube surface and (b) the deepest cube surface point below "
+ "the body's visual-mesh surface, minus the deepest penetration of the body's collision geoms "
+ "into the cube. Above threshold_m the episode ends at the record before (terminal reason "
+ "cube_visual_overlap): the cube is inside a part of the real gripper that has no collision "
+ "shape. Stored per record as visual_overlap (m)",
+ "grid_m": s.cfg["visual_overlap"]["grid_m"],
+ "point_spacing_m": s.cfg["visual_overlap"]["point_spacing_m"],
+ "cube_points_per_edge": s.cfg["visual_overlap"]["cube_points_per_edge"],
+ "parity_disagreements": {m.body(b).name: s.overlap[b].parity_disagreements
+ for b in s.overlap_bodies}}},
+ "families": [{k: f[k] for k in ("name", "group", "select", "note")} for f in cfg["families"]],
+ "terminal_reasons": list(TERMINAL),
+ "phases": list(PHASES),
+ "outcomes": list(OUTCOMES),
+ "physics_config": {
+ "simulator": f"MuJoCo {mujoco.__version__} (CPU, python bindings)",
+ "timestep_s": m.opt.timestep, "integrator": ph["integrator"], "cone": ph["cone"],
+ "impratio": m.opt.impratio, "solver": ph["solver"], "iterations": m.opt.iterations,
+ "ls_iterations": m.opt.ls_iterations, "tolerance": m.opt.tolerance,
+ "noslip_iterations": m.opt.noslip_iterations, "gravity": m.opt.gravity.tolist(),
+ "jaw_cube_contact": {"from": "Menagerie class collision_gripper (priority 1, used for every jaw contact)",
+ "condim": int(m.geom_condim[gripper_geom]),
+ "friction": m.geom_friction[gripper_geom].tolist(),
+ "solref": m.geom_solref[gripper_geom].tolist(),
+ "solimp": m.geom_solimp[gripper_geom].tolist()},
+ "cube_table_contact": {k: cfg["table"][k] for k in ("condim", "friction", "solref", "solimp")},
+ "table": cfg["table"], "cube": cfg["cube"], "warmup_s": cfg["warmup_s"],
+ "excluded_contacts": [["world (table)", "base"], ["base", "shoulder"]],
+ "joint_limits": {
+ "joints": {j: {"range_rad": m.jnt_range[i].tolist(), "limited": bool(m.jnt_limited[i]),
+ "solref": m.jnt_solref[i].tolist(), "solimp": m.jnt_solimp[i].tolist(),
+ "margin_rad": float(m.jnt_margin[i]),
+ "ctrl_range_rad": m.actuator_ctrlrange[s.act[k]].tolist()}
+ for k, (j, i) in enumerate(zip(JOINTS, jid))},
+ "scripted_target_margin_rad": s.cfg["joint_target_margin_rad"],
+ "target_range_rad": np.stack((s.tlo, s.thi), 1).tolist(),
+ "note": "compiled MuJoCo settings: soft joint-limit constraints (MuJoCo default solref and solimp); "
+ "every applied target lies in target_range_rad. A joint can still pass its limit by a few "
+ "mrad under load; the limit constraint then acts like a stiff spring"},
+ "base_collision": "convex hulls of the 4 Menagerie base meshes (added: the Menagerie base has no "
+ "collision geoms); a contact with the cube ends the episode (terminal reason cube_base)",
+ "model_sha256": hashlib.sha256(s.spec.to_xml().encode()).hexdigest(),
+ "menagerie": json.loads((export.REPO_ROOT / cfg["source_manifest"]).read_text())["source"],
+ },
+ }
+
+
+def collect(cfg, out_dir, workers, campaign="pilot", families=None, scale=None, probe_scale=None, chunk=16,
+ cfg_path=CONFIG):
+ """Simulate the episodes of a campaign (``campaign_counts``) on a worker pool. Each pool task simulates ``chunk``
+ episodes and writes them as one shard; the shards are merged in job order (family, then episode number) and
+ written as the data directory. Pilot and production: splits 0/1 by family; test: all split 2."""
+ t_start = time.perf_counter()
+ assets = verify_assets(cfg)
+ counts = campaign_counts(cfg, campaign, scale, probe_scale, families)
+ check_seeds(cfg, campaign, counts)
+ master = int(cfg["campaigns"][campaign]["master_seed"])
+ jobs = [(f, i, master) for f, n in counts for i in range(n)]
+ out_dir = Path(out_dir)
+ out_dir.parent.mkdir(parents=True, exist_ok=True)
+ s = Scene(cfg)
+ system = system_json(s, cfg)
+ print(f"campaign {campaign}: master seed {master}, {len(jobs)} episodes, {workers} workers, "
+ f"{chunk} episodes per shard", flush=True)
+ # The shard folder stays until the data directory is written: a finished shard leaves a stats file next to it,
+ # and a run started again skips those shards. A worker that dies (for example killed for lack of memory) stops
+ # the run with BrokenProcessPool instead of a silent hang.
+ tmp = Path(str(out_dir) + ".shards")
+ tmp.mkdir(parents=True, exist_ok=True)
+ tasks = [(jobs[k:k + chunk], tmp / f"shard_{k // chunk:06d}.npz") for k in range(0, len(jobs), chunk)]
+ stats = [json.loads(t[1].with_suffix(".json").read_text()) if t[1].with_suffix(".json").exists() else None
+ for t in tasks]
+ todo = [k for k, st in enumerate(stats) if st is None]
+ done, every = sum(len(tasks[k][0]) for k in range(len(tasks)) if stats[k] is not None), max(1, len(todo) // 20)
+ print(f"{len(tasks) - len(todo)} of {len(tasks)} shards already done", flush=True)
+ with ProcessPoolExecutor(workers, mp_context=mp.get_context("spawn"), initializer=_worker_init,
+ initargs=(str(cfg_path),)) as pool:
+ for n, (k, st) in enumerate(pool.map(_work, [(k, tasks[k]) for k in todo])):
+ side = tasks[k][1].with_suffix(".json")
+ side.with_name(side.name + ".tmp").write_text(json.dumps(st, default=_plain))
+ side.with_name(side.name + ".tmp").replace(side)
+ stats[k] = json.loads(side.read_text())
+ done += len(tasks[k][0])
+ if (n + 1) % every == 0 or n + 1 == len(todo):
+ el = time.perf_counter() - t_start
+ print(f"{done}/{len(jobs)} episodes, {el:.0f} s, {done / el:.2f} episodes/s, "
+ f"about {el * (len(jobs) - done) / done:.0f} s left", flush=True)
+ arrays = export.merge_shards([st["shard"] for st in stats if st["shard"]])
+ wall = time.perf_counter() - t_start
+ n_ep = len(arrays["lengths"])
+ arrays["episode_id"] = np.arange(n_ep, dtype=np.int64)
+ arrays["group_id"] = np.arange(n_ep, dtype=np.int64)
+ arrays["variant"] = arrays["variant"].astype("U16")
+ if campaign == "extra": # supplementary training episodes: all split 0 (the validation set stays that of production)
+ arrays["splits"] = np.zeros(len(arrays["family"]), np.int8)
+ elif campaign == "test":
+ arrays["splits"] = np.full(n_ep, 2, np.int8)
+ else:
+ arrays["splits"] = export.assign_splits(arrays["family"], arrays["group_id"], seed=master)
+ rejected = [r for st in stats for r in st["rejected"]]
+ cpu = float(sum(sum(st["cpu_s"].values()) for st in stats))
+ busy = float(sum(sum(st["wall_s"].values()) for st in stats))
+ transitions = int(((arrays["lengths"] - 1) // 2).sum())
+ per_family = {}
+ for f, fam in enumerate(cfg["families"]):
+ sel = arrays["family"] == f
+ if sel.any():
+ per_family[fam["name"]] = dict(
+ episodes=int(sel.sum()), worker_cpu_s=float(sum(st["cpu_s"].get(fam["name"], 0.0) for st in stats)),
+ worker_wall_s=float(sum(st["wall_s"].get(fam["name"], 0.0) for st in stats)),
+ transitions_20ms=int(((arrays["lengths"][sel] - 1) // 2).sum()))
+ throughput = dict(workers=workers, chunk=chunk, wall_s=wall, worker_cpu_s=cpu, worker_wall_s=busy,
+ load_average=list(os.getloadavg()), cpu_count=os.cpu_count(),
+ episodes_per_wall_s=n_ep / wall, episodes_per_cpu_s=n_ep / cpu,
+ transitions_20ms_per_cpu_s=transitions / cpu,
+ records_10ms_per_cpu_s=float((arrays["lengths"] - 1).sum()) / cpu, per_family=per_family)
+ manifest = dict(
+ collector="nedm.contact_nrd.collect.so101_grasp", campaign=campaign, master_seed=master,
+ episode_counts={cfg["families"][f]["name"]: n for f, n in counts},
+ episode_scale=dict(tasks=scale, probes=probe_scale, families=families),
+ config=cfg, config_sha256=hashlib.sha256(json.dumps(cfg, sort_keys=True).encode()).hexdigest(),
+ vendor_files_sha256=assets, collector_source_sha256=source_hashes(), rejected_numerical=rejected,
+ throughput=throughput, summary=summarize(system, arrays))
+ info = export.write_dataset(out_dir, system, arrays, manifest)
+ shutil.rmtree(tmp)
+ print(json.dumps({k: info[k] for k in ("episodes", "valid_records", "split_counts")}, indent=1))
+ print(json.dumps({k: v for k, v in throughput.items() if k != "per_family"}, indent=1))
+ return info
+
+
+def summarize(system, arrays):
+ """Terminations, end states (where the cube is in the last interval of the episodes that run to their end),
+ task outcomes, slip, contact-force histogram and label flips (threshold 0 vs 2x), penetration depths, landing speed
+ and energy change of cube-table impacts, cube-table label switches while the jaws close and grip, and the
+ single-jaw training windows that touch a palm block; records with a joint past its limit and the stored overlap of
+ the cube with the visual meshes of the gripper and the moving jaw."""
+ fam_names = [f["name"] for f in system["families"]]
+ lengths, contacts, family = arrays["lengths"], arrays["contacts"].astype(bool), arrays["family"]
+ thr = system["contact_rule"]["threshold_n"]
+ out = {"terminal_reasons": {}, "end_states": {}, "outcomes": {}, "slip": {}, "penetration_mm": {}, "impacts": {},
+ "table_switches_close_grip": {}, "joint_limits": {}, "visual_overlap_mm": {}}
+ valid = np.arange(arrays["arm"].shape[1])[None, :] < lengths[:, None]
+ limits = np.array(system["bodies"][0]["joints"]["range_rad"])
+ q = arrays["arm"][..., :6].astype(np.float64)
+ past = np.maximum(np.maximum(limits[:, 0] - q, q - limits[:, 1]), 0.0) * valid[..., None] # rad past the limit
+ joints = system["bodies"][0]["joint_names"]
+ cube_body = next(b for b in system["bodies"] if b["name"] == "cube")["geometry"]
+ energy_args = cube_body["mass_kg"], cube_body["inertia_diag_kgm2"][0], system["physics_config"]["gravity"][2]
+ phases = system["phases"]
+ for f, name in enumerate(fam_names):
+ sel = family == f
+ if not sel.any():
+ continue
+ tr = arrays["terminal_reason"][sel]
+ out["terminal_reasons"][name] = {r: int((tr == k).sum()) for k, r in enumerate(system["terminal_reasons"])
+ if (tr == k).any()}
+ last = np.flatnonzero(sel), np.maximum(lengths[sel] - 2, 0)
+ c, palm, done = contacts[last], arrays["palm_force"][last] > thr, tr == 0
+ jaw = c[:, :2].any(1)
+ out["end_states"][name] = dict(ended_early=int((~done).sum()), on_table=int((done & c[:, 2] & ~jaw).sum()),
+ on_gripper=int((done & jaw).sum()),
+ on_a_palm_block=int((done & palm.any(1)).sum()),
+ in_air=int((done & ~c.any(1)).sum()))
+ p = past[sel]
+ out["joint_limits"][name] = dict(records=int(valid[sel].sum()), past_a_limit=int((p > 0).any(-1).sum()),
+ by_joint={j: int((p[..., k] > 0).sum()) for k, j in enumerate(joints)
+ if (p[..., k] > 0).any()},
+ max_mrad=float(p.max() * 1000))
+ out["visual_overlap_mm"][name] = _stats(arrays["visual_overlap"][sel][valid[sel]] * 1000)
+ oc = arrays["outcome"][sel]
+ out["outcomes"][name] = {r: int((oc == k).sum()) for k, r in enumerate(system["outcomes"]) if (oc == k).any()}
+ for key in ("hold_slip_mm", "carry_slip_mm"):
+ v = arrays[key][sel]
+ v = v[np.isfinite(v)]
+ if len(v):
+ out["slip"].setdefault(name, {})[key] = _stats(v)
+ out["penetration_mm"][name] = {p: _stats(arrays["contact_depth"][sel][..., q][contacts[sel][..., q]] * 1000)
+ for q, p in enumerate(PAIRS)}
+ ev, switches = [], []
+ for i in np.flatnonzero(sel):
+ n = lengths[i]
+ cube = arrays["cube"][i, :n].astype(np.float64)
+ ev += impacts(contacts[i, :n - 1], cube, cube_energy(cube, *energy_args))
+ grip = np.flatnonzero(np.isin(arrays["phase"][i, :n - 1], [phases.index("close"), phases.index("grip")]))
+ if len(grip):
+ switches.append(int(np.abs(np.diff(contacts[i, grip[0]:grip[-1] + 1, 2].astype(int))).sum()))
+ if ev:
+ gain = np.array([g for _, g in ev if g is not None] + [-np.inf])
+ out["impacts"][name] = {"landings": len(ev), "landing_speed_m_s": _stats([v for v, _ in ev]),
+ "bounces": len(gain) - 1, "energy_gain_above_0.1_mj": int((gain > 1e-4).sum()),
+ "largest_change_mj": float(gain.max() * 1000) if len(gain) > 1 else None}
+ if switches:
+ sw = np.array(switches)
+ out["table_switches_close_grip"][name] = dict(episodes=len(sw), off_and_on_again=int((sw >= 2).sum()),
+ max=int(sw.max()))
+ force = arrays["contact_force"]
+ valid = np.arange(force.shape[1])[None, :] < (lengths - 1)[:, None]
+ edges = np.r_[0.0, np.logspace(-6, 2, 33)]
+ out["contact_force_histogram"] = {"edges_n": edges.tolist()}
+ flips = {}
+ for p, meta in enumerate(system["pair_metadata"]):
+ f = force[..., p][valid]
+ out["contact_force_histogram"][meta["name"]] = np.histogram(f, np.r_[edges, np.inf])[0].tolist()
+ on = f > thr
+ flips[meta["name"]] = dict(on=int(on.sum()), on_at_0=int((f > 0).sum()), on_at_2x=int((f > 2 * thr).sum()),
+ flips_0=int(((f > 0) != on).sum()), flips_2x=int(((f > 2 * thr) != on).sum()),
+ half_to_1x=int(((f > thr / 2) & ~on).sum()),
+ x1_to_2x=int((on & (f <= 2 * thr)).sum()))
+ out["label_flips"] = flips
+ lab, _, valid_w, _ = validate.training_windows(system, arrays["contacts"], lengths, arrays["splits"])
+ palm = np.concatenate((arrays["palm_force"] > thr, np.zeros_like(arrays["contacts"][..., :1], bool)), -1)
+ palm_lab = validate.training_windows(system, palm, lengths, arrays["splits"])[0]
+ single = valid_w & (lab.sum(-1) == 1) & (arrays["splits"] == 0)[:, None]
+ out["single_jaw_windows_train"] = {}
+ for q in (0, 1):
+ w = single & lab[..., q]
+ out["single_jaw_windows_train"][PAIRS[q]] = {
+ "all": int(w.sum()), "touching_a_palm_block": int((w & palm_lab[..., q]).sum()),
+ "by_family": {fam_names[f]: [int(w[family == f].sum()), int((w & palm_lab[..., q])[family == f].sum())]
+ for f in range(len(fam_names)) if w[family == f].any()}}
+ return out
+
+
+# ---- convergence -----------------------------------------------------------------------------------------------
+def replay(s, ep, actions):
+ """Open-loop replay of recorded commands (one per record) from the episode's start -> states, contact labels and
+ the deepest penetration [3] of the pairs (m)."""
+ m, d = s.m, s.d
+ c = ep["cube"]
+ s.reset(ep["q0"], c["pos"], c["quat"], c.get("vel"), c.get("omega"), c["spawn"])
+ n = len(actions)
+ arm, cube, contacts = np.zeros((n, 12)), np.zeros((n, 13)), np.zeros((n - 1, 3), bool)
+ depth = np.zeros(3)
+ for k in range(n):
+ arm[k], cube[k] = s.state()
+ if k == n - 1:
+ break
+ d.ctrl[s.act] = actions[k]
+ fmax = np.zeros(3)
+ for _ in range(s.nsub):
+ mujoco.mj_step(m, d)
+ f, pen = s.contact_forces()
+ fmax = np.maximum(fmax, f[:3])
+ depth = np.maximum(depth, pen)
+ contacts[k] = fmax > s.thr
+ return arm, cube, contacts, depth
+
+
+def cube_energy(cube, mass, inertia, gravity_z):
+ """Kinetic plus potential energy [T] (J) of recorded cube states (world angular velocity; a cube's inertia is
+ the same about every axis)."""
+ return (0.5 * mass * (cube[:, 7:10] ** 2).sum(-1) + 0.5 * inertia * (cube[:, 10:13] ** 2).sum(-1)
+ - mass * gravity_z * cube[:, 2])
+
+
+def impacts(contacts, cube, energy):
+ """Cube-table contact events after a contact-free interval of the cube -> [(speed at the onset m/s, energy after
+ - energy before J if the cube is contact-free again after the event, else None)]."""
+ free = ~contacts.any(1)
+ table = contacts[:, 2] & ~contacts[:, :2].any(1)
+ out, k, n = [], 1, len(contacts)
+ while k < n:
+ if table[k] and free[k - 1]:
+ k1 = k
+ while k1 < n and table[k1]:
+ k1 += 1
+ change = float(energy[k1] - energy[k]) if k1 < n and free[k1] else None
+ out.append((float(np.linalg.norm(cube[k, 7:10])), change))
+ k = k1
+ k += 1
+ return out
+
+
+def grasp_frame(s, arm, cube):
+ """Cube centre in the grasp frame [T, 3] for recorded arm and cube states."""
+ out = np.zeros((len(arm), 3))
+ for t in range(len(arm)):
+ dk = s.fk(arm[t, :6], cube[t, :3])
+ r = dk.xmat[s.gripper].reshape(3, 3)
+ out[t] = r.T @ (cube[t, :3] - dk.xpos[s.gripper]) - s.grasp_point
+ return out
+
+
+def conv_variants(cfg):
+ """Physics settings of the convergence check: the chosen step, twice (if it divides the record step) and half of
+ it, the tight solver, and the reference (a quarter of the step with the tight solver)."""
+ dt, tight = cfg["physics"]["timestep_s"], cfg["tight_solver"]
+ out = {"chosen": {}, "double_step": {"timestep_s": 2 * dt}, "half_step": {"timestep_s": dt / 2},
+ "tight_solver": dict(tight), "reference": {"timestep_s": dt / 4, **tight}}
+ ratio = cfg["record_step_s"] / (2 * dt)
+ if abs(ratio - round(ratio)) > 1e-9:
+ del out["double_step"]
+ return out
+
+
+_CONV = None
+
+
+def _conv_init(cfg_path):
+ global _CONV
+ cfg = load_config(cfg_path)
+ _CONV = cfg, {k: Scene(cfg, v) for k, v in conv_variants(cfg).items()}
+
+
+def _conv_job(args):
+ """One episode planned and run at the chosen step, its commands replayed with every variant -> row."""
+ fam_index, index = args
+ cfg, scenes = _CONV
+ s = scenes["chosen"]
+ fam = cfg["families"][fam_index]
+ rng = np.random.default_rng(episode_seed(cfg["convergence"]["master_seed"], fam_index, index))
+ n_rec = int(fam["records"])
+ while True:
+ try:
+ plan = FAMILIES[fam["name"]](s, rng, (n_rec - 1) // s.per_ctrl + 1)
+ except PlanError:
+ continue
+ rec = run_episode(s, plan, n_rec)
+ if not isinstance(rec, str):
+ break
+ if rec is None:
+ return dict(family=fam["name"], index=index, rejected=True)
+ actions, phases = rec["action"], rec["per_record"]["phase"]
+ runs = {k: replay(sc, plan, actions) for k, sc in scenes.items()}
+ ref_arm, ref_cube, ref_con, _ = runs["reference"]
+ n, rec_dt = len(actions), cfg["record_step_s"]
+ marks = {}
+ close = np.flatnonzero(phases == P["close"])
+ for sec in ((0.2, 0.5, 1.0) if len(close) else ()):
+ marks[f"close+{sec:g}s"] = int(close[0]) + round(sec / rec_dt)
+ hold = np.flatnonzero(phases == P["hold"])
+ if len(hold):
+ marks["hold_end"] = int(hold[np.argmax(np.diff(hold) > 1)] if (np.diff(hold) > 1).any() else hold[-1])
+ free = ~ref_con.any(1)
+ for k in range(3, len(ref_con)): # the first landing of a falling cube
+ if ref_con[k, 2] and free[k - 3:k].all() and ref_cube[k, 9] < -0.3:
+ marks["landing+50ms"] = k + round(0.05 / rec_dt)
+ break
+ marks = {k: v for k, v in marks.items() if v < n}
+ group = fam["group"]
+ energy_args = s.m.body_mass[s.cube_body], s.m.body_inertia[s.cube_body, 0], s.m.opt.gravity[2]
+ row = dict(family=fam["name"], index=index, records=n, terminal=TERMINAL[rec["terminal"]], marks=marks,
+ determinism_max_abs=float(max(np.abs(runs["chosen"][0] - rec["states"]["arm"]).max(),
+ np.abs(runs["chosen"][1] - rec["states"]["cube"]).max())))
+ for k, (arm, cube, con, depth) in runs.items():
+ v = dict(depth_mm=(depth * 1000).tolist(), labels_differ=(con != ref_con).sum(0).tolist(),
+ impacts=impacts(con, cube, cube_energy(cube, *energy_args)))
+ if k != "reference":
+ v["errors"] = {name: dict(
+ cube_pos_mm=float(np.linalg.norm(cube[t, :3] - ref_cube[t, :3]) * 1000),
+ cube_angle_deg=float(np.degrees(2 * np.arccos(min(1.0, abs(cube[t, 3:7] @ ref_cube[t, 3:7]))))),
+ cube_w_rad_s=float(np.linalg.norm(cube[t, 10:13] - ref_cube[t, 10:13])),
+ joint_max_mrad=float(np.abs(arm[t, :6] - ref_arm[t, :6]).max() * 1000)) for name, t in marks.items()}
+ v["timing"] = timing_errors(con, ref_con, rec_dt)
+ if group != "probe":
+ ep = dict(contacts=con, states={"cube": cube},
+ per_record=dict(phase=phases, cube_in_grasp=grasp_frame(s, arm, cube)))
+ o = outcome(ep, s.half, group)
+ v.update(outcome=OUTCOMES[o["outcome"]], carry_slip_mm=o["carry_slip_mm"])
+ row[k] = v
+ return row
+
+
+def convergence(cfg, out=None, workers=1, scale=1.0, cfg_path=CONFIG):
+ """Episodes of every family (counts in the config's ``convergence`` block, times ``scale``) simulated at the
+ chosen step; their recorded commands replayed open loop with the other settings and compared with the reference.
+ Per variant: cube and joint errors at marks (0.2 / 0.5 / 1 s after the jaw starts to close, the end of the first
+ hold, 50 ms after the first landing of a falling cube), contact onset/offset timing and label differences of the
+ three pairs, energy change in cube-table impacts, deepest penetration, grasp outcome and cube slip while
+ carried."""
+ names = [f["name"] for f in cfg["families"]]
+ jobs = [(names.index(name), i) for name, count in cfg["convergence"]["episodes"].items()
+ for i in range(max(1, int(round(count * scale))))]
+ for v in conv_variants(cfg).values(): # fail here, not in the worker initializers
+ Scene(cfg, v)
+ with mp.get_context("spawn").Pool(workers, initializer=_conv_init, initargs=(str(cfg_path),)) as pool:
+ rows = pool.map(_conv_job, jobs, chunksize=1)
+ rejected = [r for r in rows if r.get("rejected")]
+ rows = [r for r in rows if not r.get("rejected")]
+ variants = conv_variants(cfg)
+ report = {"variants": variants, "episodes": len(rows), "rejected_numerical": len(rejected),
+ "summary": {"all": convergence_summary(rows, variants),
+ "families": {f: convergence_summary([r for r in rows if r["family"] == f], variants)
+ for f in cfg["convergence"]["episodes"]}},
+ "rows": rows}
+ if out:
+ Path(out).parent.mkdir(parents=True, exist_ok=True)
+ Path(out).write_text(json.dumps(report, indent=1) + "\n")
+ return report
+
+
+def timing_errors(a, b, dt, reach=25):
+ """Onsets and offsets of two [T-1, P] label arrays: each event of ``a`` matched to the nearest unmatched event of
+ the same kind in ``b`` within ``reach`` records -> per pair the matched time differences (ms), the events of
+ either run left unmatched (short flickers of grazing contacts) and the events of ``b``."""
+ out = {}
+ for p, name in enumerate(PAIRS):
+ ea, eb = (np.diff(np.r_[0, x[:, p].astype(int)]) for x in (a, b))
+ dts, unmatched = [], 0
+ for kind in (1, -1):
+ ia, ib = list(np.flatnonzero(ea == kind)), list(np.flatnonzero(eb == kind))
+ for k in ia:
+ j = min(ib, key=lambda x: abs(x - k), default=None)
+ if j is not None and abs(j - k) <= reach:
+ dts.append(float(abs(j - k) * dt * 1000))
+ ib.remove(j)
+ else:
+ unmatched += 1
+ unmatched += len(ib)
+ out[name] = dict(dt_ms=dts, unmatched=unmatched, events_b=int((eb != 0).sum()))
+ return out
+
+
+def _stats(x):
+ x = np.asarray(x, float)
+ return dict(n=int(len(x)), median=float(np.median(x)), p95=float(np.quantile(x, 0.95)),
+ max=float(x.max())) if len(x) else None
+
+
+def convergence_summary(rows, variants):
+ """Per variant: error statistics at each mark; per pair the matched timing, the share of reference events
+ matched within 20 ms, unmatched events and label differences; impacts that gained energy; deepest penetration;
+ outcomes that differ from the reference and the carry slip."""
+ out = {}
+ if not rows:
+ return out
+ for v in variants:
+ rs = [r[v] for r in rows]
+ e = {}
+ if v != "reference":
+ for mark in sorted({m for r in rows for m in r["marks"]}):
+ for key in ("cube_pos_mm", "cube_angle_deg", "cube_w_rad_s", "joint_max_mrad"):
+ e[f"{mark} {key}"] = _stats([x["errors"][mark][key] for x in rs if mark in x["errors"]])
+ for p in PAIRS:
+ d = np.concatenate([x["timing"][p]["dt_ms"] for x in rs] + [np.zeros(0)])
+ events = sum(x["timing"][p]["events_b"] for x in rs)
+ e[f"{p} timing_ms"] = _stats(d)
+ e[f"{p} reference_events"] = int(events)
+ e[f"{p} within_20ms"] = float((d <= 20 + 1e-6).sum() / max(events, 1))
+ e[f"{p} unmatched_events"] = int(sum(x["timing"][p]["unmatched"] for x in rs))
+ intervals = sum(r["records"] - 1 for r in rows)
+ for q, p in enumerate(PAIRS):
+ e[f"{p} labels_differ_per_1000"] = 1000 * sum(x["labels_differ"][q] for x in rs) / intervals
+ e[f"{p} depth_mm"] = _stats([x["depth_mm"][q] for x in rs if x["depth_mm"][q] > 0])
+ gains = np.array([g for x in rs for _, g in x["impacts"] if g is not None] + [-np.inf])
+ e["impacts"] = {"bounces": int(len(gains) - 1), "energy_gain_above_0.1_mj": int((gains > 1e-4).sum()),
+ "largest_change_mj": float(gains.max() * 1000) if len(gains) > 1 else None}
+ slip = [x["carry_slip_mm"] for x in rs if "carry_slip_mm" in x and np.isfinite(x["carry_slip_mm"])]
+ if slip:
+ e["carry_slip_mm"] = _stats(slip)
+ e["outcome_differs"] = int(sum(x["outcome"] != r["reference"]["outcome"] for x, r in zip(rs, rows)
+ if "outcome" in x))
+ e["determinism_max_abs"] = float(max(r["determinism_max_abs"] for r in rows))
+ out[v] = e
+ return out
+
+
+# ---- rendering -------------------------------------------------------------------------------------------------
+def render(cfg, data_dir, episodes, out_dir, fps=50, size=(480, 640)):
+ """Videos of recorded episodes: the stored states (arm angles, cube pose) shown with the scene."""
+ import imageio
+ s = Scene(cfg)
+ with np.load(Path(data_dir) / "unified_data.npz") as f:
+ arrays = {k: f[k] for k in ("arm", "cube", "lengths", "family", "contacts")}
+ system = json.loads((Path(data_dir) / "system.json").read_text())
+ out_dir = Path(out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ m, d = s.m, mujoco.MjData(s.m)
+ s.m.vis.global_.offwidth, s.m.vis.global_.offheight = size[1], size[0]
+ renderer = mujoco.Renderer(m, size[0], size[1])
+ cam = mujoco.MjvCamera()
+ cam.lookat[:] = [0.2, 0.0, 0.05]
+ cam.distance, cam.azimuth, cam.elevation = 0.75, 145, -25
+ paths = []
+ for i in episodes:
+ name = system["families"][int(arrays["family"][i])]["name"]
+ path = out_dir / f"episode{i:05d}_{name}.mp4"
+ step = round(1 / fps / system["record_step_s"])
+ with imageio.get_writer(path, fps=fps, macro_block_size=1) as w:
+ for k in range(0, int(arrays["lengths"][i]), step):
+ d.qpos[s.qadr] = arrays["arm"][i, k, :6]
+ d.qpos[s.cq: s.cq + 7] = arrays["cube"][i, k, :7]
+ mujoco.mj_forward(m, d)
+ renderer.update_scene(d, cam)
+ w.append_data(renderer.render())
+ paths.append(str(path))
+ renderer.close()
+ return paths
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--config", type=Path, default=CONFIG)
+ sub = parser.add_subparsers(dest="cmd", required=True)
+ c = sub.add_parser("collect", help="simulate the families and write a data directory")
+ c.add_argument("--out", type=Path, required=True)
+ c.add_argument("--workers", type=int)
+ c.add_argument("--campaign", choices=("pilot", "production", "test", "extra", "noisy_v1"), default="pilot",
+ help="master seed and episode counts from the config's campaigns block; pilot and production: "
+ "splits 0/1 by family; test: all split 2")
+ c.add_argument("--chunk", type=int, default=16, help="episodes per pool task and shard file")
+ c.add_argument("--families", nargs="*", help="only these families")
+ c.add_argument("--scale", type=float, help="replace the campaign's task and probe factors (smoke runs)")
+ c.add_argument("--probe-scale", type=float, help="replace the campaign's probe factor")
+ v = sub.add_parser("convergence", help="physics-step and solver convergence on episodes of every family")
+ v.add_argument("--out", type=Path, required=True)
+ v.add_argument("--workers", type=int)
+ v.add_argument("--scale", type=float, default=1.0, help="multiply the episode counts of the convergence block")
+ r = sub.add_parser("report", help="terminations, outcomes, slip, force histogram and label flips of a directory")
+ r.add_argument("data", type=Path)
+ w = sub.add_parser("render", help="videos of recorded episodes")
+ w.add_argument("data", type=Path)
+ w.add_argument("--episodes", type=int, nargs="+", required=True)
+ w.add_argument("--out", type=Path)
+ args = parser.parse_args()
+ cfg = load_config(args.config)
+ if args.cmd == "collect":
+ collect(cfg, args.out, args.workers or cfg["workers"], args.campaign, args.families, args.scale,
+ args.probe_scale, args.chunk, args.config)
+ elif args.cmd == "convergence":
+ report = convergence(cfg, args.out, args.workers or cfg["workers"], args.scale, args.config)
+ print(json.dumps(report["summary"]["all"], indent=1))
+ elif args.cmd == "report":
+ system = json.loads((args.data / "system.json").read_text())
+ with np.load(args.data / "unified_data.npz") as f:
+ arrays = {k: f[k] for k in f.files}
+ print(json.dumps(summarize(system, arrays), indent=1))
+ else:
+ print("\n".join(render(cfg, args.data, args.episodes, args.out or args.data / "videos")))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/src/nedm/contact_nrd/collect/validate.py b/so101_pick_place/code/src/nedm/contact_nrd/collect/validate.py
new file mode 100644
index 0000000000000000000000000000000000000000..994a86b51f6c76e3cc7dadd1d03ba6e308f0c4f8
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/contact_nrd/collect/validate.py
@@ -0,0 +1,299 @@
+"""Check a contact NRD data directory against the collection contract and count what training needs.
+
+ python -m nedm.contact_nrd.collect.validate DIR [--output report.json]
+
+Hard checks (exit code 1 if one fails): array shapes and dtypes, finite valid records, unit and sign-continuous
+quaternions, 0/1 contacts, the padding rule, commands constant inside each control period. Frame check: the
+step-average rates computed from the poses (as contact NRD training does) are compared with the mean of the
+recorded instantaneous rates at both ends of the step; a large relative error points to a wrong frame (body instead
+of world angular velocity), a wrong channel order or a time shift. It uses up to 400 evenly spaced episodes of the
+families that are not core-only (rate_consistency; the same episodes as without core-only families) and up to 400
+core-only episodes apart (rate_consistency_core_only). Coverage (the windows contact NRD training
+draws, with its labels: contact in the step or in the step before): contact-free windows of each moving body
+(all, and on the core grid of train.py: every free_phase_step-th record),
+windows with exactly one active pair (per pair), contact onsets, by family and split. Families with
+"use": "core_only" (train.py: core only) are counted apart: the split blocks count the other families as before and
+add core_only_* counts (contact-free and core-grid windows only; core_fit_ = what the core fit draws from), and
+a core-only family block has only its contact-free counts. A core-only family must have select: false; its episodes
+need a branch_start [N] array (the branch record) with no contact label from it on. numpy only.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+import numpy as np
+
+POSE_TYPES = {"position": 0, "angle": 0, "quaternion": 1, "velocity": 2, "angular_rate": 2, "angular_velocity": 3}
+
+
+def window_labels(contacts, stride):
+ """[N, T-1, P] interval labels -> [N, T-stride, P]: pair in contact during the step starting at each record."""
+ c = contacts.astype(np.int32)
+ cum = np.concatenate((np.zeros_like(c[:, :1]), c.cumsum(1)), 1)
+ return (cum[:, stride:] - cum[:, :-stride]) > 0
+
+
+def training_windows(system, contacts, lengths, splits):
+ """The labels and window masks of contact NRD training (train.py): labels [N, W, P] (step or step before),
+ involved [N, W, D] (body touched now or in the record interval before), valid [N, W] (command grid)."""
+ stride = round(system["model_step_s"] / system["record_step_s"])
+ lab = window_labels(contacts, stride)
+ spread = np.zeros_like(lab)
+ spread[:, stride:] = lab[:, :-stride]
+ lab = lab | spread
+ n, w, p = lab.shape
+ prev = np.concatenate((np.zeros_like(lab[:, :1]), window_labels(contacts, 1)[:, : w - 1]), 1)
+ after = prev & ~lab
+ touched = lab | after
+ moving = [k for k, b in enumerate(system["bodies"]) if b["moving"]]
+ slot = {k: s for s, k in enumerate(moving)}
+ involved = np.zeros((n, w, len(moving)), bool)
+ for q, (i, j) in enumerate(system["pairs"]):
+ involved[..., slot[i]] |= touched[..., q]
+ if j in slot:
+ involved[..., slot[j]] |= touched[..., q]
+ acting = any(int(b.get("action_dim", 0)) for b in system["bodies"] if b["moving"])
+ grid = (np.arange(w) % stride == 0) if acting else np.ones(w, bool)
+ valid = (np.arange(w)[None, :] < (lengths - stride)[:, None]) & grid[None, :]
+ return lab, involved, valid, stride
+
+
+def step_average(states, types, stride, dt):
+ """Rate channels from pose differences over one model step (as data.step_average_rates) -> [N, T-stride, k]."""
+ pc = [c for c, t in enumerate(types) if POSE_TYPES[t] == 0]
+ qc = [c for c, t in enumerate(types) if POSE_TYPES[t] == 1]
+ vc = [c for c, t in enumerate(types) if POSE_TYPES[t] == 2]
+ wc = [c for c, t in enumerate(types) if POSE_TYPES[t] == 3]
+ out = {}
+ if pc and len(pc) == len(vc):
+ out["linear"] = (vc, (states[:, stride:, pc] - states[:, :-stride, pc]) / dt)
+ if len(qc) == 4 and len(wc) == 3:
+ q1, q0 = states[:, stride:][..., qc].astype(np.float64), states[:, :-stride][..., qc].astype(np.float64)
+ w0, v0 = q0[..., :1], -q0[..., 1:]
+ w1, v1 = q1[..., :1], q1[..., 1:]
+ w = w1 * w0 - (v1 * v0).sum(-1, keepdims=True)
+ v = w1 * v0 + w0 * v1 + np.cross(v1, v0)
+ sign = np.where(w < 0, -1.0, 1.0)
+ w, v = w * sign, v * sign
+ nrm = np.linalg.norm(v, axis=-1, keepdims=True)
+ ang = 2 * np.arctan2(nrm, w)
+ rot = np.where(nrm > 1e-12, v / np.maximum(nrm, 1e-12) * ang, 2 * v)
+ out["angular"] = (wc, rot / dt)
+ return out
+
+
+def validate(root, max_frame_episodes=400):
+ root = Path(root)
+ system = json.loads((root / "system.json").read_text())
+ with np.load(root / "unified_data.npz") as f:
+ arrays = {k: f[k] for k in f.files}
+ fails, warns, report = [], [], {"dir": str(root), "system": system.get("name")}
+ moving = [b for b in system["bodies"] if b["moving"]]
+ lengths, splits, contacts = arrays["lengths"], arrays["splits"], arrays["contacts"]
+ n = len(lengths)
+ t_rec = int(system["records_per_episode"])
+ report["episodes"] = int(n)
+ report["valid_records"] = int(lengths.sum())
+ rec_dt = float(system["record_step_s"])
+ report["hours"] = float(((lengths - 1) * rec_dt).sum() / 3600)
+ try:
+ from nedm.contact_nrd.collect.export import check_arrays
+ check_arrays(system, arrays)
+ except ValueError as exc:
+ fails.append(f"shape: {exc}")
+ return dict(report, fails=fails, warns=warns, ok=False)
+ valid_rec = np.arange(t_rec)[None, :] < lengths[:, None] # [N, T]
+ if (lengths < 2).any() or (lengths > t_rec).any():
+ fails.append("lengths outside [2, records_per_episode]")
+ if not np.isin(contacts, (0, 1)).all():
+ fails.append("contacts are not 0/1")
+ pad_int = np.arange(t_rec - 1)[None, :] >= (lengths - 1)[:, None]
+ if contacts[pad_int].any():
+ fails.append("contacts after the last valid interval are not zero")
+ for b in moving:
+ x = arrays[b["name"]]
+ if x.dtype != np.float32:
+ warns.append(f"{b['name']}: dtype {x.dtype} (contract: float32)")
+ if not np.isfinite(x[valid_rec]).all():
+ fails.append(f"{b['name']}: non-finite values in valid records")
+ last = x[np.arange(n), lengths - 1]
+ if not np.array_equal(np.where(valid_rec[..., None], x, last[:, None]), x):
+ fails.append(f"{b['name']}: padding does not repeat the last valid record")
+ qc = [c for c, t in enumerate(b["channel_types"]) if t == "quaternion"]
+ if qc:
+ q = x[..., qc].astype(np.float64)
+ norm_err = np.abs(np.linalg.norm(q, axis=-1) - 1)[valid_rec]
+ report[f"{b['name']}_quat_norm_err_max"] = float(norm_err.max())
+ if norm_err.max() > 1e-4:
+ fails.append(f"{b['name']}: quaternion norm error {norm_err.max():.2e}")
+ dots = (q[:, 1:] * q[:, :-1]).sum(-1)[valid_rec[:, 1:]]
+ if (dots < 0).any():
+ fails.append(f"{b['name']}: quaternion sign flips ({int((dots < 0).sum())} records)")
+ if (q[:, 0, 0] < 0).any():
+ fails.append(f"{b['name']}: quaternion w < 0 at the first record")
+ if "action" in arrays:
+ act = arrays["action"]
+ if not np.isfinite(act[valid_rec]).all():
+ fails.append("action: non-finite values in valid records")
+ ctrl = system.get("control_step_s", system["model_step_s"])
+ per = round(ctrl / rec_dt)
+ if per > 1:
+ k = np.arange(1, t_rec)
+ inside = (k % per != 0)[None, :] & valid_rec[:, 1:]
+ changed = np.abs(act[:, 1:] - act[:, :-1]).max(-1) > 0
+ if (changed & inside).any():
+ fails.append(f"action changes inside a control period ({int((changed & inside).sum())} records)")
+ # families and the core-only rules
+ pair_names = [m.get("name", str(q)) for q, m in enumerate(system.get("pair_metadata", [{}] * len(system["pairs"])))]
+ fam = arrays.get("family")
+ fam_names = [f["name"] for f in system.get("families", [])]
+ if (fam is not None) != bool(fam_names):
+ fails.append("the family array and system.json families must come together")
+ elif fam is not None:
+ if fam.min() < 0 or fam.max() >= len(fam_names):
+ fails.append("family values outside the families list")
+ elif not all(isinstance(f.get("select"), bool) for f in system["families"]):
+ fails.append("every system.json family needs select: true or false")
+ else:
+ sel = np.array([f["select"] for f in system["families"]])
+ # test campaigns (split 2 only) and supplementary training folders (split 0 only, merged with a campaign
+ # that has the validation episodes) are exempt
+ if (splits == 1).any() and (splits == 0).any() and not (sel[fam] & (splits == 1)).any():
+ fails.append("no validation episode in a family with select: true (checkpoint selection needs them)")
+ uses = [f.get("use") for f in system.get("families", [])]
+ core_ep = np.zeros(n, bool)
+ if fam is not None and fam_names and fam.min() >= 0 and fam.max() < len(fam_names):
+ if set(uses) - {None, "core_only"}:
+ fails.append("family use must be absent or core_only")
+ if any(u == "core_only" and f.get("select") for u, f in zip(uses, system["families"])):
+ fails.append("a core-only family must have select: false")
+ core_ep = np.isin(fam, [k for k, u in enumerate(uses) if u == "core_only"])
+ if core_ep.any():
+ bs = arrays.get("branch_start")
+ if bs is None or bs.shape != (n,):
+ fails.append("core-only episodes need a branch_start [N] array")
+ else:
+ b = bs[core_ep].astype(np.int64)
+ if (b < 1).any() or (b >= lengths[core_ep]).any():
+ fails.append("branch_start of core-only episodes outside [1, length - 1]")
+ else:
+ after = np.arange(t_rec - 1)[None, :] >= b[:, None]
+ if contacts[core_ep][after].any():
+ fails.append("core-only episodes have contact labels from their branch_start on")
+ # frame check (relative RMS error of the step-average rates) on up to max_frame_episodes evenly spaced episodes
+ # of the families other than core-only ones (all episodes without them) and, apart, of the core-only families
+ stride = round(system["model_step_s"] / rec_dt)
+ dt = stride * rec_dt
+
+ def frame_check(ids, what=""):
+ pick = ids[np.linspace(0, len(ids) - 1, min(len(ids), max_frame_episodes)).round().astype(int)]
+ frame = {}
+ for b in moving:
+ x = arrays[b["name"]][pick].astype(np.float64)
+ ok = (np.arange(t_rec - stride)[None, :] < (lengths[pick] - stride)[:, None])
+ for kind, (cols, avg) in step_average(x, b["channel_types"], stride, dt).items():
+ if stride == 2: # Simpson: the midpoint record catches speed peaks inside a step
+ inst = (x[:, :-2, cols] + 4 * x[:, 1:-1, cols] + x[:, 2:, cols]) / 6
+ else:
+ inst = 0.5 * (x[:, stride:, cols] + x[:, :-stride, cols])
+ err = (avg - inst)[ok]
+ # relative to the largest channel RMS of the group: near-constant channels do not inflate the ratio
+ scale = np.sqrt((x[:, :, cols][valid_rec[pick]] ** 2).mean(0)).max() + 1e-9
+ rel = np.sqrt((err ** 2).mean(0)) / scale
+ frame[f"{b['name']}_{kind}"] = dict(channels=[b["channels"][c] for c in cols],
+ relative_rms=[round(float(r), 4) for r in rel])
+ if (rel > 0.5).any():
+ warns.append(f"{what}{b['name']} {kind}: step-average vs recorded rates differ (relative RMS up "
+ f"to {rel.max():.2f}); check frames, channel order and timing")
+ return frame, len(pick)
+ others = np.flatnonzero(~core_ep)
+ if len(others):
+ report["rate_consistency"], n_other = frame_check(others)
+ if core_ep.any():
+ report["rate_consistency_core_only"], n_core = frame_check(np.flatnonzero(core_ep), "core-only episodes: ")
+ report["rate_consistency_episodes"] = dict(other=n_other if len(others) else 0, core_only=n_core)
+ # coverage
+ lab, involved, valid, _ = training_windows(system, contacts, lengths, splits)
+ train_cfg = Path(__file__).resolve().parents[4] / "configs/contact_nrd/train.json"
+ free_phase_step = json.loads(train_cfg.read_text())["free_phase_step"] if train_cfg.exists() else 5
+
+ def counts(sel, core_only=False):
+ if not core_only:
+ sel = sel & ~core_ep # the other families, counted as without core-only episodes
+ v = valid & sel[:, None]
+ out = {"windows": int(v.sum())}
+ phase = (np.arange(v.shape[1]) % free_phase_step == 0)[None, :]
+ if core_only: # contact-free windows only: core-only windows are never contact or single-pair windows
+ for s, b in enumerate(moving):
+ out[f"free_{b['name']}"] = int((v & ~involved[..., s]).sum())
+ out[f"core_{b['name']}"] = int((v & phase & ~involved[..., s]).sum())
+ return out
+ for s, b in enumerate(moving):
+ out[f"free_{b['name']}"] = int((v & ~involved[..., s]).sum())
+ out[f"core_{b['name']}"] = int((v & phase & ~involved[..., s]).sum())
+ single = lab.sum(-1) == 1
+ for q, name in enumerate(pair_names):
+ out[f"single_{name}"] = int((v & single & lab[..., q]).sum())
+ out[f"on_{name}"] = int((v & lab[..., q]).sum())
+ out["multi_contact"] = int((v & (lab.sum(-1) >= 2)).sum())
+ c = contacts[sel].astype(bool)
+ onsets = (c[:, 1:] & ~c[:, :-1]).sum((0, 1)) + c[:, 0].sum(0)
+ out.update({f"onsets_{name}": int(onsets[q]) for q, name in enumerate(pair_names)})
+ return out
+
+ def block(sel):
+ out = counts(sel)
+ if (sel & core_ep).any():
+ extra = counts(sel & core_ep, core_only=True)
+ out["core_only_episodes"] = int((sel & core_ep).sum())
+ out.update({f"core_only_{k}": v for k, v in extra.items()})
+ out.update({f"core_fit_{b['name']}": out[f"core_{b['name']}"] + extra[f"core_{b['name']}"] for b in moving})
+ return out
+ report["coverage"] = {"all": block(np.ones(n, bool))}
+ for s in (0, 1, 2):
+ if (splits == s).any():
+ report["coverage"][f"split{s}"] = block(splits == s)
+ if fam is not None and fam_names:
+ for f, name in enumerate(fam_names):
+ sel = fam == f
+ if sel.any():
+ core_fam = uses[f] == "core_only" if f < len(uses) else False
+ report["coverage"][f"family_{name}"] = dict(episodes=int(sel.sum()),
+ hours=float(((lengths[sel] - 1) * rec_dt).sum() / 3600),
+ **({"use": "core_only"} if core_fam else {}),
+ **counts(sel, core_only=core_fam))
+ if "terminal_reason" in arrays and "terminal_reasons" in system:
+ tr = arrays["terminal_reason"]
+ report["terminal_reasons"] = {name: int((tr == k).sum()) for k, name in enumerate(system["terminal_reasons"])}
+ train = report["coverage"].get("split0", {})
+ for s, b in enumerate(moving):
+ core_fit = train.get(f"core_fit_{b['name']}", train.get(f"core_{b['name']}", 0)) if train else 0
+ if train and core_fit < 1000:
+ warns.append(f"{b['name']}: only {core_fit} contact-free training windows on the core grid (every "
+ "free_phase_step-th record, as train.py draws them; core-only families included)")
+ for name in pair_names:
+ if train and train.get(f"single_{name}", 0) < 20:
+ warns.append(f"pair {name}: only {train.get('single_' + name, 0)} single-pair training windows "
+ "(the contact fit skips pairs with fewer than 20)")
+ report.update(fails=fails, warns=warns, ok=not fails)
+ return report
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("data", type=Path)
+ parser.add_argument("--output", type=Path)
+ args = parser.parse_args()
+ report = validate(args.data)
+ text = json.dumps(report, indent=1)
+ if args.output:
+ args.output.write_text(text + "\n")
+ print(text)
+ sys.exit(0 if report["ok"] else 1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/src/nedm/render/__init__.py b/so101_pick_place/code/src/nedm/render/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c89ee62e3d3b30017a03470327b634cb7ed80e74
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/__init__.py
@@ -0,0 +1,43 @@
+"""Batch rendering for NRD rollouts: one image per world, every step, on the GPU.
+
+ scene = Scene.from_urdf("go2.urdf").add_ground()
+ renderer = BatchRenderer(scene, num_worlds=1024, width=128, height=128)
+ frames = renderer.render(cameras.follow(xy), joint_q=joint_q)
+ frames.depth_torch() # (1024, 1, 128, 128), on the device, no copy
+
+The scene, poses and cameras need only torch and trimesh. The drawing is done by a backend,
+``BatchRenderer(..., backend="newton")`` (Newton / Warp), imported when a renderer is built.
+"""
+
+from nedm.render import cameras
+from nedm.render.poses import (
+ JointMap,
+ PlanarPose,
+ base_transform,
+ compose,
+ quat_from_rpy,
+ tilt_from_gravity,
+ transform_from_matrix,
+)
+from nedm.render.renderer import BatchRenderer
+from nedm.render.scene import Ground, MeshBody, Scene
+from nedm.render.video import CollageRecorder, depth_to_gray, grid, save_sheet
+
+__all__ = [
+ "BatchRenderer",
+ "CollageRecorder",
+ "Ground",
+ "JointMap",
+ "MeshBody",
+ "PlanarPose",
+ "Scene",
+ "base_transform",
+ "cameras",
+ "compose",
+ "depth_to_gray",
+ "grid",
+ "quat_from_rpy",
+ "save_sheet",
+ "tilt_from_gravity",
+ "transform_from_matrix",
+]
diff --git a/so101_pick_place/code/src/nedm/render/backends/__init__.py b/so101_pick_place/code/src/nedm/render/backends/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1052738174b854908521e5a62bfa4ff9259a423
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/backends/__init__.py
@@ -0,0 +1,17 @@
+"""Renderer backends. Each draws a :class:`~nedm.render.scene.Scene` for many worlds at once.
+
+A backend is constructed with the scene and the image settings, and has one method:
+``render(body_q, camera)`` with body transforms (N, bodies, 7) and camera transforms
+(N, cameras, 7), both ``xyzw`` and both torch tensors, returning a :class:`Frames`.
+"""
+
+from __future__ import annotations
+
+BACKENDS = ("newton",) # the study's Madrona backend is not part of this release (so101-pick-place-study)
+
+
+def make(name: str):
+ if name == "newton":
+ from nedm.render.backends.newton import NewtonBackend
+ return NewtonBackend
+ raise ValueError(f"unknown renderer backend {name!r}, choose from {BACKENDS}")
diff --git a/so101_pick_place/code/src/nedm/render/backends/newton.py b/so101_pick_place/code/src/nedm/render/backends/newton.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5eb62a1bab74460f14b0d723b4ea5e9f3d26376
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/backends/newton.py
@@ -0,0 +1,290 @@
+"""Newton's Warp ray tracer, used as a renderer only.
+
+Newton holds the scene (one copy of the bodies per world, plus what every world shares) and
+the cameras. No solver is created and nothing is simulated. It is pure Warp kernels, so it
+runs wherever Warp does: NVIDIA through the stock wheel, AMD Instinct through AMD's ROCm
+port, and CPU. Apache-2.0, as are Newton and Warp.
+"""
+
+from __future__ import annotations
+
+import math
+import warnings
+from typing import Any, Sequence
+
+import numpy as np
+
+# where a ray of an invalid pixel starts (camera frame, m): far behind the camera, pointing away from everything
+INVALID_RAY_ORIGIN = 1.0e4
+LIGHT_TYPES = {"spot": 0, "directional": 1, "point": 2} # 2: Newton's point-light branch (any id but 0 and 1)
+_KERNELS: dict = {}
+
+
+def _mask_kernel():
+ """Warp kernel: colour black (alpha 255) and depth 0 at the invalid pixels of every world."""
+ if "mask" not in _KERNELS:
+ import warp as wp
+
+ @wp.kernel(enable_backward=False)
+ def mask_invalid(valid: wp.array3d(dtype=wp.int32), color: wp.array4d(dtype=wp.uint32),
+ depth: wp.array4d(dtype=wp.float32)):
+ w, c, y, x = wp.tid()
+ if valid[c, y, x] == 0:
+ color[w, c, y, x] = wp.uint32(0xFF000000)
+ depth[w, c, y, x] = 0.0
+
+ _KERNELS["mask"] = mask_invalid
+ return _KERNELS["mask"]
+
+
+class Frames:
+ """The images of one render call. Views into the renderer's buffers: copy to keep them."""
+
+ def __init__(self, color, depth, hdr=None, shape_index=None):
+ self._color, self._depth, self._hdr, self._shape_index = color, depth, hdr, shape_index
+
+ def hdr_torch(self):
+ """(N, C, H, W, 3) float32 linear colour before the 8-bit clamp, on the render device (``hdr=True`` only)."""
+ import warp as wp
+ if self._hdr is None:
+ raise RuntimeError("build the renderer with hdr=True")
+ h = wp.to_torch(self._hdr)
+ return h.reshape(*h.shape[:4], 3)
+
+ @property
+ def rgb(self) -> np.ndarray:
+ """(N, C, H, W, 3) uint8."""
+ c = self._color.numpy()
+ return c.view(np.uint8).reshape(*c.shape, 4)[..., :3]
+
+ @property
+ def depth(self) -> np.ndarray:
+ """(N, C, H, W) float32, distance along the ray in metres, 0 where nothing was hit."""
+ return self._depth.numpy()
+
+ def rgb_torch(self):
+ """(N, C, H, W, 3) uint8 on the render device, zero-copy."""
+ import torch
+ import warp as wp
+ c = wp.to_torch(self._color)
+ return c.view(torch.uint8).reshape(*c.shape, 4)[..., :3]
+
+ def depth_torch(self):
+ """(N, C, H, W) float32 on the render device, zero-copy."""
+ import warp as wp
+ return wp.to_torch(self._depth)
+
+ def shape_index_torch(self):
+ """(N, C, H, W) int64 Newton shape index per pixel (-1: nothing hit), on the render device (``segment=True``
+ only)."""
+ import torch
+ import warp as wp
+ if self._shape_index is None:
+ raise RuntimeError("build the renderer with segment=True")
+ s = wp.to_torch(self._shape_index).view(torch.int32).long()
+ return torch.where(s < 0, torch.full_like(s, -1), s) # 0xFFFFFFFF (no hit) -> -1
+
+
+class NewtonBackend:
+ """``camera_models``: None (every camera a pinhole of ``fov_deg``: Newton's own rays, the original behaviour) or one
+ model per camera (:class:`~nedm.render.cameras.PinholeCamera` / :class:`~nedm.render.cameras.CalibratedCamera`);
+ pixels without a ray in their model are drawn black with depth 0 (:attr:`valid`). ``hdr``: also keep the linear
+ colour before the 8-bit clamp (:meth:`Frames.hdr_torch`). ``segment``: also keep Newton's shape index per pixel
+ (:meth:`Frames.shape_index_torch`; :attr:`shape_body` maps it to the body index of the scene, statics after the
+ bodies)."""
+
+ def __init__(self, scene, num_worlds: int, width: int, height: int, cameras: int, fov_deg: float,
+ device: Any, shadows: bool, sky: tuple[int, int, int], camera_models: Sequence | None = None,
+ hdr: bool = False, segment: bool = False) -> None:
+ import newton
+ import warp as wp
+ from newton.sensors import SensorTiledCamera
+ self._wp, self._newton = wp, newton
+ self.num_worlds, self.cameras, self.num_bodies = int(num_worlds), int(cameras), len(scene.bodies)
+
+ bodies = newton.ModelBuilder()
+ for body in scene.bodies:
+ vertices, faces = body.arrays()
+ bodies.add_shape_mesh(bodies.add_body(label=body.name), mesh=newton.Mesh(vertices, faces.reshape(-1)),
+ color=body.color)
+ b = newton.ModelBuilder()
+ for _ in range(self.num_worlds):
+ b.begin_world()
+ b.add_builder(bodies)
+ b.end_world()
+ if scene.ground is not None: # shared by every world
+ ground = scene.ground
+ b.add_ground_plane(height=ground.height, color=ground.color)
+ half = (ground.tile_size or 0.0) / 2
+ for center in ground.tile_centers():
+ b.add_shape_box(-1, xform=wp.transform(wp.vec3(*center), wp.quat_identity()),
+ hx=half, hy=half, hz=ground.tile_thickness / 2, color=ground.tile_color)
+ for mesh, xf in scene.statics:
+ vertices, faces = mesh.arrays()
+ b.add_shape_mesh(-1, xform=wp.transform(wp.vec3(*xf[:3]), wp.quat(*xf[3:])),
+ mesh=newton.Mesh(vertices, faces.reshape(-1)), color=mesh.color)
+ self.model = b.finalize(device=device)
+ self.state = self.model.state()
+ self.device = self.model.device
+
+ self._camera = SensorTiledCamera(model=self.model)
+ self._camera.utils.create_default_light(enable_shadows=shadows)
+ self.width, self.height, self.fov_deg = int(width), int(height), float(fov_deg)
+ self.camera_models = None
+ self.valid = None # (C, H, W) bool numpy; None: pinholes of fov_deg (every pixel has a ray)
+ self._valid = None # its int32 Warp copy, only when some pixel is invalid
+ self._ray_cache: dict = {} # camera-model key -> (rays, valid, valid int32, ray_z): intrinsics DR per call
+ if camera_models is None:
+ self._rays = self._camera.utils.compute_pinhole_camera_rays(width, height,
+ [math.radians(fov_deg)] * self.cameras)
+ else:
+ self.set_camera_models(camera_models)
+ self._color = self._camera.utils.create_color_image_output(width, height, self.cameras)
+ self._depth = self._camera.utils.create_depth_image_output(width, height, self.cameras)
+ self._hdr = self._camera.utils.create_hdr_color_image_output(width, height, self.cameras) if hdr else None
+ self._shape_index = None
+ if segment:
+ self._shape_index = self._camera.utils.create_shape_index_image_output(width, height, self.cameras)
+ sb = self.model.shape_body.numpy()
+ nb = self.num_bodies
+ lut = np.empty(len(sb), np.int64)
+ statics = 0
+ for k, b in enumerate(sb): # bodies are world-major: global body = world * nb + local
+ if b >= 0:
+ lut[k] = int(b) % nb
+ else:
+ lut[k] = nb + statics
+ statics += 1
+ self.shape_body = lut # Newton shape index -> scene body index (statics: nb + k)
+ r, g, bl = sky
+ self._clear = SensorTiledCamera.ClearData(clear_color=0xFF000000 | (bl << 16) | (g << 8) | r)
+ self._camera_xf = wp.zeros((self.cameras, self.num_worlds), dtype=wp.transformf, device=self.device)
+ self._bvh_built = False
+ self.interop: str | None = None # "zero-copy" or "host-copy"
+
+ def render(self, body_q, camera) -> Frames:
+ self._put(self.state.body_q, body_q.reshape(self.num_worlds * self.num_bodies, 7))
+ self._put(self._camera_xf, camera.transpose(0, 1))
+ geometry = self._newton.geometry
+ if self._bvh_built:
+ geometry.refit_bvh_shape(self.model, self.state)
+ else:
+ geometry.build_bvh_shape(self.model, self.state)
+ self._bvh_built = True
+ if self._hdr is None and self._shape_index is None: # the original call, unchanged
+ self._camera.update(self.state, self._camera_xf, self._rays, color_image=self._color,
+ depth_image=self._depth, clear_data=self._clear)
+ else:
+ self._camera.update(self.state, self._camera_xf, self._rays, color_image=self._color,
+ depth_image=self._depth, clear_data=self._clear, hdr_color_image=self._hdr,
+ shape_index_image=self._shape_index)
+ if self._valid is not None:
+ self._wp.launch(_mask_kernel(), dim=(self.num_worlds, self.cameras, self.height, self.width),
+ inputs=[self._valid, self._color, self._depth], device=self.device)
+ self._wp.synchronize()
+ return Frames(self._color, self._depth, self._hdr, self._shape_index)
+
+ # ---- camera models -------------------------------------------------------------------------------------------
+ RAY_CACHE = 16 # ray sets kept on the device (2 cameras x 448 x 448: 9.6 MB each)
+
+ def set_camera_models(self, models: Sequence) -> None:
+ """One camera model per camera (rays shared by all worlds; call again to change intrinsics between calls).
+ Pinholes get Newton's own pinhole rays (their own fov each); calibrated cameras get their undistorted rays.
+ The last :attr:`RAY_CACHE` ray sets are kept, so cycling through a few intrinsics draws costs no ray
+ computation after the first use of each."""
+ models = list(models)
+ if len(models) != self.cameras:
+ raise ValueError(f"{len(models)} camera models for {self.cameras} cameras")
+ key = tuple(repr(m) for m in models)
+ hit = self._ray_cache.get(key)
+ if hit is None:
+ hit = self._compute_rays(models)
+ if len(self._ray_cache) >= self.RAY_CACHE:
+ self._ray_cache.pop(next(iter(self._ray_cache)))
+ self._ray_cache[key] = hit
+ self._rays, self.valid, self._valid, self.ray_z = hit
+ self.camera_models = models
+
+ def _compute_rays(self, models):
+ from nedm.render.cameras import camera_rays
+ wp = self._wp
+ fovs = [math.radians(m.fovy_deg) if m.kind == "pinhole" else 1.0 for m in models]
+ rays = self._camera.utils.compute_pinhole_camera_rays(self.width, self.height, fovs)
+ dirs, valid = camera_rays(models, self.width, self.height)
+ custom = [c for c, m in enumerate(models) if m.kind != "pinhole"]
+ if custom:
+ r = rays.numpy() # (C, H, W, 2, 3): origin, direction
+ for c in custom:
+ ok = valid[c]
+ r[c, :, :, 0] = np.where(ok[..., None], 0.0, np.array([0.0, 0.0, INVALID_RAY_ORIGIN]))
+ r[c, :, :, 1] = np.where(ok[..., None], dirs[c], np.array([0.0, 0.0, 1.0]))
+ rays = wp.array(r.astype(np.float32), dtype=wp.vec3f, device=self.device)
+ valid_wp = None if valid.all() else wp.array(valid.astype(np.int32), dtype=wp.int32, device=self.device)
+ # z-depth per unit ray length (camera -z component of the unit ray), 0 at invalid pixels
+ ray_z = np.where(valid, -dirs[..., 2], 0.0).astype(np.float32)
+ return rays, valid, valid_wp, ray_z
+
+ # ---- lights (shared by all worlds: Newton has no per-world lights) -------------------------------------------
+ def set_lights(self, lights: Sequence[dict], shadows: bool | None = None, ambient: bool | None = None) -> None:
+ """Replace the lights. Each light: ``{"type": "directional" | "spot" | "point", "direction": (3,) (the way the
+ light travels; directional and spot), "position": (3,) (spot, point), "shadow": bool}``. Newton lights have no
+ intensity or colour (each adds albedo * max(0, n.L), spot/point times 1/(1 + 0.02 d^2)). ``shadows``: the
+ global shadow switch; ``ambient``: Newton's fixed hemispheric ambient term on/off.
+
+ A directional light may carry ``"intensity"`` w in (0, 1) (and ``"center"`` (3,), default the origin): it is
+ drawn as a POINT light at distance d = sqrt((1/w - 1) / 0.02) m from ``center``, against the light's direction,
+ whose attenuation 1/(1 + 0.02 d^2) is w there (an approximation: over +-0.25 m around ``center`` the direction
+ varies by atan(0.25/d) and the intensity by about +-0.5 d / (d^2 + 50) relative; d = 7.1 m at w = 0.5)."""
+ wp = self._wp
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ rc = self._camera.render_context
+ lights = [self._dimmed(dict(lt)) for lt in lights]
+ n = len(lights)
+ if n == 0:
+ rc.lights_active = None
+ else:
+ dev = self.device
+ rc.lights_active = wp.array([True] * n, dtype=wp.bool, device=dev)
+ rc.lights_type = wp.array([LIGHT_TYPES[lt.get("type", "directional")] for lt in lights], dtype=wp.int32,
+ device=dev)
+ rc.lights_cast_shadow = wp.array([bool(lt.get("shadow", True)) for lt in lights], dtype=wp.bool,
+ device=dev)
+ pos = [np.asarray(lt.get("position", (0.0, 0.0, 0.0)), float) for lt in lights]
+ way = [np.asarray(lt.get("direction", (0.0, 0.0, -1.0)), float) for lt in lights]
+ rc.lights_position = wp.array([wp.vec3f(*p) for p in pos], dtype=wp.vec3f, device=dev)
+ rc.lights_orientation = wp.array([wp.vec3f(*(d / np.linalg.norm(d))) for d in way], dtype=wp.vec3f,
+ device=dev)
+ if shadows is not None:
+ self._camera.render_config.enable_shadows = bool(shadows)
+ if ambient is not None:
+ self._camera.render_config.enable_ambient_lighting = bool(ambient)
+
+ @staticmethod
+ def _dimmed(light: dict) -> dict:
+ """A directional light with ``intensity`` < 1 -> the equivalent far point light (see :meth:`set_lights`)."""
+ w = float(light.pop("intensity", 1.0))
+ center = np.asarray(light.pop("center", (0.0, 0.0, 0.0)), float)
+ if w >= 1.0:
+ return light
+ if w <= 0.0 or light.get("type", "directional") != "directional":
+ raise ValueError(f"intensity {w}: only directional lights, 0 < intensity <= 1")
+ d = np.asarray(light["direction"], float)
+ dist = math.sqrt((1.0 / w - 1.0) / 0.02)
+ return {"type": "point", "position": center - dist * d / np.linalg.norm(d),
+ "shadow": light.get("shadow", True)}
+
+ def _put(self, dst, src) -> None:
+ """Write a torch tensor into a Warp array, in place when both are on the render device."""
+ wp = self._wp
+ src = src.detach().float().contiguous()
+ if self.interop != "host-copy":
+ try:
+ wp.copy(dst, wp.from_torch(src, dtype=dst.dtype))
+ self.interop = "zero-copy"
+ return
+ except Exception as error: # noqa: BLE001
+ print(f"torch to warp without a copy is unavailable here ({type(error).__name__}: "
+ f"{str(error)[:120]}), copying through the host instead")
+ self.interop = "host-copy"
+ dst.assign(src.cpu().numpy())
diff --git a/so101_pick_place/code/src/nedm/render/camera_fx.py b/so101_pick_place/code/src/nedm/render/camera_fx.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d35fbe1dab611a232a2ddf5b70629b132a5f0d1
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/camera_fx.py
@@ -0,0 +1,269 @@
+"""Camera response and image-space camera effects for the real-setup renderer (torch, any device).
+
+Tone map (per camera, optionally per world): the linear colour of the ray tracer (Newton ``hdr_color``: albedo times
+the summed light, no exposure, no gamma) -> sRGB in 0-1::
+
+ x = hdr * exposure * wb[c] * cos(theta) ** vignette (theta: the pixel's ray angle to the optical axis)
+ x = x + black[c] (flare / black level, linear)
+ y = srgb_oetf(clamp(x, 0, 1)) ** gamma (gamma 1: plain sRGB)
+
+Parameter vector per camera, :data:`TONE_KEYS` order: exposure, wb_r, wb_g, wb_b, black_r, black_g, black_b, gamma,
+vignette.
+
+Image-space effects (:class:`ImageFX`), applied to uint8 / float images [N, H, W, 3] after rendering, one draw per
+image: nominal per-camera blur and chroma blur (applied by the real-scene renderer itself), Gaussian sensor noise,
+Gaussian blur, linear motion blur, JPEG
+compression (the robot's cameras stream MJPG;
+own DCT implementation: 8 x 8 blocks, YCbCr 4:2:0, the IJG quality scaling of the standard tables), each with a
+probability and a range. Nominal values and ranges come from ``real_scene_v1.json`` (``"image_fx"``).
+"""
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+
+import torch
+import torch.nn.functional as F
+
+TONE_KEYS = ("exposure", "wb_r", "wb_g", "wb_b", "black_r", "black_g", "black_b", "gamma", "vignette")
+TONE_DEFAULT = {"exposure": 1.0, "wb": (1.0, 1.0, 1.0), "black": (0.0, 0.0, 0.0), "gamma": 1.0, "vignette": 0.0}
+
+
+def tone_vector(d: dict | None) -> list[float]:
+ """Tone-map dict (``exposure``, ``wb`` (3,), ``black`` (3,), ``gamma``, ``vignette``) -> the 9 values."""
+ d = {**TONE_DEFAULT, **(d or {})}
+ return [float(d["exposure"]), *map(float, d["wb"]), *map(float, d["black"]), float(d["gamma"]),
+ float(d["vignette"])]
+
+
+def tone_dict(v) -> dict:
+ v = [float(x) for x in v]
+ return {"exposure": v[0], "wb": v[1:4], "black": v[4:7], "gamma": v[7], "vignette": v[8]}
+
+
+def srgb_oetf(x: torch.Tensor) -> torch.Tensor:
+ """Linear 0-1 -> sRGB 0-1 (IEC 61966-2-1)."""
+ return torch.where(x <= 0.0031308, 12.92 * x, 1.055 * x.clamp_min(0.0031308) ** (1 / 2.4) - 0.055)
+
+
+def srgb_eotf(y: torch.Tensor) -> torch.Tensor:
+ """sRGB 0-1 -> linear 0-1."""
+ return torch.where(y <= 0.04045, y / 12.92, ((y.clamp_min(0.04045) + 0.055) / 1.055) ** 2.4)
+
+
+def tone_map(hdr: torch.Tensor, params: torch.Tensor, cos_theta: torch.Tensor | None = None) -> torch.Tensor:
+ """hdr [B, C, H, W, 3] linear; params [C, 9] or [B, C, 9] (:data:`TONE_KEYS`); cos_theta [C, H, W] (needed when a
+ vignette exponent is not 0) -> sRGB float 0-1 [B, C, H, W, 3]."""
+ p = params.to(hdr.device, hdr.dtype)
+ if p.dim() == 2:
+ p = p[None]
+ p = p[:, :, None, None, :] # [B|1, C, 1, 1, 9]
+ x = hdr * p[..., 0:1] * p[..., 1:4]
+ if cos_theta is not None and bool((p[..., 8] != 0).any()):
+ x = x * cos_theta.to(hdr.device, hdr.dtype)[None, :, :, :, None].clamp_min(1e-3) ** p[..., 8:9]
+ x = (x + p[..., 4:7]).clamp(0.0, 1.0)
+ return srgb_oetf(x) ** p[..., 7:8]
+
+
+def to_uint8(y: torch.Tensor) -> torch.Tensor:
+ return (y * 255.0 + 0.5).clamp(0, 255).to(torch.uint8)
+
+
+# ---- image-space effects -----------------------------------------------------------------------------------------
+def _as_float(img: torch.Tensor) -> tuple[torch.Tensor, bool]:
+ if img.dtype == torch.uint8:
+ return img.float() / 255.0, True
+ return img.float(), False
+
+
+def gaussian_noise(img: torch.Tensor, sigma: torch.Tensor, generator=None) -> torch.Tensor:
+ """img [N, H, W, 3] float 0-1; sigma [N] (0-1 units). Random numbers on the generator's device."""
+ gdev = generator.device if generator is not None else img.device
+ n = torch.randn(img.shape, device=gdev, generator=generator, dtype=img.dtype).to(img.device)
+ return (img + n * sigma.to(img)[:, None, None, None]).clamp(0, 1)
+
+
+def _conv_per_image(img: torch.Tensor, kernels: torch.Tensor) -> torch.Tensor:
+ """img [N, H, W, 3]; kernels [N, k, k] (normalised) -> [N, H, W, 3] (reflect padding)."""
+ N, H, W, _ = img.shape
+ k = kernels.shape[-1]
+ x = img.permute(0, 3, 1, 2).reshape(1, N * 3, H, W)
+ x = F.pad(x, (k // 2,) * 4, mode="reflect")
+ w = kernels.to(img)[:, None].repeat_interleave(3, 0) # [N * 3, 1, k, k]
+ return F.conv2d(x, w, groups=N * 3).reshape(N, 3, H, W).permute(0, 2, 3, 1)
+
+
+def gaussian_blur(img: torch.Tensor, sigma: torch.Tensor, k: int = 7) -> torch.Tensor:
+ """img [N, H, W, 3] float; sigma [N] px (0 = unchanged)."""
+ r = torch.arange(k, device=img.device, dtype=img.dtype) - k // 2
+ s = sigma.to(img).clamp_min(1e-3)[:, None]
+ g = torch.exp(-0.5 * (r[None] / s) ** 2)
+ g = g / g.sum(-1, keepdim=True)
+ return _conv_per_image(img, g[:, :, None] * g[:, None, :])
+
+
+def chroma_blur(img: torch.Tensor, sigma: torch.Tensor, k: int = 9) -> torch.Tensor:
+ """Blur only the colour (JFIF Cb, Cr) of img [N, H, W, 3] float 0-1 by a Gaussian of ``sigma`` [N] px; the luma
+ stays sharp (the cameras' chroma subsampling / chroma denoising: small saturated objects lose colour)."""
+ r, g, b = img.unbind(-1)
+ y = 0.299 * r + 0.587 * g + 0.114 * b
+ cb, cr = b - y, r - y
+ c = gaussian_blur(torch.stack([cb, cr, torch.zeros_like(cb)], -1), sigma, k)
+ cb, cr = c[..., 0], c[..., 1]
+ r2, b2 = y + cr, y + cb
+ g2 = (y - 0.299 * r2 - 0.114 * b2) / 0.587
+ return torch.stack([r2, g2, b2], -1).clamp(0, 1)
+
+
+def motion_blur(img: torch.Tensor, length: torch.Tensor, angle: torch.Tensor, k: int = 9) -> torch.Tensor:
+ """img [N, H, W, 3] float; a line kernel of ``length`` px [N] at ``angle`` rad [N] (anti-aliased by distance)."""
+ r = torch.arange(k, device=img.device, dtype=img.dtype) - k // 2
+ yy, xx = torch.meshgrid(r, r, indexing="ij")
+ c, s = torch.cos(angle).to(img)[:, None, None], torch.sin(angle).to(img)[:, None, None]
+ along = xx[None] * c + yy[None] * s
+ across = -xx[None] * s + yy[None] * c
+ half = (length.to(img) / 2).clamp_min(0.0)[:, None, None]
+ w = (1 - across.abs()).clamp_min(0) * (half + 0.5 - along.abs()).clamp(0, 1)
+ w = w / w.sum((-1, -2), keepdim=True).clamp_min(1e-6)
+ return _conv_per_image(img, w)
+
+
+_LUMA_Q = torch.tensor([[16, 11, 10, 16, 24, 40, 51, 61], [12, 12, 14, 19, 26, 58, 60, 55],
+ [14, 13, 16, 24, 40, 57, 69, 56], [14, 17, 22, 29, 51, 87, 80, 62],
+ [18, 22, 37, 56, 68, 109, 103, 77], [24, 35, 55, 64, 81, 104, 113, 92],
+ [49, 64, 78, 87, 103, 121, 120, 101], [72, 92, 95, 98, 112, 100, 103, 99]], dtype=torch.float32)
+_CHROMA_Q = torch.full((8, 8), 99.0)
+_CHROMA_Q[:4, :4] = torch.tensor([[17, 18, 24, 47], [18, 21, 26, 66], [24, 26, 56, 99], [47, 66, 99, 99]])
+
+
+def _dct_matrix(device, dtype) -> torch.Tensor:
+ n = torch.arange(8, device=device, dtype=dtype)
+ m = torch.cos((2 * n[None, :] + 1) * n[:, None] * math.pi / 16) * math.sqrt(2 / 8)
+ m[0] = m[0] / math.sqrt(2)
+ return m
+
+
+def _qtable(base: torch.Tensor, quality: torch.Tensor) -> torch.Tensor:
+ """IJG scaling: [N, 8, 8] tables for qualities [N] (1-100)."""
+ q = quality.clamp(1, 100)
+ scale = torch.where(q < 50, 5000 / q, 200 - 2 * q)
+ return ((base[None] * scale[:, None, None] + 50) / 100).floor().clamp(1, 255)
+
+
+def _blocks_q(x: torch.Tensor, table: torch.Tensor, D: torch.Tensor) -> torch.Tensor:
+ """x [N, H, W] (0-255 minus 128), H, W multiples of 8 -> quantised and reconstructed."""
+ N, H, W = x.shape
+ b = x.reshape(N, H // 8, 8, W // 8, 8).permute(0, 1, 3, 2, 4) # [N, by, bx, 8, 8]
+ c = D @ b @ D.T
+ t = table[:, None, None]
+ c = torch.round(c / t) * t
+ return (D.T @ c @ D).permute(0, 1, 3, 2, 4).reshape(N, H, W)
+
+
+def jpeg(img: torch.Tensor, quality: torch.Tensor) -> torch.Tensor:
+ """JPEG round trip of img [N, H, W, 3] float 0-1 at ``quality`` [N] (1-100): YCbCr (JFIF), 4:2:0 chroma (2 x 2
+ mean, bilinear back), 8 x 8 DCT with the IJG-scaled standard tables. Edge padding to multiples of 16."""
+ N, H, W, _ = img.shape
+ ph, pw = (-H) % 16, (-W) % 16
+ x = img.permute(0, 3, 1, 2) * 255.0
+ if ph or pw:
+ x = F.pad(x, (0, pw, 0, ph), mode="replicate")
+ r, g, b = x[:, 0], x[:, 1], x[:, 2]
+ y = 0.299 * r + 0.587 * g + 0.114 * b
+ cb = -0.168736 * r - 0.331264 * g + 0.5 * b + 128
+ cr = 0.5 * r - 0.418688 * g - 0.081312 * b + 128
+ D = _dct_matrix(img.device, torch.float32)
+ qq = quality.to(img.device, torch.float32)
+ y = _blocks_q(y.float() - 128, _qtable(_LUMA_Q.to(img.device), qq), D) + 128
+ sub = lambda c: F.avg_pool2d(c[:, None].float(), 2)[:, 0] # noqa: E731
+ tc = _qtable(_CHROMA_Q.to(img.device), qq)
+ cb = _blocks_q(sub(cb) - 128, tc, D) + 128
+ cr = _blocks_q(sub(cr) - 128, tc, D) + 128
+ up = lambda c: F.interpolate(c[:, None], scale_factor=2, mode="bilinear", align_corners=False)[:, 0] # noqa
+ cb, cr = up(cb) - 128, up(cr) - 128
+ out = torch.stack([y + 1.402 * cr, y - 0.344136 * cb - 0.714136 * cr, y + 1.772 * cb], 1)
+ out = out[:, :, :H, :W].permute(0, 2, 3, 1) / 255.0
+ return out.clamp(0, 1).to(img.dtype)
+
+
+@dataclass
+class ImageFX:
+ """Per-image camera effects after rendering, one draw per image. Each effect: probability ``p_*`` and a range;
+ the nominal effects (always on: the real camera's sharpness ``nominal_blur_px`` and colour bleeding
+ ``nominal_chroma_px``, a number or a dict per camera name) come first. Values in px or 0-1 units."""
+
+ nominal_blur_px: float | dict = 0.0
+ nominal_chroma_px: float | dict = 0.0
+ p_noise: float = 0.8
+ noise: tuple = (0.004, 0.02) # std (0-1 units)
+ p_blur: float = 0.3
+ blur_px: tuple = (0.3, 1.0) # Gaussian sigma (px at the output size)
+ p_motion: float = 0.2
+ motion_px: tuple = (1.0, 3.0) # line length (px)
+ p_jpeg: float = 0.8
+ jpeg_quality: tuple = (50, 95)
+ extra: dict = field(default_factory=dict)
+
+ @classmethod
+ def from_dict(cls, d: dict | None) -> "ImageFX":
+ d = dict(d or {})
+ known = {k: (tuple(v) if isinstance(v, list) else v) for k, v in d.items() if k in cls.__dataclass_fields__}
+ return cls(**known, extra={k: v for k, v in d.items() if k not in cls.__dataclass_fields__})
+
+ def draw(self, n: int, generator=None, device="cpu") -> dict:
+ """Per-image draws (random numbers on the generator's device, results on ``device``)."""
+ gdev = generator.device if generator is not None else torch.device(device)
+
+ def u(lo, hi):
+ return (lo + (hi - lo) * torch.rand(n, generator=generator, device=gdev)).to(device)
+
+ def on(p):
+ return (torch.rand(n, generator=generator, device=gdev) < p).to(device)
+
+ return {"noise": torch.where(on(self.p_noise), u(*self.noise), 0.0),
+ "blur": torch.where(on(self.p_blur), u(*self.blur_px), 0.0),
+ "motion": torch.where(on(self.p_motion), u(*self.motion_px), 0.0),
+ "motion_angle": u(0.0, math.pi),
+ "jpeg": torch.where(on(self.p_jpeg), u(*self.jpeg_quality).round(), 0.0)}
+
+ @staticmethod
+ def _per_camera(v, camera):
+ if isinstance(v, dict):
+ return float(v.get(camera, 0.0)) if camera is not None else 0.0
+ return float(v)
+
+ def nominal(self, x: torch.Tensor, camera: str | None) -> torch.Tensor:
+ """The nominal (always-on) effects of ``camera`` on float images [N, H, W, 3]: chroma blur, then blur.
+ :class:`~nedm.render.so101.SO101Renderer` applies them itself for a real scene with ``image_fx``."""
+ chroma = self._per_camera(self.nominal_chroma_px, camera)
+ if chroma > 0:
+ x = chroma_blur(x, torch.full((len(x),), chroma, device=x.device))
+ blur = self._per_camera(self.nominal_blur_px, camera)
+ if blur > 0:
+ x = gaussian_blur(x, torch.full((len(x),), blur, device=x.device))
+ return x
+
+ def apply(self, img: torch.Tensor, draw: dict | None = None, generator=None, camera: str | None = None,
+ nominal: bool = False) -> torch.Tensor:
+ """img [N, H, W, 3] uint8 or float 0-1 -> same dtype: the random effects of ``draw`` (None: none). The
+ nominal effects only with ``nominal`` (the real-scene renderer already applied them to its output);
+ ``camera``: the camera name for per-camera nominal effects (all images of one call from one camera)."""
+ x, was_u8 = _as_float(img)
+ dev = x.device
+ if nominal:
+ x = self.nominal(x, camera)
+ if draw is not None:
+ d = {k: v.to(dev) for k, v in draw.items()}
+ sel = d["blur"] > 0
+ if sel.any():
+ x[sel] = gaussian_blur(x[sel], d["blur"][sel])
+ sel = d["motion"] > 0
+ if sel.any():
+ x[sel] = motion_blur(x[sel], d["motion"][sel], d["motion_angle"][sel])
+ sel = d["noise"] > 0
+ if sel.any():
+ x[sel] = gaussian_noise(x[sel], d["noise"][sel], generator)
+ sel = d["jpeg"] > 0
+ if sel.any():
+ x[sel] = jpeg(x[sel], d["jpeg"][sel])
+ return to_uint8(x) if was_u8 else x
diff --git a/so101_pick_place/code/src/nedm/render/cameras.py b/so101_pick_place/code/src/nedm/render/cameras.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f15aea45c110629604e61fef951d8ac6129d754
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/cameras.py
@@ -0,0 +1,303 @@
+"""Camera poses, one per world, and camera models (the rays of each camera).
+
+A camera looks along its own -Z axis with +Y up (the OpenGL convention Newton's ray tracer
+uses). Every pose helper returns transforms (N, 7) that :meth:`BatchRenderer.render` accepts.
+Calibrations use the OpenCV convention (x right, y down, z forward): :func:`pose_from_opencv`
+and :func:`pose_to_opencv` are the one conversion.
+
+Camera models (``BatchRenderer(..., camera_models=[...])``, Newton only): :class:`PinholeCamera`
+(own vertical fov) and :class:`CalibratedCamera` (``opencv_fisheye`` / ``opencv`` lens with K, D
+of the real image, a crop box and the renderer's output size).
+"""
+
+from __future__ import annotations
+
+import math
+
+import numpy as np
+import torch
+
+from nedm.render.poses import compose, transform_from_matrix
+
+
+def look_at(eye: torch.Tensor, target: torch.Tensor, up=(0.0, 0.0, 1.0)) -> torch.Tensor:
+ """Cameras at ``eye`` (N, 3) looking at ``target`` (N, 3), world +Z up by default."""
+ # float64 until the final cast: a camera axis off by one float32 ulp flips silhouette pixels
+ eye, target = torch.as_tensor(eye, dtype=torch.float64), torch.as_tensor(target, dtype=torch.float64)
+ eye, target = torch.broadcast_tensors(eye.reshape(-1, 3), target.reshape(-1, 3).to(eye.device))
+ up_t = torch.as_tensor(up, dtype=torch.float64, device=eye.device).expand_as(eye)
+ forward = torch.nn.functional.normalize(target - eye, dim=-1)
+ right = torch.nn.functional.normalize(torch.cross(forward, up_t, dim=-1), dim=-1)
+ true_up = torch.cross(right, forward, dim=-1)
+ matrix = torch.eye(4, dtype=torch.float64, device=eye.device).repeat(eye.shape[0], 1, 1)
+ matrix[:, :3, 0], matrix[:, :3, 1], matrix[:, :3, 2], matrix[:, :3, 3] = right, true_up, -forward, eye
+ return transform_from_matrix(matrix)
+
+
+def follow(
+ xy: torch.Tensor,
+ eye_offset=(-1.05, -1.20, 0.70),
+ look_offset=(0.10, 0.0, 0.20),
+) -> torch.Tensor:
+ """Third-person view that tracks each world's ``xy`` (N, 2) at a fixed world-frame offset.
+
+ The offset does not turn with the robot, so turning stays visible in the picture.
+ """
+ xy = torch.as_tensor(xy, dtype=torch.float32)
+ eye = torch.as_tensor(eye_offset, dtype=torch.float64, device=xy.device)
+ look = torch.as_tensor(look_offset, dtype=torch.float64, device=xy.device)
+ one = look_at(eye[None], look[None]) # orientation is the same in every world
+ out = one.repeat(xy.shape[0], 1)
+ out[:, :2] = xy + eye[:2].float()
+ return out
+
+
+def mounted(body: torch.Tensor, local: torch.Tensor) -> torch.Tensor:
+ """Camera fixed to a body: ``body`` (N, 7) world poses, ``local`` (7,) the camera in the body frame.
+
+ For a forward-looking camera on a robot whose +X is forward and +Z is up, build ``local``
+ with ``look_at(position, position + (1, 0, 0))``.
+ """
+ local = torch.as_tensor(local, dtype=torch.float32, device=body.device).reshape(-1, 7)
+ return compose(body.float(), local.expand(body.shape[0], 7))
+
+
+# ---- camera conventions -------------------------------------------------------------------------------------------
+# OpenCV camera frame: x right, y down, z forward (optical axis). Renderer (Newton, MuJoCo) camera frame: x right, y up,
+# z backward. The two differ by a turn of 180 deg about the camera x axis: R_renderer = R_opencv @ diag(1, -1, -1).
+def pose_from_opencv(pose) -> torch.Tensor:
+ """Camera poses in the OpenCV convention -> renderer transforms. ``pose`` (..., 7) = x y z, qw qx qy qz (the
+ calibration contract's ``T_parent_cam``: camera frame x right, y down, z forward, in the parent frame, metres).
+ Returns (..., 7) = x y z, qx qy qz qw of the same camera in the renderer's convention (-Z forward, +Y up), float64.
+ The inverse is :func:`pose_to_opencv`."""
+ p = torch.as_tensor(pose, dtype=torch.float64)
+ w, x, y, z = p[..., 3:7].unbind(-1)
+ n = torch.sqrt(w * w + x * x + y * y + z * z)
+ # q_renderer = q_opencv * q_x(pi), q_x(pi) = (w 0, x 1, y 0, z 0): (w, x, y, z) * (0, 1, 0, 0) = (-x, w, z, -y)
+ return torch.cat([p[..., :3], torch.stack([w, z, -y, -x], -1) / n[..., None]], -1)
+
+
+def pose_to_opencv(transform) -> torch.Tensor:
+ """Renderer transforms (..., 7) = x y z, qx qy qz qw -> OpenCV-convention poses (..., 7) = x y z, qw qx qy qz
+ (inverse of :func:`pose_from_opencv`; the quaternion sign is chosen with qw >= 0), float64."""
+ t = torch.as_tensor(transform, dtype=torch.float64)
+ x, y, z, w = t[..., 3:7].unbind(-1)
+ # q_opencv = q_renderer * q_x(pi)^-1 = q_renderer * (0, -1, 0, 0): (w, x, y, z) * (0, -1, 0, 0) = (x, -w, -z, y)
+ q = torch.stack([x, -w, -z, y], -1)
+ q = q / q.norm(dim=-1, keepdim=True)
+ q = torch.where(q[..., :1] < 0, -q, q)
+ return torch.cat([t[..., :3], q], -1)
+
+
+def opencv_look_at(eye, target, up=(0.0, 0.0, 1.0)) -> torch.Tensor:
+ """OpenCV-convention poses (N, 7) x y z, qw qx qy qz of cameras at ``eye`` (N, 3) looking at ``target`` (N, 3)
+ (image up towards world ``up``), float64 throughout: the contract's layout, for placeholder calibrations and
+ tests. A view direction parallel to ``up`` has no defined roll: those rows use world +y as ``up`` (+x if the view
+ is along y), so the result is always a unit quaternion. ``eye`` == ``target`` raises ValueError."""
+ eye = torch.as_tensor(eye, dtype=torch.float64).reshape(-1, 3)
+ target = torch.as_tensor(target, dtype=torch.float64).reshape(-1, 3)
+ eye, target = torch.broadcast_tensors(eye, target)
+ if bool(((target - eye).norm(dim=-1) < 1e-12).any()):
+ raise ValueError("opencv_look_at: eye and target coincide")
+ z = torch.nn.functional.normalize(target - eye, dim=-1)
+ up_t = torch.as_tensor(up, dtype=torch.float64).expand_as(z).clone()
+ for alt in ((0.0, 1.0, 0.0), (1.0, 0.0, 0.0)):
+ bad = torch.cross(z, up_t, dim=-1).norm(dim=-1) < 1e-9 * up_t.norm(dim=-1).clamp_min(1e-300)
+ up_t[bad] = torch.tensor(alt, dtype=torch.float64)
+ x = torch.nn.functional.normalize(torch.cross(z, up_t, dim=-1), dim=-1)
+ y = torch.cross(z, x, dim=-1) # image down
+ m = torch.stack([x, y, z], -1) # columns = camera axes in the world
+ m00, m01, m02, m10, m11, m12, m20, m21, m22 = m.reshape(-1, 9).unbind(-1)
+ four = torch.stack([1 + m00 + m11 + m22, 1 + m00 - m11 - m22, 1 - m00 + m11 - m22, 1 - m00 - m11 + m22], -1)
+ rows = torch.stack([torch.stack([four[:, 0], m21 - m12, m02 - m20, m10 - m01], -1), # 4w (w, x, y, z)
+ torch.stack([m21 - m12, four[:, 1], m01 + m10, m02 + m20], -1), # 4x
+ torch.stack([m02 - m20, m01 + m10, four[:, 2], m12 + m21], -1), # 4y
+ torch.stack([m10 - m01, m02 + m20, m12 + m21, four[:, 3]], -1)], -2) # 4z
+ big = four.argmax(-1)
+ q = rows[torch.arange(len(big)), big] / (2 * torch.sqrt(four[torch.arange(len(big)), big]))[:, None]
+ q = torch.where(q[:, :1] < 0, -q, q)
+ return torch.cat([eye, q], -1)
+
+
+# ---- camera models: per-camera rays ---------------------------------------------------------------------------------
+class PinholeCamera:
+ """The renderer's own pinhole: vertical field of view ``fovy_deg``, square pixels, principal point at the image
+ centre. Newton draws it with its own ray kernel (``compute_pinhole_camera_rays``), so a renderer whose cameras are
+ all pinholes of one fov draws exactly the pictures it drew before camera models existed."""
+
+ kind = "pinhole"
+
+ def __init__(self, fovy_deg: float):
+ self.fovy_deg = float(fovy_deg)
+
+ def __repr__(self) -> str:
+ return f"PinholeCamera(fovy_deg={self.fovy_deg})"
+
+ def rays(self, width: int, height: int) -> tuple[np.ndarray, np.ndarray]:
+ """Unit ray directions (H, W, 3) float64 in the renderer's camera frame and validity (H, W) bool (all True).
+ Newton's formula in float64: d = (u 2h W/H, -v 2h, -1), u = (px + 0.5)/W - 0.5, v = (py + 0.5)/H - 0.5."""
+ h = math.tan(math.radians(self.fovy_deg) / 2)
+ u = (np.arange(width) + 0.5) / width - 0.5
+ v = (np.arange(height) + 0.5) / height - 0.5
+ x, y = u[None, :] * 2 * h * width / height, -v[:, None] * 2 * h
+ d = np.stack(np.broadcast_arrays(x, y, -np.ones((1, 1))), -1)
+ return d / np.linalg.norm(d, axis=-1, keepdims=True), np.ones((height, width), bool)
+
+
+class CalibratedCamera:
+ """A calibrated real camera, drawn through its own lens model.
+
+ ``model``: ``"opencv_fisheye"`` (Kannala-Brandt, ``D`` = k1..k4 as ``cv2.fisheye``: r_d = theta (1 + k1 theta^2 +
+ k2 theta^4 + k3 theta^6 + k4 theta^8), valid beyond 90 deg where cv2.fisheye itself is not) or ``"opencv"``
+ (radial-tangential, ``D`` = k1 k2 p1 p2 [k3 [k4 k5 k6 ...]] as ``cv2.projectPoints``). ``K`` = (fx, fy, cx, cy) and ``width`` x ``height`` of the REAL image (pixel centres at
+ integer coordinates, OpenCV's convention). ``crop`` = (x0, y0, w, h) in real pixels (None: the whole image).
+
+ The output image (W_out x H_out, the renderer's size) samples the crop box like ``cv2.resize(real[y0:y0+h,
+ x0:x0+w], (W_out, H_out))``: output pixel (i, j) looks along the undistorted ray of the real-image point
+ u = x0 + (j + 0.5) w / W_out - 0.5, v = y0 + (i + 0.5) h / H_out - 0.5. Pixels outside the real sensor, or whose
+ point has no ray in the model (beyond the lens model's monotonic range), are invalid: the renderer draws them black
+ with depth 0.
+ """
+
+ MODELS = ("opencv_fisheye", "opencv")
+
+ def __init__(self, model: str, K, D, width: int, height: int, crop=None):
+ if model not in self.MODELS:
+ raise ValueError(f"camera model {model!r}: one of {self.MODELS}")
+ self.kind = self.model = model
+ self.K = tuple(float(k) for k in K)
+ self.D = tuple(float(d) for d in D)
+ if len(self.K) != 4:
+ raise ValueError("K = (fx, fy, cx, cy)")
+ if model == "opencv_fisheye" and len(self.D) != 4:
+ raise ValueError("opencv_fisheye: D = (k1, k2, k3, k4)")
+ if model == "opencv" and len(self.D) not in (4, 5, 8, 12, 14):
+ raise ValueError("opencv: D has 4, 5, 8, 12 or 14 coefficients (cv2.projectPoints)")
+ self.width, self.height = int(width), int(height)
+ self.crop = tuple(float(c) for c in crop) if crop is not None else (0.0, 0.0, float(width), float(height))
+
+ @classmethod
+ def from_contract(cls, cam: dict, crop=None) -> "CalibratedCamera":
+ """From one ``cameras`` entry of the calibration contract (``model``, ``K``, ``D``, ``width``, ``height``)."""
+ return cls(cam["model"], cam["K"], cam["D"], cam["width"], cam["height"], crop)
+
+ def __repr__(self) -> str:
+ return (f"CalibratedCamera({self.model!r}, K={self.K}, D={self.D}, {self.width}x{self.height}, "
+ f"crop={self.crop})")
+
+ @property
+ def matrix(self) -> np.ndarray:
+ fx, fy, cx, cy = self.K
+ return np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], np.float64)
+
+ # -- pixel grids --
+ def real_pixels(self, width: int, height: int) -> tuple[np.ndarray, np.ndarray]:
+ """Real-image coordinates (u, v), each (H_out, W_out) float64, of the output pixel centres."""
+ x0, y0, w, h = self.crop
+ u = x0 + (np.arange(width) + 0.5) * w / width - 0.5
+ v = y0 + (np.arange(height) + 0.5) * h / height - 0.5
+ return np.broadcast_to(u[None, :], (height, width)).copy(), np.broadcast_to(v[:, None], (height, width)).copy()
+
+ def output_pixels(self, u, v, width: int, height: int) -> tuple[np.ndarray, np.ndarray]:
+ """Real-image coordinates -> output-image coordinates (column, row; pixel centres at integers)."""
+ x0, y0, w, h = self.crop
+ return (np.asarray(u) - x0 + 0.5) * width / w - 0.5, (np.asarray(v) - y0 + 0.5) * height / h - 0.5
+
+ # -- the lens model --
+ def _theta_max(self) -> float:
+ """Fisheye: the largest incidence angle (rad, <= pi) up to which r_d(theta) increases."""
+ k1, k2, k3, k4 = self.D
+ t = np.linspace(0.0, math.pi, 200001)
+ t2 = t * t
+ slope = 1 + 3 * k1 * t2 + 5 * k2 * t2 ** 2 + 7 * k3 * t2 ** 3 + 9 * k4 * t2 ** 4
+ bad = np.nonzero(slope <= 0)[0]
+ return float(t[bad[0] - 1]) if len(bad) else math.pi
+
+ def _fisheye_r(self, theta):
+ k1, k2, k3, k4 = self.D
+ t2 = theta * theta
+ return theta * (1 + k1 * t2 + k2 * t2 ** 2 + k3 * t2 ** 3 + k4 * t2 ** 4)
+
+ def _fisheye_theta(self, rd: np.ndarray, tmax: float) -> np.ndarray:
+ """theta with r_d(theta) = rd on [0, tmax] (rd < r_d(tmax)): Newton steps from theta = rd, then bisection for
+ any point that has not converged to 1e-13."""
+ k1, k2, k3, k4 = self.D
+ theta = np.clip(rd, 0.0, tmax)
+ for _ in range(12):
+ t2 = theta * theta
+ slope = 1 + 3 * k1 * t2 + 5 * k2 * t2 ** 2 + 7 * k3 * t2 ** 3 + 9 * k4 * t2 ** 4
+ theta = np.clip(theta - (self._fisheye_r(theta) - rd) / np.maximum(slope, 1e-9), 0.0, tmax)
+ bad = np.abs(self._fisheye_r(theta) - rd) > 1e-13
+ if bad.any():
+ lo, hi, r = np.zeros(bad.sum()), np.full(bad.sum(), tmax), rd[bad]
+ for _ in range(64): # bisection on the monotonic part: 2^-64 of tmax
+ mid = 0.5 * (lo + hi)
+ big = self._fisheye_r(mid) > r
+ hi, lo = np.where(big, mid, hi), np.where(big, lo, mid)
+ theta[bad] = 0.5 * (lo + hi)
+ return theta
+
+ def directions(self, u, v) -> tuple[np.ndarray, np.ndarray]:
+ """Undistorted unit ray directions (..., 3) float64 in the OPENCV camera frame of real-image points (u, v),
+ and validity (...) bool (inside the sensor and inside the lens model's range)."""
+ u, v = np.asarray(u, np.float64), np.asarray(v, np.float64)
+ fx, fy, cx, cy = self.K
+ inside = (u >= -0.5) & (u <= self.width - 0.5) & (v >= -0.5) & (v <= self.height - 0.5)
+ if self.model == "opencv_fisheye":
+ xd, yd = (u - cx) / fx, (v - cy) / fy
+ rd = np.hypot(xd, yd)
+ tmax = self._theta_max()
+ ok = rd < self._fisheye_r(tmax)
+ theta = self._fisheye_theta(np.where(ok, rd, 0.0), tmax)
+ s = np.where(rd > 0, np.sin(theta) / np.where(rd > 0, rd, 1.0), 1.0)
+ d = np.stack([xd * s, yd * s, np.cos(theta)], -1)
+ return d / np.linalg.norm(d, axis=-1, keepdims=True), inside & ok
+ import cv2
+ pts = np.stack([u.ravel(), v.ravel()], -1)[:, None, :]
+ D = np.array(self.D, np.float64)
+ def solve(p, iters):
+ crit = (cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, iters, 1e-15)
+ xy = cv2.undistortPointsIter(p, self.matrix, D, None, None, crit).reshape(-1, 2)
+ back, _ = cv2.projectPoints(np.c_[xy, np.ones(len(xy))].reshape(-1, 1, 3), np.zeros(3), np.zeros(3),
+ self.matrix, D)
+ return xy, np.linalg.norm(back.reshape(-1, 2) - p[:, 0], axis=-1)
+
+ xy, err = solve(pts, 40)
+ slow = ~(err < 1e-4)
+ if slow.any(): # strong distortion: more fixed-point iterations
+ xy[slow], err[slow] = solve(pts[slow], 400)
+ d = np.concatenate([xy, np.ones((len(xy), 1))], -1)
+ d = d / np.linalg.norm(d, axis=-1, keepdims=True)
+ # the radial factor must still grow with r at the solution (else it is the far, folded branch of the model)
+ k1, k2, k3, k4, k5, k6 = (*D[:2], *(D[4:8].tolist() + [0.0] * 4)[:4])
+ r2 = (xy ** 2).sum(-1)
+ num = 1 + k1 * r2 + k2 * r2 ** 2 + k3 * r2 ** 3
+ den = 1 + k4 * r2 + k5 * r2 ** 2 + k6 * r2 ** 3
+ dnum = 2 * k1 * r2 + 4 * k2 * r2 ** 2 + 6 * k3 * r2 ** 3 # r d(num)/dr
+ dden = 2 * k4 * r2 + 4 * k5 * r2 ** 2 + 6 * k6 * r2 ** 3
+ slope = (num + dnum) * den - num * dden # sign of d(r num/den)/dr
+ ok = (err < 1e-3) & (slope > 0) & np.isfinite(xy).all(-1)
+ return d.reshape(*u.shape, 3), inside & ok.reshape(u.shape)
+
+ def project(self, points) -> np.ndarray:
+ """Real-image coordinates (N, 2) of points (N, 3) in the OPENCV camera frame (cv2's own projection)."""
+ import cv2
+ p = np.asarray(points, np.float64).reshape(-1, 1, 3)
+ D = np.array(self.D, np.float64)
+ if self.model == "opencv_fisheye":
+ out, _ = cv2.fisheye.projectPoints(p, np.zeros(3), np.zeros(3), self.matrix, D)
+ else:
+ out, _ = cv2.projectPoints(p, np.zeros(3), np.zeros(3), self.matrix, D)
+ return out.reshape(-1, 2)
+
+ def rays(self, width: int, height: int) -> tuple[np.ndarray, np.ndarray]:
+ """Unit ray directions (H, W, 3) float64 in the RENDERER's camera frame (x right, y up, z backward) of the
+ output pixels, and validity (H, W) bool."""
+ d, ok = self.directions(*self.real_pixels(width, height))
+ return d * np.array([1.0, -1.0, -1.0]), ok
+
+
+def camera_rays(models, width: int, height: int) -> tuple[np.ndarray, np.ndarray]:
+ """Rays of several cameras: directions (C, H, W, 3) float64 (renderer frame) and validity (C, H, W) bool."""
+ out = [m.rays(width, height) for m in models]
+ return np.stack([d for d, _ in out]), np.stack([v for _, v in out])
diff --git a/so101_pick_place/code/src/nedm/render/poses.py b/so101_pick_place/code/src/nedm/render/poses.py
new file mode 100644
index 0000000000000000000000000000000000000000..08dc1c2c1aa3c6704f217c7aea04239ec28fd6de
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/poses.py
@@ -0,0 +1,175 @@
+"""Reduced state -> poses the renderer can draw.
+
+A transform is seven numbers, ``[x, y, z, qx, qy, qz, qw]``, as Warp and Newton store it.
+Everything here is batched torch on whatever device the NRD model runs on, so the result
+reaches the renderer without leaving the GPU.
+
+The reduced states in this repository do not carry x, y or yaw. Every environment recovers
+them by integrating the predicted body-frame velocities and yaw rate. :class:`PlanarPose` is
+that integration, written once.
+"""
+
+from __future__ import annotations
+
+from typing import Mapping, Sequence
+
+import torch
+
+
+def quat_from_rpy(roll: torch.Tensor, pitch: torch.Tensor, yaw: torch.Tensor) -> torch.Tensor:
+ """Quaternion ``xyzw`` of ``R = Rz(yaw) Ry(pitch) Rx(roll)``, shape (..., 4)."""
+ cr, sr = torch.cos(roll / 2), torch.sin(roll / 2)
+ cp, sp = torch.cos(pitch / 2), torch.sin(pitch / 2)
+ cy, sy = torch.cos(yaw / 2), torch.sin(yaw / 2)
+ return torch.stack(
+ [
+ sr * cp * cy - cr * sp * sy,
+ cr * sp * cy + sr * cp * sy,
+ cr * cp * sy - sr * sp * cy,
+ cr * cp * cy + sr * sp * sy,
+ ],
+ dim=-1,
+ )
+
+
+def tilt_from_gravity(gravity_body: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Roll and pitch from the gravity direction in the body frame.
+
+ ``gravity_body = R^T (0, 0, -1)`` with ``R = Rz(yaw) Ry(pitch) Rx(roll)`` gives
+ ``(sin pitch, -sin roll cos pitch, -cos roll cos pitch)``. The vector need not be unit
+ length, which matters because a predicted state rarely is.
+ """
+ g = gravity_body
+ pitch = torch.atan2(g[..., 0], torch.sqrt(g[..., 1] ** 2 + g[..., 2] ** 2))
+ roll = torch.atan2(-g[..., 1], -g[..., 2])
+ return roll, pitch
+
+
+def base_transform(
+ xy_yaw: torch.Tensor,
+ z: torch.Tensor | float,
+ roll: torch.Tensor | None = None,
+ pitch: torch.Tensor | None = None,
+) -> torch.Tensor:
+ """Transform (N, 7) of a base at planar pose ``xy_yaw`` (N, 3), height ``z``, tilted."""
+ n = xy_yaw.shape[0]
+ zero = torch.zeros(n, dtype=torch.float32, device=xy_yaw.device)
+ roll = zero if roll is None else roll.float()
+ pitch = zero if pitch is None else pitch.float()
+ out = torch.zeros(n, 7, dtype=torch.float32, device=xy_yaw.device)
+ out[:, 0] = xy_yaw[:, 0].float()
+ out[:, 1] = xy_yaw[:, 1].float()
+ out[:, 2] = z
+ out[:, 3:] = quat_from_rpy(roll, pitch, xy_yaw[:, 2].float())
+ return out
+
+
+def transform_from_matrix(matrix: torch.Tensor) -> torch.Tensor:
+ """Homogeneous matrices (..., 4, 4) -> transforms (..., 7). Rotation must be proper."""
+ m = matrix[..., :3, :3]
+ m00, m01, m02 = m[..., 0, 0], m[..., 0, 1], m[..., 0, 2]
+ m10, m11, m12 = m[..., 1, 0], m[..., 1, 1], m[..., 1, 2]
+ m20, m21, m22 = m[..., 2, 0], m[..., 2, 1], m[..., 2, 2]
+ # Shepperd: divide by the LARGEST of the four components. Taking each from its own square
+ # root loses half the precision whenever a component is near zero.
+ four_sq = torch.stack([1 + m00 - m11 - m22, 1 - m00 + m11 - m22, 1 - m00 - m11 + m22,
+ 1 + m00 + m11 + m22], dim=-1) # 4x^2, 4y^2, 4z^2, 4w^2
+ rows = torch.stack([
+ torch.stack([four_sq[..., 0], m01 + m10, m02 + m20, m21 - m12], dim=-1), # 4x * (x, y, z, w)
+ torch.stack([m01 + m10, four_sq[..., 1], m12 + m21, m02 - m20], dim=-1), # 4y * ...
+ torch.stack([m02 + m20, m12 + m21, four_sq[..., 2], m10 - m01], dim=-1), # 4z * ...
+ torch.stack([m21 - m12, m02 - m20, m10 - m01, four_sq[..., 3]], dim=-1), # 4w * ...
+ ], dim=-2)
+ big = four_sq.argmax(dim=-1)
+ quat = torch.gather(rows, -2, big[..., None, None].expand(*big.shape, 1, 4)).squeeze(-2)
+ quat = quat / (2.0 * torch.sqrt(torch.gather(four_sq, -1, big[..., None])))
+ quat = torch.where(quat[..., 3:4] < 0, -quat, quat)
+ return torch.cat([matrix[..., :3, 3], quat], dim=-1).float()
+
+
+def quat_rotate(q: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
+ """Rotate vectors ``v`` (..., 3) by quaternions ``q`` (..., 4) in ``xyzw``."""
+ u, w = q[..., :3], q[..., 3:4]
+ t = 2.0 * torch.cross(u, v, dim=-1)
+ return v + w * t + torch.cross(u, t, dim=-1)
+
+
+def compose(parent: torch.Tensor, child: torch.Tensor) -> torch.Tensor:
+ """``parent * child`` for transforms (..., 7): the child pose expressed in the parent's frame."""
+ pq, cq = parent[..., 3:], child[..., 3:]
+ pu, pw = pq[..., :3], pq[..., 3:4]
+ cu, cw = cq[..., :3], cq[..., 3:4]
+ quat = torch.cat([pw * cu + cw * pu + torch.cross(pu, cu, dim=-1),
+ pw * cw - (pu * cu).sum(-1, keepdim=True)], dim=-1)
+ return torch.cat([parent[..., :3] + quat_rotate(pq, child[..., :3]), quat], dim=-1)
+
+
+class PlanarPose:
+ """x, y and yaw of every world, integrated from body velocities and yaw rate.
+
+ The same update as ``HMMWVNeuralTrackingEnv._integrate_pose`` and the rollout metric in
+ the trainers: yaw first, then the body velocity rotated by the new yaw. Kept in float64,
+ as those do, because the sum runs for thousands of steps.
+ """
+
+ def __init__(self, num_worlds: int, dt_s: float, device: str | torch.device | None = None):
+ self.dt_s = float(dt_s)
+ self.xy_yaw = torch.zeros(num_worlds, 3, dtype=torch.float64, device=device)
+
+ def reset(self, ids: torch.Tensor | None = None, xy_yaw: torch.Tensor | None = None) -> None:
+ ids = slice(None) if ids is None else ids
+ self.xy_yaw[ids] = 0.0 if xy_yaw is None else xy_yaw.double()
+
+ def step(self, vx: torch.Tensor, vy: torch.Tensor, yaw_rate: torch.Tensor) -> torch.Tensor:
+ vx, vy = vx.double(), vy.double()
+ yaw = self.xy_yaw[:, 2] + yaw_rate.double() * self.dt_s
+ x = self.xy_yaw[:, 0] + (vx * torch.cos(yaw) - vy * torch.sin(yaw)) * self.dt_s
+ y = self.xy_yaw[:, 1] + (vx * torch.sin(yaw) + vy * torch.cos(yaw)) * self.dt_s
+ self.xy_yaw = torch.stack([x, y, yaw], dim=-1)
+ return self.xy_yaw
+
+
+class JointMap:
+ """State columns -> the joint coordinates of a URDF scene, matched by name.
+
+ ``mapping`` gives, for each URDF joint, the state field that holds its angle, or a tuple
+ ``(field, sign, offset)`` when the two conventions differ:
+ ``q_urdf = sign * state[field] + offset``. Names rather than positions, because a
+ reordered preset is exactly the kind of error that renders a plausible wrong robot.
+ """
+
+ def __init__(
+ self,
+ joint_index: Mapping[str, int],
+ coord_count: int,
+ state_fields: Sequence[str],
+ mapping: Mapping[str, str | tuple[str, float] | tuple[str, float, float]],
+ base_coords: int = 7,
+ ):
+ column = {name: i for i, name in enumerate(state_fields)}
+ src, dst, sign, offset = [], [], [], []
+ for joint, spec in mapping.items():
+ field, s, o = (spec, 1.0, 0.0) if isinstance(spec, str) else (*spec, 0.0)[:3]
+ if joint not in joint_index:
+ raise KeyError(f"the scene has no joint {joint!r}, it has {sorted(joint_index)}")
+ if field not in column:
+ raise KeyError(f"the state has no field {field!r}")
+ src.append(column[field])
+ dst.append(int(joint_index[joint]))
+ sign.append(float(s))
+ offset.append(float(o))
+ self.coord_count, self.base_coords = int(coord_count), int(base_coords)
+ self.src, self.dst = src, dst
+ self.sign = torch.tensor(sign, dtype=torch.float32)
+ self.offset = torch.tensor(offset, dtype=torch.float32)
+
+ def joint_q(self, state: torch.Tensor, base: torch.Tensor | None = None) -> torch.Tensor:
+ """(N, coord_count). ``base`` (N, 7) fills a floating base. Omit it for a fixed one."""
+ q = torch.zeros(state.shape[0], self.coord_count, dtype=torch.float32, device=state.device)
+ if base is not None:
+ q[:, : self.base_coords] = base
+ elif self.base_coords == 7:
+ q[:, 6] = 1.0
+ sign, offset = self.sign.to(state.device), self.offset.to(state.device)
+ q[:, self.dst] = sign * state[:, self.src] + offset
+ return q
diff --git a/so101_pick_place/code/src/nedm/render/renderer.py b/so101_pick_place/code/src/nedm/render/renderer.py
new file mode 100644
index 0000000000000000000000000000000000000000..180b70e55dbd33c6627a3a7c7817fec9f6690818
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/renderer.py
@@ -0,0 +1,123 @@
+"""Batch renderer: meshes and per-world poses in, one image per world out.
+
+A renderer only. The NRD model stays the dynamics, and nothing is simulated to make a
+picture. The drawing is done by a backend (``nedm.render.backends``) chosen by name, and the
+scene, poses and cameras are the same whichever one draws them.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Mapping, Sequence
+
+import numpy as np
+import torch
+
+from nedm.render import backends
+from nedm.render.scene import Scene
+
+
+class BatchRenderer:
+ """``num_worlds`` copies of a :class:`Scene`, each with its own poses and cameras.
+
+ Poses and camera transforms may be torch tensors or numpy arrays. Torch tensors on the
+ render device are read in place. Anything else is copied there first.
+ """
+
+ def __init__(
+ self,
+ scene: Scene,
+ num_worlds: int,
+ width: int = 128,
+ height: int = 128,
+ cameras: int = 1,
+ fov_deg: float = 45.0,
+ device: Any = None,
+ shadows: bool = True,
+ sky: tuple[int, int, int] = (200, 215, 230),
+ backend: str = "newton",
+ camera_models: Sequence | None = None,
+ hdr: bool = False,
+ segment: bool = False,
+ ) -> None:
+ """``camera_models``: None (every camera a pinhole of ``fov_deg``, the original behaviour) or one model per
+ camera from :mod:`nedm.render.cameras` (``PinholeCamera(fovy_deg)``, ``CalibratedCamera(...)``; Newton only).
+ Rays are shared by all worlds; camera POSES stay per world. ``hdr``: keep the linear colour too (Newton).
+ ``segment``: keep the shape index per pixel too (Newton, ``Frames.shape_index_torch``)."""
+ self.scene, self.num_worlds = scene, int(num_worlds)
+ self.width, self.height, self.cameras = int(width), int(height), int(cameras)
+ self.body_names = scene.body_names
+ self.body_index = {name: i for i, name in enumerate(self.body_names)}
+ self.joint_index, self.coord_count = scene.joint_index, scene.coord_count
+ self.backend_name = backend
+ extra = {}
+ if camera_models is not None:
+ extra["camera_models"] = list(camera_models)
+ if hdr:
+ extra["hdr"] = True
+ if segment:
+ extra["segment"] = True
+ if extra and backend != "newton":
+ raise NotImplementedError(f"camera models, hdr and segment outputs need the newton backend, "
+ f"not {backend!r}")
+ self.backend = backends.make(backend)(scene, self.num_worlds, self.width, self.height, self.cameras,
+ fov_deg, device, shadows, sky, **extra)
+ self.device = self.backend.device
+ self._torch_device = torch.device("cuda:0" if "cuda" in str(self.device) else "cpu")
+ self._body_q: torch.Tensor | None = None
+
+ @property
+ def valid_mask(self) -> torch.Tensor | None:
+ """(C, H, W) bool: pixels with a ray in their camera model (None: no camera models, i.e. Newton's own pinholes,
+ or not a Newton renderer; with camera models it is always an array, all True when every pixel has a ray)."""
+ valid = getattr(self.backend, "valid", None)
+ return None if valid is None else torch.from_numpy(valid)
+
+ def set_camera_models(self, models: Sequence) -> None:
+ """New camera models (one per camera) for the next renders (Newton). Poses stay per world and per call."""
+ if self.backend_name != "newton":
+ raise NotImplementedError("camera models need the newton backend")
+ self.backend.set_camera_models(models)
+
+ @property
+ def interop(self) -> str | None:
+ """``"zero-copy"`` or ``"host-copy"``, once something has been rendered."""
+ return self.backend.interop
+
+ # ---- poses -----------------------------------------------------------------------
+
+ def set_joint_q(self, joint_q) -> None:
+ """Joint coordinates (N, coord_count) of a URDF scene. Runs forward kinematics."""
+ if not self.scene.articulated:
+ raise RuntimeError("this scene has no joints, give body transforms with set_body_q")
+ self._body_q = self.scene.body_transforms(self._tensor(joint_q, (self.num_worlds, self.coord_count)))
+
+ def set_body_q(self, body_q) -> None:
+ """World transforms (N, bodies, 7) of every body, in :attr:`body_names` order."""
+ self._body_q = self._tensor(body_q, (self.num_worlds, len(self.body_names), 7))
+
+ def body_q(self) -> torch.Tensor:
+ """Current body transforms (N, bodies, 7), on the render device."""
+ if self._body_q is None:
+ raise RuntimeError("no poses yet: call set_joint_q or set_body_q first")
+ return self._body_q
+
+ def joint_map(self, state_fields: Sequence[str], mapping: Mapping[str, Any]):
+ """A :class:`~nedm.render.poses.JointMap` from state fields to this scene's joints."""
+ from nedm.render.poses import JointMap
+ return JointMap(self.joint_index, self.coord_count, state_fields, mapping,
+ base_coords=7 if self.scene.floating else 0)
+
+ # ---- render ----------------------------------------------------------------------
+
+ def render(self, camera, *, joint_q=None, body_q=None):
+ """Render every world. ``camera`` is (N, 7), or (N, C, 7) with several cameras per world."""
+ if joint_q is not None:
+ self.set_joint_q(joint_q)
+ if body_q is not None:
+ self.set_body_q(body_q)
+ return self.backend.render(self.body_q(), self._tensor(camera, (self.num_worlds, self.cameras, 7)))
+
+ def _tensor(self, value, shape: tuple[int, ...]) -> torch.Tensor:
+ if isinstance(value, np.ndarray):
+ value = torch.from_numpy(np.ascontiguousarray(value, dtype=np.float32))
+ return value.detach().to(self._torch_device, torch.float32).reshape(shape)
diff --git a/so101_pick_place/code/src/nedm/render/scene.py b/so101_pick_place/code/src/nedm/render/scene.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce9b71b425f473a7fb90b9288e68f4bbda49804d
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/scene.py
@@ -0,0 +1,179 @@
+"""What gets drawn, described without reference to any renderer.
+
+A :class:`Scene` is plain data: the moving bodies as triangle meshes, optionally the URDF
+joint tree that poses them, and whatever every world shares (a ground, fixed meshes). Each
+renderer backend builds its own representation from it, so the same scene and the same poses
+can be drawn by more than one renderer and the pictures compared.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable, Mapping, Sequence
+
+import numpy as np
+import torch
+
+from nedm.render.poses import transform_from_matrix
+from nedm.render.urdf import UrdfModel, load_urdf
+
+Color = tuple[float, float, float]
+IDENTITY = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)
+
+
+@dataclass
+class MeshBody:
+ """One rigid body drawn as a triangle mesh, given in the body's own frame."""
+
+ name: str
+ vertices: np.ndarray | None = None # (V, 3)
+ faces: np.ndarray | None = None # (F, 3)
+ path: str | Path | None = None # anything trimesh loads, instead of vertices/faces
+ color: Color = (0.8, 0.8, 0.8)
+ scale: float = 1.0
+
+ def arrays(self) -> tuple[np.ndarray, np.ndarray]:
+ """Vertices (V, 3) float32 and faces (F, 3) int32, with the scale applied."""
+ if self.path is not None:
+ import trimesh
+ mesh = trimesh.load(str(self.path), force="mesh", process=False)
+ vertices, faces = np.asarray(mesh.vertices), np.asarray(mesh.faces)
+ else:
+ vertices, faces = np.asarray(self.vertices), np.asarray(self.faces)
+ return (vertices * self.scale).astype(np.float32), faces.reshape(-1, 3).astype(np.int32)
+
+
+@dataclass
+class Ground:
+ """A plane at ``height``, with a checker of thin tiles over ``extent`` (x0, x1, y0, y1).
+
+ The tiles are geometry, not a texture. They are what makes motion visible from a camera
+ that follows the robot, and they work on renderers and GPUs without texture support.
+ """
+
+ height: float = 0.0
+ color: Color = (0.60, 0.55, 0.46)
+ tile_size: float | None = 0.5
+ tile_color: Color = (0.47, 0.42, 0.34)
+ extent: tuple[float, float, float, float] = (-5.0, 13.0, -9.0, 9.0)
+ tile_thickness: float = 0.002
+
+ def tile_centers(self) -> list[tuple[float, float, float]]:
+ if self.tile_size is None:
+ return []
+ t = float(self.tile_size)
+ return [((i + 0.5) * t, (j + 0.5) * t, self.height + self.tile_thickness / 2)
+ for i in range(round(self.extent[0] / t), round(self.extent[1] / t))
+ for j in range(round(self.extent[2] / t), round(self.extent[3] / t))
+ if (i + j) % 2 == 0]
+
+ def tile_mesh(self) -> MeshBody | None:
+ """All tiles as ONE mesh, for renderers that pay per object rather than per triangle."""
+ centers = self.tile_centers()
+ if not centers:
+ return None
+ h = np.array([self.tile_size / 2, self.tile_size / 2, self.tile_thickness / 2])
+ corners = np.array([[x, y, z] for x in (-1, 1) for y in (-1, 1) for z in (-1, 1)]) * h
+ box = np.array([[0, 1, 3], [0, 3, 2], [4, 6, 7], [4, 7, 5], [0, 4, 5], [0, 5, 1],
+ [2, 3, 7], [2, 7, 6], [0, 2, 6], [0, 6, 4], [1, 5, 7], [1, 7, 3]])
+ vertices = np.concatenate([corners + np.array(c) for c in centers])
+ faces = np.concatenate([box + 8 * k for k in range(len(centers))])
+ return MeshBody("ground_tiles", vertices=vertices, faces=faces, color=self.tile_color)
+
+
+class Scene:
+ """What one world contains, and what all worlds share.
+
+ Two ways to describe the moving part:
+
+ * :meth:`from_urdf` for an articulated robot. Poses are given as joint coordinates and
+ :meth:`body_transforms` runs the forward kinematics.
+ * :meth:`from_meshes` for rigid bodies whose transforms the caller computes, for example
+ a chassis and four wheels, or the links of an arm with its own kinematics.
+ """
+
+ def __init__(self) -> None:
+ self.bodies: list[MeshBody] = []
+ self.statics: list[tuple[MeshBody, tuple[float, ...]]] = []
+ self.ground: Ground | None = None
+ self.urdf: UrdfModel | None = None
+ self._drawn_links: list[int] = []
+
+ @classmethod
+ def from_urdf(
+ cls,
+ path: str | Path,
+ floating: bool = True,
+ draw: str = "visual",
+ colors: Mapping[str, Color] | Callable[[str], Color | None] | None = None,
+ ) -> "Scene":
+ """``draw``: ``"visual"`` (the URDF's visual geometry) or ``"collision"``.
+
+ ``colors`` maps a link name to a color, as a dict or a function. Links are drawn in
+ flat colors.
+ """
+ scene = cls()
+ scene.urdf = load_urdf(path, floating=floating, draw=draw)
+ pick = colors if callable(colors) else (colors or {}).get
+ for i, link in enumerate(scene.urdf.links):
+ if link.vertices is None:
+ continue
+ color = pick(link.name)
+ body = MeshBody(link.name, vertices=link.vertices, faces=link.faces)
+ if color is not None:
+ body.color = tuple(color)
+ scene.bodies.append(body)
+ scene._drawn_links.append(i)
+ return scene
+
+ @classmethod
+ def from_meshes(cls, bodies: Sequence[MeshBody]) -> "Scene":
+ scene = cls()
+ scene.bodies = list(bodies)
+ return scene
+
+ # ---- shared by every world -------------------------------------------------------
+
+ def add_ground(self, height: float = 0.0, **options) -> "Scene":
+ """A ground plane with a tile checker. See :class:`Ground` for the options."""
+ self.ground = Ground(height=height, **options)
+ return self
+
+ def add_static_mesh(self, mesh: MeshBody, transform: Sequence[float] | None = None) -> "Scene":
+ """A fixed mesh every world sees, for terrain or obstacles. ``transform`` is 7 numbers."""
+ self.statics.append((mesh, IDENTITY if transform is None else tuple(float(v) for v in transform)))
+ return self
+
+ # ---- what the caller needs to build poses ----------------------------------------
+
+ @property
+ def articulated(self) -> bool:
+ return self.urdf is not None
+
+ @property
+ def floating(self) -> bool:
+ return self.urdf is not None and self.urdf.floating
+
+ @property
+ def body_names(self) -> list[str]:
+ return [body.name for body in self.bodies]
+
+ @property
+ def coord_count(self) -> int:
+ return self.urdf.coord_count if self.urdf is not None else 0
+
+ @property
+ def joint_index(self) -> dict[str, int]:
+ """URDF joint name -> index of its coordinate in a world's ``joint_q`` row."""
+ return self.urdf.joint_index if self.urdf is not None else {}
+
+ def body_transforms(self, joint_q: torch.Tensor) -> torch.Tensor:
+ """Forward kinematics: joint coordinates (N, coord_count) -> body transforms (N, bodies, 7)."""
+ if self.urdf is None:
+ raise RuntimeError("this scene has no joints, give body transforms directly")
+ rotation, position = self.urdf.forward_kinematics(joint_q)
+ rotation, position = rotation[:, self._drawn_links], position[:, self._drawn_links]
+ matrix = torch.zeros(*rotation.shape[:2], 4, 4, dtype=torch.float32, device=joint_q.device)
+ matrix[..., :3, :3], matrix[..., :3, 3], matrix[..., 3, 3] = rotation, position, 1.0
+ return transform_from_matrix(matrix)
diff --git a/so101_pick_place/code/src/nedm/render/so101.py b/so101_pick_place/code/src/nedm/render/so101.py
new file mode 100644
index 0000000000000000000000000000000000000000..43f75ea5c3abd551f605600e6c7cece552079917
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/so101.py
@@ -0,0 +1,2082 @@
+"""SO101 + cube + goal scene for the batch renderer: the arm of the grasp NRD study, drawn from the visual meshes of the
+pinned Menagerie MJCF, the collector's table and 30 mm cube, a goal marker, and up to three cameras: ``front`` (fixed,
+across the table, facing the arm), ``top`` (fixed, straight down over the workspace) and ``wrist`` (the MJCF
+``wrist_cam``).
+
+ r = SO101Renderer(num_worlds=1024, backend="newton") # Warp: any CUDA GPU (luffy 5090), AMD, CPU
+ rgb = r.render(q, cube_pos, cube_quat_wxyz, goal) # [B, 2, 128, 128, 3] uint8, cameras in r.cameras order
+ rgb, depth = r.render(..., depth=True) # depth [B, 2, H, W] float32: z-depth (m), 0 = no hit
+ r = SO101Renderer(1024, 224, 224, cameras=("front", "wrist")) # ACT input (spec v2 B7); or ("top", "wrist")
+ rgb = r.render_state(world_state, goal) # a WorldState of the NRD or of MuJoCo, same function
+
+One renderer has one resolution and one field of view for all its cameras (the wrist camera's fovy 61 deg, as
+``BatchRenderer`` takes one ``fov_deg``); the fixed cameras are placed so that 61 deg frames the workspace. The REAL
+setup (off by default; Newton only) instead draws the calibrated real cameras (fisheye / radial-tangential lens models
+from the calibration contract, a crop box of the real 640 x 480 image per camera) in a light-box scene:
+
+ real = RealScene.from_path("~/so101_r2s_claude/scene/real_scene_v1.json") # fitted scene + crops + DR ranges
+ r = SO101Renderer(1024, 224, 224, real=real) # cameras ("external", "wrist"), student crops
+ dr = RealDR.from_dict(real.dr)
+ rgb = r.render_dr(q, cube_pos, cube_quat, goal, draw=dr.draw(r.scene, 1024, gen)) # per-world DR
+ r.set_lights(dr.lights(real.lights, gen)); r.set_camera_models(dr.camera_models(r.scene, gen)) # per call
+ rgb = ImageFX.from_dict(real.image_fx).apply(rgb[:, c], fx_draw, camera=name) # nominal + random camera effects
+
+The student crop (``nedm.render.student_view``) is the same code the real-robot script uses (``hw_lib``).
+
+Backend: Newton / Warp (``backend="newton"``). The study also had a Madrona backend; it is not part of this release
+(the ``madrona`` branches below are not reachable: ``nedm.render.backends.BACKENDS``).
+
+Frames and units: world z up, table top at z = 0, arm base frame = world frame (as in the collector's scene,
+``nedm.contact_nrd.collect.so101_grasp.build_spec``). Joint angles in rad, in ``so101.xml`` order (jaw = joint 5),
+as in the NRD data. Quaternions given to and returned by this module are w x y z (NRD, MuJoCo); the renderer's own
+transforms are x y z w and are converted here. Depth is MuJoCo's convention (distance along the camera axis), not the
+renderer's ray length.
+
+The same function draws NRD states (:func:`poses_from_nrd`) and MuJoCo states (:func:`poses_from_qpos`); identical
+states give identical pictures. With distinct cube face colours, give the TRUE cube orientation (``WorldState``), not
+the NRD's canonical relabelling; a one-colour cube looks the same under all 24 relabellings.
+
+Mesh export (:meth:`SO101Assets.from_mjcf`) needs ``mujoco``; everything else needs torch and numpy only, and the
+assets can be cached to one ``.npz`` (:meth:`SO101Assets.save` / :meth:`SO101Assets.load`).
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from dataclasses import dataclass, field, replace
+from pathlib import Path
+from typing import Sequence
+
+import numpy as np
+import torch
+
+from nedm.render.scene import MeshBody, Scene
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+CONFIG = REPO_ROOT / "configs/contact_nrd/collection/so101_grasp.json"
+VIEWS = ("front", "top", "wrist") # the cameras a scene can hold
+CAMERAS = ("front", "wrist") # the default set
+JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper")
+# colours of the collector's MuJoCo scene (build_spec); the arm keeps its MJCF material colours
+TABLE_COLOR = (0.55, 0.5, 0.45)
+CUBE_COLOR = (0.15, 0.35, 0.85)
+GOAL_COLOR = (0.2, 0.72, 0.3)
+# optional distinct face colours, order +x, -x, +y, -y, +z, -z of the cube frame
+FACE_COLORS = ((0.85, 0.15, 0.15), (0.95, 0.5, 0.1), (0.15, 0.35, 0.85), (0.92, 0.92, 0.92), (0.75, 0.2, 0.75),
+ (0.1, 0.75, 0.8))
+SKY = (200, 215, 230)
+# Front camera: across the table, facing the arm, 45 deg down. With the shared 61 deg field of view it frames the
+# whole workspace annulus (r 0.15-0.27 m around the pan axis, +-75 deg) from the table up to z = 0.18 m, with the
+# cube's half diagonal as margin (worst point at 0.9 of the half width), and the arm base.
+FRONT_EYE = (0.616, 0.0, 0.456)
+FRONT_TARGET = (0.22, 0.0, 0.06)
+# Top camera: straight down over the middle of the annulus (x 0.057-0.330 m, |y| <= 0.282 m with the cube's half
+# diagonal), image up = world +x (arm base in the lower half, the robot's left = image left). At fovy 61 deg and
+# 0.66 m it frames that box from the table up to z = 0.15 m (worst point at 0.95 of the half width); 6.1 mm per pixel
+# on the table at 128 px, 3.5 mm at 224 px.
+TOP_EYE = (0.19, 0.0, 0.66)
+TOP_TARGET = (0.19, 0.0, 0.0)
+TOP_UP = (1.0, 0.0, 0.0)
+GOAL_HALF = 0.023 # goal plate half side (m): a 30 mm cube on the goal leaves 8 mm of plate on every side
+GOAL_THICKNESS = 0.001 # m; the plate lies on the table top, so a cube resting on it sinks 1 mm into it (hidden)
+GOAL_FRAME_WIDTH = 0.006 # m, the "frame" style: an outline of this width, outer half side GOAL_HALF
+# "tray" style (build8_tray_student.md): a VISUAL-ONLY tray at the goal pose (no collision anywhere: the MuJoCo scene and
+# the NRD do not know it). A flat base slightly larger than the cube's 30 mm footprint (inner side 40 mm) with a low
+# rim (5 mm high, 4 mm wide); base light cream, rim orange, against the blue cube and the grey-brown table. The base is
+# 1 mm thick on the table top, so a cube resting on the goal hides 1 mm of it (as the plate); the rim intersects the
+# cube only when the cube is more than 5 mm off the tray centre (visual overlap, no contact).
+TRAY_INNER_HALF = 0.020 # m, half side of the inner square
+TRAY_RIM_WIDTH = 0.004 # m
+TRAY_RIM_HEIGHT = 0.005 # m above the table top
+TRAY_BASE_THICKNESS = 0.001
+TRAY_COLOR = (0.93, 0.91, 0.84)
+TRAY_RIM_COLOR = (0.98, 0.62, 0.15)
+# "block" style (build9_viral_student.md): a VISUAL-ONLY flat colour block at the goal pose (no collision anywhere):
+# a square of 50 mm side, 1 mm thick on the table top (a cube resting on it hides 1 mm of it), saturated red against the
+# blue cube and the grey-brown table. The lenient success of build9 = cube centre inside this square (any yaw).
+BLOCK_HALF = 0.025 # m, half side
+BLOCK_THICKNESS = 0.001 # m
+BLOCK_COLOR = (0.85, 0.12, 0.12)
+HIDDEN_Z = -100.0 # z of a hidden goal marker (far below the table)
+BOX_FACES = np.array([[0, 1, 3], [0, 3, 2], [4, 6, 7], [4, 7, 5], [0, 4, 5], [0, 5, 1],
+ [2, 3, 7], [2, 7, 6], [0, 2, 6], [0, 6, 4], [1, 5, 7], [1, 7, 3]], dtype=np.int32)
+# BOX_FACES rows of each cube face, order +x, -x, +y, -y, +z, -z
+FACE_ROWS = ((2, 3), (0, 1), (6, 7), (4, 5), (10, 11), (8, 9))
+
+
+def box_mesh(half, center=(0.0, 0.0, 0.0)) -> tuple[np.ndarray, np.ndarray]:
+ """Box with half sizes ``half`` (3,) around ``center``: vertices (8, 3) float32, faces (12, 3) int32."""
+ corners = np.array([[x, y, z] for x in (-1, 1) for y in (-1, 1) for z in (-1, 1)], dtype=np.float64)
+ return (corners * np.asarray(half, float) + np.asarray(center, float)).astype(np.float32), BOX_FACES.copy()
+
+
+def prism_mesh(corners_xy, z0: float, z1: float, center=None) -> tuple[np.ndarray, np.ndarray]:
+ """Closed prism over a convex polygon ``corners_xy`` (k, 2) from z0 to z1, outward-facing triangles (Newton culls
+ back faces), vertices relative to ``center`` (3,) (default: the polygon centroid at z = 0): (2k, 3) float32,
+ (4k - 4, 3) int32."""
+ c = np.asarray(corners_xy, np.float64).reshape(-1, 2)
+ mid = c.mean(0)
+ c = c[np.argsort(np.arctan2(c[:, 1] - mid[1], c[:, 0] - mid[0]))] # counter-clockwise from above
+ k = len(c)
+ v = np.concatenate([np.c_[c, np.full(k, z0)], np.c_[c, np.full(k, z1)]])
+ faces = [[k, k + i, k + i + 1] for i in range(1, k - 1)] # top (+z)
+ faces += [[0, i + 1, i] for i in range(1, k - 1)] # bottom (-z)
+ for i in range(k):
+ j = (i + 1) % k
+ faces += [[i, j, k + j], [i, k + j, k + i]] # sides, outward
+ center = np.r_[mid, 0.0] if center is None else np.asarray(center, np.float64)
+ return (v - center).astype(np.float32), np.array(faces, np.int32)
+
+
+def load_config(path: str | Path = CONFIG) -> dict:
+ return json.loads(Path(path).read_text())
+
+
+def vendor_xml(cfg: dict | None = None) -> Path:
+ """Path of the pinned ``so101.xml`` the collector loads (same rule as ``so101_grasp.vendor_model``)."""
+ cfg = cfg or load_config()
+ mpath = REPO_ROOT / cfg["source_manifest"]
+ manifest = json.loads(mpath.read_text())
+ path = mpath.parent / manifest["source"]["local_path"] / manifest["model"]["path"]
+ if not path.exists():
+ raise FileNotFoundError(f"{path} is missing: run python -I contact_nrd/so101_grasp/fetch_sources.py")
+ return path
+
+
+# ---- quaternions (w x y z), batched, any float dtype ----------------------------------------------------------------
+def qmul(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
+ aw, ax, ay, az = a.unbind(-1)
+ bw, bx, by, bz = b.unbind(-1)
+ return torch.stack([aw * bw - ax * bx - ay * by - az * bz, aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw], -1)
+
+
+def qrot(q: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
+ """Rotate vectors ``v`` (..., 3) by unit quaternions ``q`` (..., 4) w x y z."""
+ w, u = q[..., :1], q[..., 1:]
+ t = 2.0 * torch.cross(u, v, dim=-1)
+ return v + w * t + torch.cross(u, t, dim=-1)
+
+
+def xyzw(q: torch.Tensor) -> torch.Tensor:
+ return torch.cat([q[..., 1:], q[..., :1]], -1)
+
+
+def wxyz(q: torch.Tensor) -> torch.Tensor:
+ return torch.cat([q[..., 3:], q[..., :3]], -1)
+
+
+def yaw_quat(yaw: torch.Tensor) -> torch.Tensor:
+ """Quaternion w x y z of a turn by ``yaw`` (rad) about world z."""
+ z = torch.zeros_like(yaw)
+ return torch.stack([torch.cos(yaw / 2), z, z, torch.sin(yaw / 2)], -1)
+
+
+def flat_yaw(quat: torch.Tensor) -> torch.Tensor:
+ """Heading (rad) of a box orientation (..., 4) w x y z: the angle of the box axis that is closest to horizontal
+ among the two that are not closest to vertical. For a box lying flat on any face this is its yaw mod 90 deg."""
+ w, x, y, z = quat.unbind(-1)
+ # columns of the rotation matrix = box axes in the world
+ cols = torch.stack([
+ torch.stack([1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)], -1),
+ torch.stack([2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)], -1),
+ torch.stack([2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)], -1)], -2) # (..., 3, 3)
+ up = cols[..., 2].abs().argmax(-1) # axis closest to vertical
+ pick = torch.where(up == 0, 1, 0) # first remaining axis
+ axis = torch.gather(cols, -2, pick[..., None, None].expand(*pick.shape, 1, 3)).squeeze(-2)
+ return torch.atan2(axis[..., 1], axis[..., 0])
+
+
+# ---- assets -----------------------------------------------------------------------------------------------------
+@dataclass
+class Link:
+ """One body of the MJCF tree. ``pos``/``quat`` (w x y z) in the parent frame; a hinge about ``axis`` at the body
+ origin turns by joint ``qadr`` (None: welded to the parent)."""
+
+ name: str
+ parent: str
+ pos: tuple[float, float, float]
+ quat: tuple[float, float, float, float]
+ qadr: int | None = None
+ axis: tuple[float, float, float] | None = None
+
+
+@dataclass
+class SO101Assets:
+ """What the renderer needs from the MJCF: the body tree, one mesh per (body, colour) in its body frame, and the
+ wrist camera (``body``, ``pos``, ``quat`` w x y z in the body frame, ``fovy_deg``)."""
+
+ links: list[Link]
+ meshes: list[tuple[str, MeshBody]]
+ wrist_cam: dict
+ source: str = ""
+
+ @classmethod
+ def from_mjcf(cls, xml: str | Path | None = None) -> "SO101Assets":
+ """Visual geoms (groups 1-2) of ``so101.xml`` (default: the collector's pinned copy). The wrist camera lens is
+ left out: the camera sits inside it and a ray tracer has no near plane. The camera board (pcb) stays: it is
+ behind the camera (+9.5 mm along the camera's z), so only the front camera sees it."""
+ import mujoco
+ xml = Path(xml) if xml is not None else vendor_xml()
+ m = mujoco.MjModel.from_xml_path(str(xml))
+ name = lambda kind, i: mujoco.mj_id2name(m, kind, i) # noqa: E731
+ bodies = [name(mujoco.mjtObj.mjOBJ_BODY, b) for b in range(m.nbody)]
+ groups: dict[tuple[str, tuple], list] = {}
+ for g in range(m.ngeom):
+ if m.geom_group[g] not in (1, 2) or name(mujoco.mjtObj.mjOBJ_GEOM, g) == "wrist_camera_lens":
+ continue
+ rgba = m.mat_rgba[m.geom_matid[g]] if m.geom_matid[g] >= 0 else m.geom_rgba[g]
+ r = np.zeros(9)
+ mujoco.mju_quat2Mat(r, m.geom_quat[g])
+ t = m.geom_type[g]
+ if t == mujoco.mjtGeom.mjGEOM_MESH:
+ mid = m.geom_dataid[g]
+ v = m.mesh_vert[m.mesh_vertadr[mid]: m.mesh_vertadr[mid] + m.mesh_vertnum[mid]].astype(np.float64)
+ f = m.mesh_face[m.mesh_faceadr[mid]: m.mesh_faceadr[mid] + m.mesh_facenum[mid]].astype(np.int64)
+ elif t == mujoco.mjtGeom.mjGEOM_BOX:
+ v, f = box_mesh(m.geom_size[g])
+ v = v.astype(np.float64)
+ else:
+ raise ValueError(f"visual geom {g} of type {t} is not handled")
+ key = (bodies[m.geom_bodyid[g]], tuple(float(c) for c in np.round(rgba[:3], 3)))
+ groups.setdefault(key, []).append((v @ r.reshape(3, 3).T + m.geom_pos[g], f))
+ meshes = []
+ for (body, rgb), parts in sorted(groups.items()):
+ offsets = np.cumsum([0] + [len(v) for v, _ in parts])[:-1]
+ vertices = np.concatenate([v for v, _ in parts]).astype(np.float32)
+ faces = np.concatenate([f + o for (_, f), o in zip(parts, offsets)]).astype(np.int32)
+ meshes.append((body, MeshBody(f"{body}#{len(meshes)}", vertices=vertices, faces=faces, color=rgb)))
+ links = []
+ for b in range(1, m.nbody):
+ jn = [j for j in range(m.njnt) if m.jnt_bodyid[j] == b]
+ if jn:
+ if m.jnt_type[jn[0]] != mujoco.mjtJoint.mjJNT_HINGE or np.abs(m.jnt_pos[jn[0]]).max() > 0:
+ raise ValueError(f"body {bodies[b]}: only hinges at the body origin are handled")
+ links.append(Link(bodies[b], bodies[m.body_parentid[b]], tuple(m.body_pos[b].tolist()),
+ tuple(m.body_quat[b].tolist()), int(m.jnt_qposadr[jn[0]]) if jn else None,
+ tuple(m.jnt_axis[jn[0]].tolist()) if jn else None))
+ c = m.camera("wrist_cam").id
+ cam = {"body": bodies[m.cam_bodyid[c]], "pos": m.cam_pos[c].tolist(), "quat": m.cam_quat[c].tolist(),
+ "fovy_deg": float(m.cam_fovy[c])}
+ return cls(links, meshes, cam, str(xml))
+
+ def save(self, path: str | Path) -> None:
+ arrays = {}
+ for i, (_, mesh) in enumerate(self.meshes):
+ arrays[f"v{i}"], arrays[f"f{i}"] = mesh.arrays()
+ meta = {"links": [vars(link) for link in self.links], "wrist_cam": self.wrist_cam, "source": self.source,
+ "meshes": [{"body": body, "name": mesh.name, "color": list(mesh.color)} for body, mesh in self.meshes]}
+ np.savez_compressed(path, meta=np.array(json.dumps(meta)), **arrays)
+
+ @classmethod
+ def load(cls, path: str | Path) -> "SO101Assets":
+ z = np.load(path)
+ meta = json.loads(str(z["meta"]))
+ links = [Link(**{**x, "pos": tuple(x["pos"]), "quat": tuple(x["quat"]),
+ "axis": tuple(x["axis"]) if x["axis"] is not None else None}) for x in meta["links"]]
+ meshes = [(x["body"], MeshBody(x["name"], vertices=z[f"v{i}"], faces=z[f"f{i}"], color=tuple(x["color"])))
+ for i, x in enumerate(meta["meshes"])]
+ return cls(links, meshes, meta["wrist_cam"], meta["source"])
+
+ @property
+ def triangles(self) -> int:
+ return int(sum(len(mesh.faces) for _, mesh in self.meshes))
+
+
+def load_assets(cache: str | Path | None = None, xml: str | Path | None = None) -> SO101Assets:
+ """Assets from ``cache`` if it exists, else exported from the MJCF (and written to ``cache`` if given)."""
+ if cache is not None and Path(cache).exists():
+ return SO101Assets.load(cache)
+ assets = SO101Assets.from_mjcf(xml)
+ if cache is not None:
+ Path(cache).parent.mkdir(parents=True, exist_ok=True)
+ assets.save(cache)
+ return assets
+
+
+# ---- kinematics ---------------------------------------------------------------------------------------------------
+class SO101Kinematics:
+ """Batched torch forward kinematics of the MJCF tree (MuJoCo's rule: x_child = x_parent + R_parent pos,
+ R_child = R_parent R(quat) R(axis, q)). ``bodies`` = the links in tree order (parents first)."""
+
+ def __init__(self, links: Sequence[Link], device=None, dtype=torch.float64):
+ self.links, self.device, self.dtype = list(links), torch.device(device or "cpu"), dtype
+ self.bodies = [link.name for link in self.links]
+ index = {name: i for i, name in enumerate(self.bodies)}
+ self.parent = [index.get(link.parent, -1) for link in self.links]
+ if any(p >= i for i, p in enumerate(self.parent)):
+ raise ValueError("links must list parents before children")
+ kw = dict(device=self.device, dtype=dtype)
+ self.pos = torch.tensor([link.pos for link in self.links], **kw)
+ self.quat = torch.tensor([link.quat for link in self.links], **kw)
+ self.axis = torch.tensor([link.axis or (0.0, 0.0, 1.0) for link in self.links], **kw)
+
+ def __call__(self, q: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """q [B, 6] (rad) -> world positions [B, bodies, 3] (m) and orientations [B, bodies, 4] w x y z."""
+ q = q.to(self.device, self.dtype)
+ n = q.shape[0]
+ pos, quat = [], []
+ for i, link in enumerate(self.links):
+ p, r = self.pos[i].expand(n, 3), self.quat[i].expand(n, 4)
+ if self.parent[i] >= 0:
+ pp, pq = pos[self.parent[i]], quat[self.parent[i]]
+ p, r = pp + qrot(pq, p), qmul(pq, r)
+ if link.qadr is not None:
+ half = 0.5 * q[:, link.qadr: link.qadr + 1]
+ r = qmul(r, torch.cat([torch.cos(half), torch.sin(half) * self.axis[i]], -1))
+ pos.append(p)
+ quat.append(r)
+ return torch.stack(pos, 1), torch.stack(quat, 1)
+
+
+# ---- state layouts ------------------------------------------------------------------------------------------------
+def poses_from_nrd(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """NRD / data state [..., 2, S] (body 0 = arm: q[0:6]; body 1 = cube: pos[0:3], quat w x y z[3:7]) ->
+ (q [..., 6], cube_pos [..., 3], cube_quat [..., 4])."""
+ return x[..., 0, 0:6], x[..., 1, 0:3], x[..., 1, 3:7]
+
+
+def poses_from_qpos(qpos: torch.Tensor, qadr: Sequence[int] = range(6), cube_adr: int = 6):
+ """MuJoCo qpos [..., nq] of the collector's scene (arm joints at ``qadr``, cube free joint at ``cube_adr``) ->
+ (q [..., 6], cube_pos [..., 3], cube_quat [..., 4] w x y z)."""
+ qpos = torch.as_tensor(qpos)
+ return qpos[..., list(qadr)], qpos[..., cube_adr: cube_adr + 3], qpos[..., cube_adr + 3: cube_adr + 7]
+
+
+# ---- scene ----------------------------------------------------------------------------------------------------------
+class SO101Scene:
+ """The renderer-independent part: the :class:`~nedm.render.scene.Scene` and the map from a state to the body and
+ camera transforms (x y z w, float32) of every world.
+
+ Bodies, in order: the moving arm meshes (one per body and colour), the cube (1 mesh, or 6 with ``cube_colors``
+ of 6 colours), the goal marker (none with ``goal=None``; 2 meshes for the tray). Static: the arm base meshes and
+ the table. ``goal``: ``"plate"`` (a 1 mm square plate on the table, side 2 * GOAL_HALF), ``"frame"`` (its outline)
+ or ``"tray"`` (a visual-only tray: 40 mm inner base, 5 mm rim; ``TRAY_*`` constants) or ``"block"`` (a visual-only
+ flat colour square of 50 mm side; ``BLOCK_*`` constants).
+ ``cameras``: names from VIEWS, in the order of the output's camera axis.
+ ``table_body``: draw the table as the LAST body (fixed pose) instead of a static mesh, so that a backend with
+ per-world body colours (Newton: :meth:`SO101Renderer.set_appearance`) can colour it per world (build9's visual
+ randomisation); the pictures are the same as with the static table.
+
+ ``plate_depth`` (real scene; None = off, the old plate): the goal plate's mesh is this deep (m, >= the scene's
+ ``plate_thickness``) below its nominal top, so a per-world plate thickness up to ``plate_depth`` is a vertical
+ shift of the plate (``transforms(..., plate_dz=)``; :class:`RealDR` ``plate_thickness``); the part below the mat
+ top is hidden in the mat.
+ ``real``: a :class:`RealScene` (off by default) builds the REAL setup instead (:meth:`_init_real`): no sim table;
+ cameras from REAL_VIEWS (default ``external`` + ``wrist``, calibrated, :attr:`camera_models`); everything is a body
+ (per-world colours and poses for all of it): the moving arm meshes, the cube, the goal plate (the 50 mm ``block``
+ style in the plate colour; none with ``goal=None``), the arm base meshes, then the floor, the mat and the walls
+ (:attr:`env_pose`, overridable per world). :attr:`groups` = body indices of REAL_GROUPS.
+ """
+
+ def __init__(self, assets: SO101Assets | None = None, cube_colors=None, goal: str | None = "plate",
+ front_eye=FRONT_EYE, front_target=FRONT_TARGET, device=None, cfg: dict | None = None,
+ cameras: Sequence[str] | None = None, top_eye=TOP_EYE, top_target=TOP_TARGET,
+ table_body: bool = False, real: "RealScene | None" = None, plate_depth: float | None = None):
+ from nedm.render import cameras as cams
+ self.real, self.camera_models = real, None
+ self.plate_depth = None
+ if plate_depth is not None and real is None:
+ raise ValueError("plate_depth (plate thickness randomisation) needs the real scene")
+ if real is not None:
+ self._init_real(real, assets, cube_colors, goal, front_eye, front_target, device, cfg, cameras, top_eye,
+ top_target, plate_depth)
+ return
+ cameras = CAMERAS if cameras is None else cameras
+ self.cameras = tuple(cameras)
+ self.table_body = bool(table_body)
+ if not self.cameras or len(set(self.cameras)) != len(self.cameras) or not set(self.cameras) <= set(VIEWS):
+ raise ValueError(f"cameras {cameras!r}: distinct names from {VIEWS}")
+ self.assets = assets = assets if assets is not None else load_assets()
+ cfg = cfg or load_config()
+ self.device = torch.device(device or "cpu")
+ self.kin = SO101Kinematics(assets.links, self.device)
+ moving = self._moving_bodies()
+ bodies, mesh_body = [], []
+ for body, mesh in assets.meshes:
+ if body in moving:
+ bodies.append(mesh)
+ mesh_body.append(self.kin.bodies.index(body))
+ self.mesh_body = torch.tensor(mesh_body, device=self.device)
+ # cube: the collector's 30 mm box, one colour or one colour per face
+ self.cube_half = 0.5 * float(cfg["cube"]["size_m"])
+ v, f = box_mesh([self.cube_half] * 3)
+ colors = CUBE_COLOR if cube_colors is None else cube_colors
+ if len(colors) == 6 and not isinstance(colors[0], (int, float)):
+ for k, rows in enumerate(FACE_ROWS):
+ ff = f[list(rows)]
+ used, inv = np.unique(ff, return_inverse=True)
+ bodies.append(MeshBody(f"cube_face{k}", vertices=v[used], faces=inv.reshape(-1, 3).astype(np.int32),
+ color=tuple(colors[k])))
+ else:
+ bodies.append(MeshBody("cube", vertices=v, faces=f, color=tuple(colors)))
+ self.cube_meshes = len(bodies) - len(mesh_body)
+ self.goal_style = goal
+ if goal == "plate":
+ v, f = box_mesh([GOAL_HALF, GOAL_HALF, GOAL_THICKNESS / 2], (0.0, 0.0, GOAL_THICKNESS / 2))
+ bodies.append(MeshBody("goal", vertices=v, faces=f, color=GOAL_COLOR))
+ elif goal == "frame":
+ h, w, t = GOAL_HALF, GOAL_FRAME_WIDTH, GOAL_THICKNESS
+ parts = [box_mesh([h, w / 2, t / 2], (0.0, s * (h - w / 2), t / 2)) for s in (-1, 1)]
+ parts += [box_mesh([w / 2, h - w, t / 2], (s * (h - w / 2), 0.0, t / 2)) for s in (-1, 1)]
+ bodies.append(MeshBody("goal", vertices=np.concatenate([p[0] for p in parts]),
+ faces=np.concatenate([p[1] + 8 * k for k, p in enumerate(parts)]), color=GOAL_COLOR))
+ elif goal == "tray":
+ hi, w, hr, tb = TRAY_INNER_HALF, TRAY_RIM_WIDTH, TRAY_RIM_HEIGHT, TRAY_BASE_THICKNESS
+ ho = hi + w
+ v, f = box_mesh([ho, ho, tb / 2], (0.0, 0.0, tb / 2))
+ bodies.append(MeshBody("goal", vertices=v, faces=f, color=TRAY_COLOR))
+ parts = [box_mesh([ho, w / 2, hr / 2], (0.0, s * (ho - w / 2), hr / 2)) for s in (-1, 1)]
+ parts += [box_mesh([w / 2, hi, hr / 2], (s * (ho - w / 2), 0.0, hr / 2)) for s in (-1, 1)]
+ bodies.append(MeshBody("goal_rim", vertices=np.concatenate([p[0] for p in parts]),
+ faces=np.concatenate([p[1] + 8 * k for k, p in enumerate(parts)]),
+ color=TRAY_RIM_COLOR))
+ elif goal == "block":
+ v, f = box_mesh([BLOCK_HALF, BLOCK_HALF, BLOCK_THICKNESS / 2], (0.0, 0.0, BLOCK_THICKNESS / 2))
+ bodies.append(MeshBody("goal", vertices=v, faces=f, color=BLOCK_COLOR))
+ elif goal is not None:
+ raise ValueError(f"goal style {goal!r}: 'plate', 'frame', 'tray', 'block' or None")
+ self.goal_meshes = 0 if goal is None else (2 if goal == "tray" else 1)
+ t = cfg["table"]
+ tv, tf = box_mesh([0.5 * t["size_xy_m"][0], 0.5 * t["size_xy_m"][1], 0.5 * t["thickness_m"]])
+ table_mesh = MeshBody("table", vertices=tv, faces=tf, color=TABLE_COLOR)
+ self.table_pose = torch.tensor([*t["center_xy_m"], -0.5 * t["thickness_m"], 0.0, 0.0, 0.0, 1.0],
+ dtype=torch.float64, device=self.device)
+ if self.table_body:
+ bodies.append(table_mesh)
+ self.scene = Scene.from_meshes(bodies)
+ # static: the base (welded to the world) and the table, as the collector builds them
+ zero = torch.zeros(1, 6, dtype=torch.float64, device=self.device)
+ bpos, bquat = self.kin(zero)
+ for body, mesh in assets.meshes:
+ if body not in moving:
+ i = self.kin.bodies.index(body)
+ self.scene.add_static_mesh(mesh, torch.cat([bpos[0, i], xyzw(bquat[0, i])]).tolist())
+ if not self.table_body:
+ self.scene.add_static_mesh(table_mesh, self.table_pose.tolist())
+ # cameras: front and top fixed (x y z, qx qy qz qw; look along -z, +y up); wrist = the MJCF camera on its body
+ f64 = lambda v: torch.tensor([v], dtype=torch.float64) # noqa: E731
+ self.front = cams.look_at(f64(front_eye), f64(front_target))[0].to(self.device)
+ self.top = cams.look_at(f64(top_eye), f64(top_target), up=TOP_UP)[0].to(self.device)
+ cam = assets.wrist_cam
+ self.cam_body = self.kin.bodies.index(cam["body"])
+ self.cam_pos = torch.tensor(cam["pos"], dtype=torch.float64, device=self.device)
+ self.cam_quat = torch.tensor(cam["quat"], dtype=torch.float64, device=self.device)
+ self.fovy_deg = float(cam["fovy_deg"])
+
+ def _init_real(self, real: "RealScene", assets, cube_colors, goal, front_eye, front_target, device, cfg, cameras,
+ top_eye, top_target, plate_depth=None) -> None:
+ """The real-setup scene (class docstring, :class:`RealScene`)."""
+ from nedm.render import cameras as cams
+ self.cameras = tuple(REAL_CAMERAS if cameras is None else cameras)
+ if not self.cameras or len(set(self.cameras)) != len(self.cameras) or not set(self.cameras) <= set(REAL_VIEWS):
+ raise ValueError(f"cameras {cameras!r}: distinct names from {REAL_VIEWS} in the real scene")
+ self.table_body = False
+ self.assets = assets = assets if assets is not None else load_assets()
+ cfg = cfg or load_config()
+ self.device = torch.device(device or "cpu")
+ self.kin = SO101Kinematics(assets.links, self.device)
+ moving = self._moving_bodies()
+ hidden = set(real.hide_bodies or ())
+ if hidden - set(self.kin.bodies):
+ raise ValueError(f"hide_bodies {sorted(hidden - set(self.kin.bodies))} are not bodies of the MJCF")
+ groups: dict[str, list[int]] = {g: [] for g in REAL_GROUPS}
+ bodies, mesh_body = [], []
+ for body, mesh in assets.meshes:
+ if body in moving and body not in hidden:
+ part = arm_part(mesh.color)
+ groups[part].append(len(bodies))
+ bodies.append(replace(mesh, color=real.color(part)))
+ mesh_body.append(self.kin.bodies.index(body))
+ wrist_cal = real.calib["cameras"].get("wrist")
+ board = real.board_mesh(wrist_cal["T_parent_cam"]) if wrist_cal is not None else None
+ if board is not None: # the real camera board, on the wrist camera's parent body
+ if wrist_cal["parent"] not in self.kin.bodies:
+ raise ValueError(f"wrist camera parent {wrist_cal['parent']!r} is not a body of the MJCF")
+ groups["board"].append(len(bodies))
+ bodies.append(MeshBody("camera_board", vertices=board[0], faces=board[1], color=real.color("board")))
+ mesh_body.append(self.kin.bodies.index(wrist_cal["parent"]))
+ fixed_parts = []
+ for part in real.parts:
+ if part["body"] not in self.kin.bodies:
+ raise ValueError(f"part {part.get('name')!r}: body {part['body']!r} is not an MJCF body")
+ if part["body"] not in moving: # on a fixed body (the base): drawn with the base meshes below
+ fixed_parts.append(part)
+ continue
+ mesh = self._part_mesh(part, real)
+ groups[part.get("group", "board")].append(len(bodies))
+ bodies.append(mesh)
+ mesh_body.append(self.kin.bodies.index(part["body"]))
+ self._init_look(real, bodies, mesh_body, groups, moving)
+ self.mesh_body = torch.tensor(mesh_body, device=self.device)
+ self.cube_half = 0.5 * float(cfg["cube"]["size_m"])
+ v, f = box_mesh([self.cube_half] * 3)
+ groups["cube"].append(len(bodies))
+ bodies.append(MeshBody("cube", vertices=v, faces=f,
+ color=tuple(cube_colors) if cube_colors is not None else real.color("cube")))
+ self.cube_meshes = 1
+ self.goal_style = None if goal is None else "block"
+ self.goal_meshes = 0 if goal is None else 1
+ if goal is not None:
+ pt = float(real.plate_thickness)
+ if plate_depth is not None: # thickness randomisation (v8): the mesh reaches this far below its top
+ self.plate_depth = max(pt, float(plate_depth))
+ if self.plate_depth is None or self.plate_depth <= pt:
+ v, f = box_mesh([BLOCK_HALF, BLOCK_HALF, pt / 2], (0.0, 0.0, pt / 2))
+ else: # top at pt as before
+ v, f = box_mesh([BLOCK_HALF, BLOCK_HALF, self.plate_depth / 2], (0.0, 0.0, pt - self.plate_depth / 2))
+ groups["plate"].append(len(bodies))
+ bodies.append(MeshBody("goal", vertices=v, faces=f, color=real.color("plate")))
+ # fixed bodies: the arm base meshes (at their welded pose), then the floor, the mat and the walls
+ zero = torch.zeros(1, 6, dtype=torch.float64, device=self.device)
+ bpos, bquat = self.kin(zero)
+ fixed = []
+ for body, mesh in assets.meshes:
+ if body not in moving and body not in hidden:
+ i = self.kin.bodies.index(body)
+ part = arm_part(mesh.color)
+ groups[part].append(len(bodies))
+ bodies.append(replace(mesh, color=real.color(part)))
+ fixed.append(torch.cat([bpos[0, i], xyzw(bquat[0, i])]))
+ for part in fixed_parts: # parts on fixed bodies (scene v4: the table clamp at the base)
+ i = self.kin.bodies.index(part["body"])
+ mesh = self._part_mesh(part, real)
+ groups[part.get("group", "board")].append(len(bodies))
+ bodies.append(mesh)
+ fixed.append(torch.cat([bpos[0, i], xyzw(bquat[0, i])]))
+ self.env_groups, self.env_names = [], []
+ for g, name, mesh, pose in real.env_meshes():
+ groups[g].append(len(bodies))
+ bodies.append(mesh)
+ fixed.append(torch.tensor(pose, dtype=torch.float64, device=self.device))
+ self.env_groups.append(g)
+ self.env_names.append(name)
+ self.fixed_pose = torch.stack(fixed) # [n_fixed, 7] x y z qx qy qz qw, float64
+ self.n_env = len(self.env_names)
+ self.groups = groups
+ self.scene = Scene.from_meshes(bodies)
+ # cameras: calibrated external (world-fixed) and wrist (on its calibrated body); top and front as the sim's
+ f64 = lambda v: torch.tensor([v], dtype=torch.float64) # noqa: E731
+ self.front = cams.look_at(f64(front_eye), f64(front_target))[0].to(self.device)
+ self.top = cams.look_at(f64(top_eye), f64(top_target), up=TOP_UP)[0].to(self.device)
+ self.fovy_deg = float(assets.wrist_cam["fovy_deg"])
+ calib = real.calib["cameras"]
+ cam = assets.wrist_cam
+ self.cam_body = self.kin.bodies.index(cam["body"])
+ self.cam_pos = torch.tensor(cam["pos"], dtype=torch.float64, device=self.device)
+ self.cam_quat = torch.tensor(cam["quat"], dtype=torch.float64, device=self.device)
+ if "wrist" in self.cameras:
+ c = calib["wrist"]
+ if c["parent"] not in self.kin.bodies:
+ raise ValueError(f"wrist camera parent {c['parent']!r} is not a body of the MJCF: {self.kin.bodies}")
+ local = cams.pose_from_opencv(c["T_parent_cam"]).to(self.device)
+ self.cam_body = self.kin.bodies.index(c["parent"])
+ self.cam_pos, self.cam_quat = local[:3], wxyz(local[3:])
+ if "external" in self.cameras:
+ c = calib["external"]
+ if c["parent"] != "world":
+ raise ValueError(f"external camera parent {c['parent']!r}: only 'world' is handled")
+ self.external = cams.pose_from_opencv(c["T_parent_cam"]).to(self.device)
+ self.camera_models = [real.camera_model(n) if n in REAL_CAMERAS else cams.PinholeCamera(self.fovy_deg)
+ for n in self.cameras]
+ # per camera tone map [C, 9] (camera_fx.TONE_KEYS), None: Newton's own 8-bit output
+ self.tone_params = None
+ if real.tone is not None:
+ from nedm.render.camera_fx import tone_vector
+ missing = [n for n in self.cameras if n not in real.tone]
+ if missing:
+ raise ValueError(f"tone map missing for cameras {missing}")
+ self.tone_params = torch.tensor([tone_vector(real.tone[n]) for n in self.cameras], dtype=torch.float32)
+ o, qp = real.plane_pose()
+ self.plane_o = torch.tensor(o, dtype=torch.float64, device=self.device)
+ self.plane_q = torch.tensor(qp, dtype=torch.float64, device=self.device) # w x y z
+
+ def _init_look(self, real, bodies, mesh_body, groups, moving) -> None:
+ """The gripper-look parts (``real.look_slots``, v12; off: ``look_names`` empty, ``look_index`` None and
+ every transform as before): the slot parts after the parts on moving bodies (group ``look``), then
+ ``look_names`` = the movable scene parts + the slots, ``look_index`` [K] their body (= moving mesh) indices,
+ ``look_pose0`` [K, 7] their nominal local poses (movable: identity; slots: hidden)."""
+ look = real.look_slots or {}
+ self.look_names, self.look_index, self.look_pose0 = [], None, None
+ if not look.get("movable") and not look.get("slots"):
+ return
+ for part in look.get("slots", ()):
+ if part["body"] not in moving:
+ raise ValueError(f"look slot {part.get('name')!r}: body {part['body']!r} is not a moving MJCF body")
+ if part.get("group") != "look":
+ raise ValueError(f"look slot {part.get('name')!r}: group must be 'look'")
+ groups["look"].append(len(bodies))
+ bodies.append(self._part_mesh(part, real))
+ mesh_body.append(self.kin.bodies.index(part["body"]))
+ names = [b.name for b in bodies]
+ idx = []
+ for nm in list(look.get("movable", ())) + [p["name"] for p in look.get("slots", ())]:
+ k = [i for i, b in enumerate(names) if b == nm]
+ if len(k) != 1:
+ raise ValueError(f"look part {nm!r}: found {len(k)} times among the moving meshes and parts")
+ idx.append(k[0])
+ self.look_names = [names[i] for i in idx]
+ self.look_index = torch.tensor(idx, dtype=torch.long, device=self.device)
+ pose0 = torch.zeros(len(idx), 7, dtype=torch.float64, device=self.device)
+ pose0[:, 6] = 1.0
+ pose0[len(look.get("movable", ())):, 2] = HIDDEN_Z
+ self.look_pose0 = pose0
+
+ def _look_apply(self, mp, mq, part_pose):
+ """Moving mesh poses (positions [n, M, 3], quaternions [n, M, 4] w x y z) with the look parts' local poses
+ (``part_pose`` [n, K, 7] x y z qx qy qz qw in the body frame, None: ``look_pose0``; z < HIDDEN_Z / 2: the
+ part is hidden far below the scene) applied."""
+ n, K = mp.shape[0], len(self.look_names)
+ lp = self.look_pose0 if part_pose is None else torch.as_tensor(part_pose).to(device=mp.device,
+ dtype=torch.float64)
+ lp = lp.reshape(-1, K, 7).expand(n, K, 7)
+ k = self.look_index.to(mp.device)
+ bp, bq = mp[:, k], mq[:, k]
+ lq = wxyz(lp[..., 3:])
+ lq = lq / lq.norm(dim=-1, keepdim=True)
+ wp, wq = bp + qrot(bq, lp[..., :3]), qmul(bq, lq)
+ hid = (lp[..., 2] < HIDDEN_Z / 2)[..., None]
+ wp = torch.where(hid, torch.tensor([0.0, 0.0, HIDDEN_Z], dtype=wp.dtype, device=wp.device), wp)
+ wq = torch.where(hid, torch.tensor([1.0, 0.0, 0.0, 0.0], dtype=wq.dtype, device=wq.device), wq)
+ mp, mq = mp.clone(), mq.clone()
+ mp[:, k], mq[:, k] = wp, wq
+ return mp, mq
+
+ @staticmethod
+ def _part_mesh(part: dict, real: "RealScene") -> MeshBody:
+ """The prism of a ``RealScene.parts`` entry in its body frame, colour ``part["color"]`` or its group's."""
+ v, f = polygon_prism(part["polygon"], part["offset"])
+ group = part.get("group", "board")
+ if group not in REAL_GROUPS:
+ raise ValueError(f"part {part.get('name')!r}: group {group!r} is not one of {REAL_GROUPS}")
+ color = tuple(float(c) for c in part["color"]) if part.get("color") is not None else real.color(group)
+ return MeshBody(part.get("name", "part"), vertices=v, faces=f, color=color)
+
+ @property
+ def env_pose(self) -> torch.Tensor:
+ """Nominal poses [n_env, 7] (x y z qx qy qz qw, float64) of the floor, mat and walls (real scene)."""
+ return self.fixed_pose[len(self.fixed_pose) - self.n_env:]
+
+ def base_outline(self) -> tuple[np.ndarray, float]:
+ """The arm base's footprint (real scene): the convex hull (k, 2) (counter-clockwise, world xy) of the visible
+ MJCF base meshes at their welded pose (not the scene's extra parts), and the base's top z. For the base
+ add-on randomisation (:meth:`RealDR.draw`)."""
+ if getattr(self, "_base_outline", None) is None:
+ zero = torch.zeros(1, 6, dtype=torch.float64)
+ bpos, bquat = self.kin(zero)
+ moving, hidden = self._moving_bodies(), set(self.real.hide_bodies or ())
+ pts = []
+ for body, mesh in self.assets.meshes:
+ if body in moving or body in hidden:
+ continue
+ i = self.kin.bodies.index(body)
+ v = torch.as_tensor(mesh.vertices, dtype=torch.float64)
+ pts.append((bpos[0, i].cpu() + qrot(bquat[0, i].cpu().expand(len(v), 4), v)).numpy())
+ if not pts:
+ raise ValueError("base_outline: the scene has no fixed base meshes")
+ p = np.concatenate(pts)
+ self._base_outline = (convex_hull_2d(p[:, :2]), float(p[:, 2].max()))
+ return self._base_outline
+
+ def _plate_shift(self, g, cube_pos, cq, plate_dz):
+ """Plate thickness randomisation (v8; table frame of the flat model): the plate rows ``g`` [n, 7]
+ (x y z qx qy qz qw, before the table-plane map) raised by ``plate_dz`` [n] (m: the plate top above the nominal
+ one; hidden plates stay), and the cube's visual lift [n] (m, along the table normal): a cube over the plate
+ sinks into the drawn plate no deeper than into the nominal plate (lift = plate_dz - its lowest corner's height
+ above the table clipped at 0, if positive: a cube resting on the table sits plate_thickness deep in the plate,
+ as in the nominal scene; full lift with the cube centre over the plate, none once its footprint is off the
+ plate, linear between), so a thicker plate does not swallow a resting or placed cube; the cube's physics
+ state is unchanged. -> (g, lift)."""
+ f64 = dict(device=self.device, dtype=torch.float64)
+ n = g.shape[0]
+ shown = g[:, 2] > HIDDEN_Z / 2
+ dz = torch.where(shown, torch.as_tensor(plate_dz).to(**f64).reshape(n), 0.0)
+ g = g.clone()
+ g[:, 2] = g[:, 2] + dz
+ qi = (self.plane_q * torch.tensor([1.0, -1.0, -1.0, -1.0], **f64)).expand(n, 4)
+ c = qrot(qi, cube_pos - self.plane_o) # cube centre, table frame
+ w_, x_, y_, z_ = qmul(qi, cq).unbind(-1) # cube rotation, table frame
+ rz = torch.stack((2 * (x_ * z_ - w_ * y_), 2 * (y_ * z_ + w_ * x_), 1 - 2 * (x_ * x_ + y_ * y_)), -1)
+ bottom = c[:, 2] - self.cube_half * rz.abs().sum(-1) # lowest corner above the table
+ yaw = 2 * torch.atan2(g[:, 5], g[:, 6]) # the plate's yaw (z turn, xyzw)
+ d = c[:, :2] - g[:, :2]
+ lx = torch.cos(yaw) * d[:, 0] + torch.sin(yaw) * d[:, 1]
+ ly = -torch.sin(yaw) * d[:, 0] + torch.cos(yaw) * d[:, 1]
+ over = ((BLOCK_HALF + self.cube_half - torch.maximum(lx.abs(), ly.abs())) / self.cube_half).clamp(0.0, 1.0)
+ lift = over * (dz - bottom.clamp_min(0.0)).clamp_min(0.0)
+ return g, torch.where(shown & torch.isfinite(lift), lift, 0.0)
+
+ @staticmethod
+ def plane_frames(plane) -> tuple[torch.Tensor, torch.Tensor]:
+ """Per-world table planes [n, 3] (c0, c1, c2; z = c0 + c1 x + c2 y, float64) -> (origin [n, 3], quaternion
+ [n, 4] w x y z) of the table frame, as :meth:`RealScene.plane_pose` (a flat plane: exactly the identity
+ turn)."""
+ c = torch.as_tensor(plane, dtype=torch.float64)
+ nrm = torch.sqrt(1.0 + c[:, 1] ** 2 + c[:, 2] ** 2)
+ z = torch.zeros_like(nrm)
+ qv = torch.stack([1.0 + 1.0 / nrm, c[:, 2] / nrm, -c[:, 1] / nrm, z], -1) # z x n, n ~ (-c1, -c2, 1)
+ return torch.stack([z, z, c[:, 0]], -1), qv / qv.norm(dim=-1, keepdim=True)
+
+ def _real_transforms(self, q, cube_pos, cube_quat, goal_pose=None, env_pose=None, plate_dz=None,
+ world_plane=None, cube_held=None, part_pose=None):
+ f64 = dict(device=self.device, dtype=torch.float64)
+ q = torch.as_tensor(q).to(**f64)
+ n = q.shape[0]
+ pos, quat = self.kin(q)
+ if getattr(self, "look_index", None) is None:
+ if part_pose is not None:
+ raise ValueError("part_pose: the scene has no gripper-look parts (RealScene.look_slots)")
+ parts = [torch.cat([pos[:, self.mesh_body], xyzw(quat[:, self.mesh_body])], -1)]
+ else: # v12 gripper look: the look parts at their per-world local poses
+ mp, mq = self._look_apply(pos[:, self.mesh_body], quat[:, self.mesh_body], part_pose)
+ parts = [torch.cat([mp, xyzw(mq)], -1)]
+ cq = torch.as_tensor(cube_quat).to(**f64)
+ cq = cq / cq.norm(dim=-1, keepdim=True)
+ cp = torch.as_tensor(cube_pos).to(**f64)
+ g = None
+ if plate_dz is not None:
+ if self.goal_style is None or self.plate_depth is None:
+ raise ValueError("plate_dz needs the goal plate and a renderer built with plate_depth")
+ g, lift = self._plate_shift(self.goal_transform(goal_pose, n), cp, cq, plate_dz)
+ if cube_held is not None: # a cube the jaws hold is drawn at its physics pose (no lift)
+ lift = torch.where(torch.as_tensor(cube_held, device=self.device).reshape(n).bool(), 0.0, lift)
+ cp = cp + lift[:, None] * qrot(self.plane_q.expand(n, 4), torch.tensor([0.0, 0.0, 1.0], **f64).expand(n, 3))
+ wp = None
+ if world_plane is not None: # per-world table plane (v8 table_render): the world drawn on it
+ if self.real.table_plane is not None:
+ raise ValueError("world_plane: the scene has its own table_plane (the physics poses are not flat)")
+ wp = torch.as_tensor(world_plane).to(**f64).reshape(n, 3)
+ wo, wq = self.plane_frames(wp)
+ wo, wq = wo.to(self.device), wq.to(self.device)
+ hz = wp[:, 0] + wp[:, 1] * cp[:, 0] + wp[:, 2] * cp[:, 1] # the cube: sheared (xy kept, as the
+ cp = cp + torch.stack([torch.zeros_like(hz), torch.zeros_like(hz), hz], -1) # joint map), tilted
+ cq = qmul(wq, cq)
+ cube = torch.cat([cp, xyzw(cq)], -1)
+ parts.append(cube[:, None])
+ if self.goal_style is not None:
+ g = self.goal_transform(goal_pose, n) if g is None else g
+ if self.real.table_plane is not None: # the plate lies on the measured table plane
+ qp = self.plane_q.expand(n, 4)
+ shown = g[:, 2:3] > HIDDEN_Z / 2
+ on = torch.cat([self.plane_o + qrot(qp, g[:, :3]), xyzw(qmul(qp, wxyz(g[:, 3:])))], -1)
+ g = torch.where(shown, on, g)
+ elif wp is not None: # ... on the world's plane (as RealScene.on_plane)
+ shown = g[:, 2:3] > HIDDEN_Z / 2
+ on = torch.cat([wo + qrot(wq, g[:, :3]), xyzw(qmul(wq, wxyz(g[:, 3:])))], -1)
+ g = torch.where(shown, on, g)
+ parts.append(g[:, None])
+ fixed = self.fixed_pose.expand(n, *self.fixed_pose.shape)
+ if env_pose is not None:
+ e = torch.as_tensor(env_pose).to(**f64).reshape(n, self.n_env, 7)
+ fixed = torch.cat([fixed[:, : len(self.fixed_pose) - self.n_env], e], 1)
+ if wp is not None: # floor, mat, walls, strip, ceiling on the world's plane (not the lab room)
+ k0, m = len(self.fixed_pose) - self.n_env, self.n_env
+ e = fixed[:, k0:]
+ wqe = wq[:, None].expand(n, m, 4)
+ on = torch.cat([wo[:, None] + qrot(wqe, e[..., :3]), xyzw(qmul(wqe, wxyz(e[..., 3:])))], -1)
+ mv = torch.tensor([gr not in ("room", "room_floor") for gr in self.env_groups], device=self.device)
+ fixed = torch.cat([fixed[:, :k0], torch.where(mv[None, :, None], on, e)], 1)
+ parts.append(fixed)
+ body_q = torch.cat(parts, 1)
+ views = []
+ for name in self.cameras:
+ if name == "wrist":
+ bp, bq = pos[:, self.cam_body], quat[:, self.cam_body]
+ views.append(torch.cat([bp + qrot(bq, self.cam_pos.expand(n, 3)),
+ xyzw(qmul(bq, self.cam_quat.expand(n, 4)))], -1))
+ else:
+ views.append(getattr(self, name).to(torch.float64).expand(n, 7))
+ return body_q.float(), torch.stack(views, 1).float()
+
+ def _moving_bodies(self) -> set[str]:
+ """Bodies with a hinge on the path to the world."""
+ moving: set[str] = set()
+ for link in self.assets.links: # parents first
+ if link.qadr is not None or link.parent in moving:
+ moving.add(link.name)
+ return moving
+
+ @property
+ def body_names(self) -> list[str]:
+ return self.scene.body_names
+
+ def transforms(self, q, cube_pos, cube_quat, goal_pose=None, env_pose=None, plate_dz=None, world_plane=None,
+ cube_held=None, part_pose=None) -> tuple[torch.Tensor, torch.Tensor]:
+ """Body transforms [B, bodies, 7] and camera transforms [B, cameras, 7] (x y z, qx qy qz qw; float32).
+
+ q [B, 6] rad; cube_pos [B, 3] m; cube_quat [B, 4] w x y z (normalised here); goal_pose None (hidden),
+ [B, 3] = goal cube centre x, y (m) and yaw (rad), or [B, 7] = goal cube pose (position, quaternion w x y z),
+ of which x, y and the yaw of the face closest to the table (:func:`flat_yaw`) are used. The marker lies on the
+ table top under that point. Rows with a non-finite goal are hidden. ``env_pose`` (real scene only)
+ [B, n_env, 7] x y z qx qy qz qw replaces the floor, mat and wall poses (:attr:`env_pose`). ``plate_dz`` (real
+ scene built with ``plate_depth`` only) [B]: per-world plate thickness (:meth:`_plate_shift`); ``cube_held`` [B]
+ bool: cubes the jaws hold (not lifted by the plate). ``world_plane`` (real scene without its own
+ ``table_plane``) [B, 3]: per-world table plane z = c0 + c1 x + c2 y (v8 consistent table images): the cube
+ (given in the flat model) is sheared by the plane height under it (xy kept) and tilted with the plane; the
+ goal plate, floor, mat, walls, strip and ceiling are put on the plane as :meth:`RealScene.on_plane` does; the
+ arm, its base, the lab room and the cameras stay (the arm frame); the caller draws the arm at the joints it
+ wants (the student's reading). ``part_pose`` (real scene with gripper-look parts, v12) [B, K, 7]: the local
+ poses of :attr:`look_names` in their bodies' frames (``_look_apply``; None: ``look_pose0``)."""
+ if self.real is not None:
+ if plate_dz is None and world_plane is None and cube_held is None and part_pose is None:
+ return self._real_transforms(q, cube_pos, cube_quat, goal_pose, env_pose)
+ return self._real_transforms(q, cube_pos, cube_quat, goal_pose, env_pose, plate_dz, world_plane,
+ cube_held, part_pose)
+ if env_pose is not None or plate_dz is not None or world_plane is not None or cube_held is not None or \
+ part_pose is not None:
+ raise ValueError("env_pose / plate_dz / world_plane / cube_held / part_pose need the real scene")
+ f64 = dict(device=self.device, dtype=torch.float64)
+ q = torch.as_tensor(q).to(**f64)
+ n = q.shape[0]
+ pos, quat = self.kin(q)
+ parts = [torch.cat([pos[:, self.mesh_body], xyzw(quat[:, self.mesh_body])], -1)]
+ cq = torch.as_tensor(cube_quat).to(**f64)
+ cube = torch.cat([torch.as_tensor(cube_pos).to(**f64), xyzw(cq / cq.norm(dim=-1, keepdim=True))], -1)
+ parts.append(cube[:, None].expand(n, self.cube_meshes, 7))
+ if self.goal_style is not None:
+ parts.append(self.goal_transform(goal_pose, n)[:, None].expand(n, self.goal_meshes, 7))
+ if self.table_body:
+ parts.append(self.table_pose.expand(n, 1, 7))
+ body_q = torch.cat(parts, 1)
+ views = []
+ for name in self.cameras:
+ if name == "wrist": # body pose composed with the MJCF camera pose
+ bp, bq = pos[:, self.cam_body], quat[:, self.cam_body]
+ views.append(torch.cat([bp + qrot(bq, self.cam_pos.expand(n, 3)),
+ xyzw(qmul(bq, self.cam_quat.expand(n, 4)))], -1))
+ else:
+ views.append(getattr(self, name).to(torch.float64).expand(n, 7))
+ return body_q.float(), torch.stack(views, 1).float()
+
+ def goal_transform(self, goal_pose, n: int) -> torch.Tensor:
+ """Goal marker transform [n, 7] (float64, x y z w) on the table top; see :meth:`transforms`."""
+ hidden = torch.zeros(n, 7, dtype=torch.float64, device=self.device)
+ hidden[:, 2], hidden[:, 6] = HIDDEN_Z, 1.0
+ if goal_pose is None:
+ return hidden
+ g = torch.as_tensor(goal_pose).to(device=self.device, dtype=torch.float64)
+ if g.shape[-1] not in (3, 7):
+ raise ValueError(f"goal_pose must be [B, 3] (x, y, yaw) or [B, 7] (pos, quat wxyz), got {tuple(g.shape)}")
+ ok = torch.isfinite(g).all(-1, keepdim=True)
+ g = torch.where(ok, g, 1.0) # no host sync (mask indexing would cost one per call)
+ yaw = g[:, 2] if g.shape[-1] == 3 else flat_yaw(g[:, 3:7] / g[:, 3:7].norm(dim=-1, keepdim=True))
+ shown = torch.cat([g[:, :2], torch.zeros_like(g[:, :1]), xyzw(yaw_quat(yaw))], -1)
+ return torch.where(ok, shown, hidden)
+
+
+# ---- the real setup (real2sim) ------------------------------------------------------------------------------------
+# Off by default: ``SO101Scene(real=RealScene(...))`` / ``SO101Renderer(real=...)``. The calibration contract
+# (``~/so101_r2s_claude/calib/calib_v1.json``): cameras with K, D, image size, parent and T_parent_cam in the OpenCV
+# convention; scene.mat.corners_xy; colours measured from real frames. The scene file (``real_scene_v1.json``,
+# :meth:`RealScene.from_path`) holds what was fitted to the real frames: the student crops, the light-box geometry,
+# albedos, lights, the per-camera tone maps and the randomisation ranges. The class defaults are PLACEHOLDERS (a
+# white light box with a black cloth mat, a white printed arm with black servos, a green 30 mm cube, a red 50 mm
+# square plate, an LED strip light on the right).
+REAL_VIEWS = ("external", "wrist", "top", "front") # external, wrist: calibrated; top, front: the 61 deg pinholes
+REAL_CAMERAS = ("external", "wrist")
+REAL_GROUPS = ("printed", "servo", "cube", "plate", "floor", "mat", "walls", "board", "room", "room_floor", "strip",
+ "addon", "look")
+# "addon": the slots of the base add-on randomisation (RealDR.base_addon, RealScene.addon_slots); empty when it is off,
+# so the group codes of the other groups (bg_dr) and every draw stay as before
+# "look": the mark / edge slots of the gripper-look randomisation (RealDR.gripper_look, RealScene.look_slots; v12);
+# empty when it is off
+SERVO_MAX_MJCF = 0.3 # so101.xml: the sts3215 servo materials (and the wrist camera board) are rgba 0.1 0.1 0.1
+# The real wrist camera's board (black PCB on a black bracket), drawn behind the calibrated wrist camera in its OpenCV
+# frame (x right, y down = towards the jaws, z forward): a w x h x t board whose front face is ``behind`` m behind the
+# camera centre, and a bracket block below and behind it. Everything has camera z < 0, so the wrist camera never sees
+# it; the external camera does (calib REVIEW.md issue 2). Sizes estimated from the external frames, not measured.
+DEFAULT_BOARD = {"size": (0.032, 0.032, 0.002), "behind": 0.004, "bracket": (0.014, 0.022, 0.018)}
+
+
+def arm_part(color) -> str:
+ """``"servo"`` for the MJCF's black servo material (rgb 0.1), else ``"printed"`` (the yellow printed parts)."""
+ return "servo" if max(color) < SERVO_MAX_MJCF else "printed"
+
+
+def load_calibration(path: str | Path) -> dict:
+ """The calibration contract (JSON) at ``path``."""
+ return json.loads(Path(path).expanduser().read_text())
+
+
+def placeholder_calibration() -> dict:
+ """A TEMPORARY calibration in the contract's layout for tests (not measured): both cameras fisheye fx = fy = 300,
+ cx = 320, cy = 240, D = (0.05, 0, 0, 0), 640 x 480; external at (0.35, -0.35, 0.45) looking at (0.2, 0, 0); wrist =
+ the MJCF ``wrist_cam`` pose on ``camera_mount`` (turned to the OpenCV convention)."""
+ from nedm.render import cameras as cams
+ ext = cams.opencv_look_at([0.35, -0.35, 0.45], [0.2, 0.0, 0.0])[0].tolist()
+ q = (0.958280, -0.285792, -0.001556, 0.004547) # so101.xml wrist_cam, w x y z
+ gl = torch.tensor([-0.00296, 0.05436, -0.05310, q[1], q[2], q[3], q[0]], dtype=torch.float64)
+ wrist = cams.pose_to_opencv(gl).tolist()
+ lens = dict(model="opencv_fisheye", width=640, height=480, K=[300.0, 300.0, 320.0, 240.0], D=[0.05, 0.0, 0.0, 0.0],
+ rms_px=float("nan"), n_points=0, holdout_rms_px=float("nan"))
+ return {"placeholder": True,
+ "cameras": {"external": dict(lens, parent="world", T_parent_cam=ext),
+ "wrist": dict(lens, parent="camera_mount", T_parent_cam=wrist)},
+ "scene": {"mat": {"corners_xy": None}, "notes": "placeholder, not measured"}}
+
+
+def _quat_from_two(a, b) -> np.ndarray:
+ """Unit quaternion w x y z of the shortest turn that maps unit vector a to unit vector b."""
+ a, b = np.asarray(a, np.float64), np.asarray(b, np.float64)
+ a, b = a / np.linalg.norm(a), b / np.linalg.norm(b)
+ if 1.0 + a @ b < 1e-12: # opposite: half turn about any axis normal to a
+ axis = np.cross(a, (1.0, 0.0, 0.0) if abs(a[0]) < 0.9 else (0.0, 1.0, 0.0))
+ return np.r_[0.0, axis / np.linalg.norm(axis)]
+ q = np.r_[1.0 + a @ b, np.cross(a, b)]
+ return q / np.linalg.norm(q)
+
+
+def _flip(faces: np.ndarray) -> np.ndarray:
+ """Reverse the winding (outward -> inward-facing triangles: Newton culls back faces)."""
+ return faces[:, ::-1].copy()
+
+
+def convex_hull_2d(points) -> np.ndarray:
+ """Convex hull (k, 2) of points (n, 2), counter-clockwise, no repeated end point (Andrew's monotone chain)."""
+ p = np.unique(np.asarray(points, np.float64).reshape(-1, 2), axis=0)
+ if len(p) < 3:
+ return p
+
+ def half(pts):
+ h = []
+ for q in pts:
+ while len(h) >= 2 and ((h[-1][0] - h[-2][0]) * (q[1] - h[-2][1])
+ - (h[-1][1] - h[-2][1]) * (q[0] - h[-2][0])) <= 0:
+ h.pop()
+ h.append(q)
+ return h
+ lower, upper = half(p), half(p[::-1])
+ return np.array(lower[:-1] + upper[:-1])
+
+
+def polygon_prism(polygon, offset) -> tuple[np.ndarray, np.ndarray]:
+ """Closed prism over a planar convex polygon (k, 3) (ordered) swept by ``offset`` (3,): vertices (2k, 3) float32,
+ faces (4k - 4, 3) int32, every face turned outward (away from the centroid)."""
+ p = np.asarray(polygon, np.float64)
+ k = len(p)
+ v = np.concatenate([p, p + np.asarray(offset, np.float64)])
+ faces = [[0, i, i + 1] for i in range(1, k - 1)] + [[k, k + i, k + i + 1] for i in range(1, k - 1)]
+ for i in range(k):
+ j = (i + 1) % k
+ faces += [[i, j, k + j], [i, k + j, k + i]]
+ f = np.array(faces, np.int64)
+ mid = v.mean(0)
+ nrm = np.cross(v[f[:, 1]] - v[f[:, 0]], v[f[:, 2]] - v[f[:, 0]])
+ out = ((v[f].mean(1) - mid) * nrm).sum(-1) < 0
+ f[out] = f[out][:, ::-1]
+ return v.astype(np.float32), f.astype(np.int32)
+
+
+@dataclass
+class RealScene:
+ """The real-setup scene configuration (geometry in the world = arm base frame, m).
+
+ ``calib``: the contract dict (or :meth:`from_path`). Camera crop: ``crop`` None (default) = the student view of
+ :mod:`nedm.render.student_view` (``student_view`` here, else ``calib["student_view"]``, else a centred square; the
+ SAME rules as the real-robot code ``hw_lib``), whose output size must equal the renderer's size; ``crop`` a dict =
+ per camera the real-pixel box [x0, y0, w, h] (None: the whole 640 x 480 image), the old explicit form.
+ Geometry: the black mat = a prism over ``mat_corners_xy`` (None: the calibration's ``scene.mat.corners_xy``, else
+ ``DEFAULT_MAT``) from z = -``mat_thickness`` to 0; the white floor = a box over ``floor_xy`` (x0, x1, y0, y1) with
+ its top at z = -``mat_thickness``; ``walls``: vertical white panels, each a floor segment ((x0, y0), (x1, y1)) of
+ the panel's inner face, ``wall_height`` tall (or its own height as a third element) and ``wall_thickness`` thick
+ away from the mat (empty: none);
+ ``ceiling``: z of a white panel over the floor (None: none); ``strip``: the LED strip, a box from ``"from"`` to
+ ``"to"`` (m) with cross-section ``"size"`` (w, t) (group ``strip``; None: none); ``room``: the dark room outside
+ the light box, an inward-facing box ``{"center": (3,), "half": (3,)}`` (group ``room``; None: rays that leave the
+ box get ``sky``; ``"floor_z"``: also a lab floor at that height, group ``room_floor``). ``table_plane``
+ (c0, c1, c2): put the floor, mat, walls, ceiling, strip and the goal plate on the
+ plane z = c0 + c1 x + c2 y (the measured real table, calib ``scene.table_plane``); None: z = 0 (the sim physics).
+ ``hide_bodies``: MJCF bodies whose meshes are left out (default the MJCF wrist camera mount and board, which sit
+ in front of the calibrated wrist camera); ``board``: the real camera board drawn behind the calibrated wrist camera
+ (:data:`DEFAULT_BOARD`; None: none). ``plate_thickness``: the goal plate (50 mm square) thickness. ``parts``:
+ extra rigid parts on arm bodies, each ``{"name", "body", "group", "polygon": (k, 3) in the body frame, "offset":
+ (3,)}`` (a prism, :func:`polygon_prism`), e.g. the real camera bracket's plate under the wrist camera; optional
+ ``"color"`` (linear albedo, default the group's colour; the group's randomisation scales it). A part on a FIXED
+ MJCF body (``"body": "base"``; scene v4: the real table clamp at the base) is drawn at that body's welded pose,
+ after the arm base meshes and before the floor (scenes without such parts keep their body order).
+ ``floor_turn`` (None: none): ``{"deg": a, "pivot": (x, y)}``, the floor box turned by a about the table normal
+ through the pivot (flat-model frame; default pivot: the middle of the floor's -x edge), the measured turn of the
+ real table edge (scene v3); it is also the pivot of ``RealDR.floor_turn_deg``. ``wall_end`` (None: none):
+ ``{"wall": k, "slide": s}``: wall k's FIRST end becomes a separate piece (``wall{k}_end``, group walls) that
+ ``RealDR.wall_end`` slides along the wall by up to +-s; the main wall then starts s later, the piece is 2 s + 10 mm
+ long, 0.5 mm behind the main wall's inner face and 0.5 mm lower (no coincident faces); nominal picture = the wall
+ ending at its listed first point.
+ ``addon_slots`` (None: none; not read from the scene file): the hidden bodies that the base add-on randomisation
+ (:attr:`RealDR.base_addon`) places per world, ``{"blocks": [(lx, ly, lz), ...], "cables": [(length, width),
+ ...]}`` and optionally ``"flats"`` / ``"drops"`` (flat cables and their sloped segments, (length, width))
+ (:meth:`RealDR.addon_slots`; ``viral.load_real_setup`` sets it from the merged ``dr``). They are the last env bodies
+ (group ``addon``, names ``addon_block{k}``, ``addon_cable{k}``, ``addon_flat{k}``, ``addon_drop{k}`` in this
+ order), nominally far below the scene.
+ ``look_slots`` (None: none; not read from the scene file; v12 gripper look): ``{"movable": [names of scene parts on
+ moving bodies that get per-world local poses (the fitted screws)], "slots": [part dicts (``parts`` layout, group
+ ``look``, on moving bodies): the mark and edge-strip slots, hidden until drawn]}``
+ (:meth:`nedm.render.gripper_look.GripperLookDR.slots`; ``viral.load_real_setup`` sets it from the merged ``dr``);
+ the slot parts follow the scene's parts on moving bodies (before the cube); :class:`SO101Scene` ``look_names``.
+ Colours (linear albedo, Newton multiplies by the light): ``colors[group]`` for REAL_GROUPS. ``lights``: Newton
+ lights (``NewtonBackend.set_lights``), shared by all worlds; ``ambient``: Newton's fixed ambient term; ``sky``:
+ 8-bit colour of rays that hit nothing. ``tone``: per camera a tone map (``camera_fx``: exposure, wb, black, gamma,
+ vignette) applied to Newton's linear output (None: Newton's own clamped 8-bit colour). ``supersample``: s x s rays
+ per output pixel, averaged after the tone map (as the real frame is area-averaged to the student size).
+ ``dr`` / ``image_fx``: the randomisation ranges (:meth:`RealDR.from_dict`, ``camera_fx.ImageFX.from_dict``)."""
+
+ DEFAULT_MAT = ((0.08, -0.22), (0.42, -0.22), (0.42, 0.22), (0.08, 0.22))
+ DEFAULT_COLORS = {"printed": (0.92, 0.92, 0.90), "servo": (0.05, 0.05, 0.05), "cube": (0.05, 0.62, 0.22),
+ "plate": (0.85, 0.08, 0.08), "floor": (0.93, 0.93, 0.93), "mat": (0.03, 0.03, 0.03),
+ "walls": (0.93, 0.93, 0.93), "board": (0.03, 0.03, 0.03), "room": (0.04, 0.035, 0.025),
+ "room_floor": (0.2, 0.18, 0.15), "strip": (1.0, 1.0, 1.0), "addon": (0.5, 0.5, 0.5),
+ "look": (0.5, 0.5, 0.5)}
+ # A key light from above (shadows) and dimmed shadowless fills from the sides and from below (the light box's
+ # diffuse glow and the floor's bounce: Newton has no inter-reflection and a fixed weak ambient, so without them
+ # the white walls come out grey and every face turned from the key light near black). Placeholders, not measured.
+ DEFAULT_LIGHTS = ({"type": "directional", "direction": (-0.25, 0.35, -1.0), "shadow": True},
+ {"type": "directional", "direction": (0.1, 1.0, -0.35), "shadow": False, "intensity": 0.6,
+ "center": (0.25, 0.0, 0.0)},
+ {"type": "directional", "direction": (1.0, -0.1, -0.35), "shadow": False, "intensity": 0.6,
+ "center": (0.25, 0.0, 0.0)},
+ {"type": "directional", "direction": (0.0, -1.0, -0.3), "shadow": False, "intensity": 0.4,
+ "center": (0.25, 0.0, 0.0)},
+ {"type": "directional", "direction": (-1.0, 0.0, -0.3), "shadow": False, "intensity": 0.4,
+ "center": (0.25, 0.0, 0.0)},
+ {"type": "directional", "direction": (0.0, 0.0, 1.0), "shadow": False, "intensity": 0.35,
+ "center": (0.25, 0.0, 0.0)})
+
+ calib: dict = field(default_factory=placeholder_calibration)
+ crop: dict | None = None
+ mat_corners_xy: Sequence | None = None
+ mat_thickness: float = 0.001
+ floor_xy: tuple = (-0.25, 0.60, -0.45, 0.45)
+ floor_thickness: float = 0.01
+ walls: Sequence = (((-0.25, 0.45), (0.60, 0.45)), ((0.60, 0.45), (0.60, -0.45)))
+ wall_height: float = 0.60
+ wall_thickness: float = 0.005
+ colors: dict = field(default_factory=dict)
+ lights: Sequence = DEFAULT_LIGHTS
+ shadows: bool = True
+ ambient: bool = True
+ sky: tuple = (25, 25, 25)
+ student_view: dict | None = None
+ tone: dict | None = None
+ supersample: int = 1
+ hide_bodies: tuple = ("camera_mount",)
+ board: dict | None = field(default_factory=lambda: dict(DEFAULT_BOARD))
+ room: dict | None = None
+ ceiling: float | None = None
+ strip: dict | None = None
+ table_plane: Sequence | None = None
+ plate_thickness: float = BLOCK_THICKNESS
+ parts: Sequence = ()
+ floor_turn: dict | None = None
+ wall_end: dict | None = None
+ dr: dict = field(default_factory=dict)
+ image_fx: dict = field(default_factory=dict)
+ source: str = ""
+ addon_slots: dict | None = None
+ look_slots: dict | None = None
+
+ # keys of the scene file's "geometry" section that map to fields
+ GEOMETRY_KEYS = ("mat_corners_xy", "mat_thickness", "floor_xy", "floor_thickness", "walls", "wall_height",
+ "wall_thickness", "room", "ceiling", "strip", "table_plane", "plate_thickness", "hide_bodies",
+ "board", "parts", "floor_turn", "wall_end")
+ WALL_END_OVERLAP = 0.01 # m: the end piece reaches this far past the main wall's start at its shortest
+ WALL_END_INSET = 0.0005 # m: the end piece lies this far behind the main wall's inner face and below its top
+
+ @classmethod
+ def from_path(cls, path: str | Path, **kw) -> "RealScene":
+ """From a calibration contract (``calib_v1.json``) or from a scene file (``real_scene_v1.json``: its
+ ``"calib"`` key names the contract; its sections set the fields). ``kw`` overrides any field."""
+ d = load_calibration(path)
+ if not str(d.get("version", "")).startswith("real_scene"):
+ return cls(calib=d, **kw)
+ return cls.from_scene_dict(d, source=str(Path(path).expanduser()), **kw)
+
+ @classmethod
+ def from_scene_dict(cls, d: dict, calib: dict | None = None, source: str = "", **kw) -> "RealScene":
+ """From a parsed scene file (see :meth:`from_path`); ``calib`` overrides the file's ``"calib"`` path."""
+ if calib is None:
+ calib = load_calibration(d["calib"])
+ f: dict = {}
+ geo = d.get("geometry") or {}
+ for k in cls.GEOMETRY_KEYS:
+ if k in geo:
+ f[k] = geo[k]
+ if f.get("table_plane") == "calib":
+ f["table_plane"] = tuple(calib["scene"]["table_plane"]["coef"])
+ if f.get("walls") is not None:
+ f["walls"] = tuple(tuple(tuple(p) if isinstance(p, (list, tuple)) else float(p) for p in w)
+ for w in f["walls"])
+ for k in ("floor_xy", "hide_bodies"):
+ if f.get(k) is not None:
+ f[k] = tuple(f[k])
+ if "colors" in d:
+ f["colors"] = {g: tuple(c) for g, c in d["colors"].items()}
+ light = d.get("light") or {}
+ if "lights" in light:
+ f["lights"] = tuple(light["lights"])
+ for k in ("shadows", "ambient"):
+ if k in light:
+ f[k] = bool(light[k])
+ if "sky" in light:
+ f["sky"] = tuple(int(c) for c in light["sky"])
+ if "student_view" in d:
+ f["student_view"] = d["student_view"]
+ if "tone" in d:
+ f["tone"] = d["tone"]
+ if "supersample" in (d.get("render") or {}):
+ f["supersample"] = int(d["render"]["supersample"])
+ f["dr"] = d.get("dr") or {}
+ f["image_fx"] = d.get("image_fx") or {}
+ f.update(kw)
+ return cls(calib=calib, source=source, **f)
+
+ def color(self, group: str) -> tuple:
+ return tuple(float(c) for c in self.colors.get(group, self.DEFAULT_COLORS[group]))
+
+ def mat_corners(self) -> np.ndarray:
+ if self.mat_corners_xy is not None:
+ return np.asarray(self.mat_corners_xy, np.float64)
+ mat = (self.calib.get("scene") or {}).get("mat") or {}
+ corners = mat.get("corners_xy")
+ return np.asarray(corners if corners is not None else self.DEFAULT_MAT, np.float64)
+
+ # -- cameras --
+ def view(self, name: str, out_res: int | None = None):
+ """The camera's :class:`~nedm.render.student_view.ViewSpec` (crop box + output size) when ``crop`` is None
+ (student-view rules), else None (explicit ``crop`` dict: box only, any output size)."""
+ from nedm.render import student_view as sv
+ if self.crop is not None:
+ return None
+ src = {"student_view": self.student_view} if self.student_view is not None else self.calib
+ cam = self.calib["cameras"][name]
+ return sv.view_specs(src, (name,), out_res, cam["width"], cam["height"])[name]
+
+ def crop_box(self, name: str, out_res: int | None = None):
+ """The real-pixel crop box [x0, y0, w, h] of a calibrated camera (None: the whole image)."""
+ if self.crop is not None:
+ return self.crop.get(name)
+ return self.view(name, out_res).crop_xywh
+
+ def camera_model(self, name: str, k_scale: float = 1.0, pp_shift=(0.0, 0.0), out_res: int | None = 224):
+ """The calibrated camera with its crop; ``k_scale`` scales fx, fy and ``pp_shift`` (px) moves cx, cy (the
+ intrinsics randomisation; the crop box stays fixed in the real image)."""
+ from nedm.render.cameras import CalibratedCamera
+ cam = dict(self.calib["cameras"][name])
+ if k_scale != 1.0 or tuple(pp_shift) != (0.0, 0.0):
+ fx, fy, cx, cy = cam["K"]
+ cam["K"] = [fx * k_scale, fy * k_scale, cx + pp_shift[0], cy + pp_shift[1]]
+ return CalibratedCamera.from_contract(cam, self.crop_box(name, out_res))
+
+ # -- geometry --
+ def plane_pose(self) -> tuple[np.ndarray, np.ndarray]:
+ """(origin (3,), quaternion w x y z) of the table frame: z = 0 of the flat model -> the measured plane."""
+ if self.table_plane is None:
+ return np.zeros(3), np.array([1.0, 0.0, 0.0, 0.0])
+ c0, c1, c2 = (float(c) for c in self.table_plane)
+ return np.array([0.0, 0.0, c0]), _quat_from_two((0.0, 0.0, 1.0), (-c1, -c2, 1.0))
+
+ def on_plane(self, pose) -> np.ndarray:
+ """A flat-model pose (7,) x y z qx qy qz qw -> the same pose on the table plane (identity without one)."""
+ pose = np.asarray(pose, np.float64)
+ if self.table_plane is None:
+ return pose
+ o, q = self.plane_pose()
+ qt = torch.tensor(q)
+ p = o + qrot(qt, torch.tensor(pose[:3])).numpy()
+ r = qmul(qt, wxyz(torch.tensor(pose[3:7]))).numpy()
+ return np.r_[p, r[1:], r[0]]
+
+ def env_meshes(self) -> list[tuple[str, str, MeshBody, np.ndarray]]:
+ """(group, name, mesh in its own frame, pose (7,) x y z qx qy qz qw) of the floor, mat, walls, then the
+ ceiling, LED strip and room when set."""
+ out = []
+ x0, x1, y0, y1 = self.floor_xy
+ top = -self.mat_thickness
+ v, f = box_mesh([(x1 - x0) / 2, (y1 - y0) / 2, self.floor_thickness / 2])
+ pose = [(x0 + x1) / 2, (y0 + y1) / 2, top - self.floor_thickness / 2, 0, 0, 0, 1.0]
+ if self.floor_turn: # turned about the table normal through the pivot
+ th = math.radians(float(self.floor_turn["deg"]))
+ piv = self.floor_pivot()
+ d = np.asarray(pose[:2]) - piv
+ pose[:2] = (piv + [math.cos(th) * d[0] - math.sin(th) * d[1],
+ math.sin(th) * d[0] + math.cos(th) * d[1]]).tolist()
+ pose[3:] = [0.0, 0.0, math.sin(th / 2), math.cos(th / 2)]
+ out.append(("floor", "floor", MeshBody("floor", vertices=v, faces=f, color=self.color("floor")),
+ self.on_plane(pose)))
+ if self.wall_end and not 0 <= int(self.wall_end["wall"]) < len(self.walls):
+ raise ValueError(f"wall_end wall {self.wall_end['wall']}: no such wall ({len(self.walls)} walls)")
+ corners = self.mat_corners()
+ v, f = prism_mesh(corners, -self.mat_thickness, 0.0)
+ out.append(("mat", "mat", MeshBody("mat", vertices=v, faces=f, color=self.color("mat")),
+ self.on_plane(np.r_[corners.mean(0), 0.0, 0, 0, 0, 1.0])))
+ mid = corners.mean(0)
+ for k, wall in enumerate(self.walls):
+ a, b = np.asarray(wall[0], np.float64), np.asarray(wall[1], np.float64)
+ height = float(wall[2]) if len(wall) > 2 else self.wall_height
+ t = (b - a) / np.linalg.norm(b - a)
+ nrm = np.array([t[1], -t[0]])
+ if np.dot(nrm, (a + b) / 2 - mid) < 0: # thickness away from the mat
+ nrm = -nrm
+ end = self.wall_end_slide(k)
+ a0 = a + t * end # the main wall (shortened with an end piece)
+ quad = np.stack([a0, b, b + nrm * self.wall_thickness, a0 + nrm * self.wall_thickness])
+ v, f = prism_mesh(quad, top, top + height)
+ out.append(("walls", f"wall{k}", MeshBody(f"wall{k}", vertices=v, faces=f, color=self.color("walls")),
+ self.on_plane(np.r_[quad.mean(0), 0.0, 0, 0, 0, 1.0])))
+ if end > 0: # the end piece (RealDR.wall_end slides it)
+ e1, ins = a + t * (2 * end + self.WALL_END_OVERLAP), self.WALL_END_INSET
+ quad = np.stack([a + nrm * ins, e1 + nrm * ins, e1 + nrm * (self.wall_thickness + ins),
+ a + nrm * (self.wall_thickness + ins)])
+ v, f = prism_mesh(quad, top, top + height - ins)
+ out.append(("walls", f"wall{k}_end", MeshBody(f"wall{k}_end", vertices=v, faces=f,
+ color=self.color("walls")),
+ self.on_plane(np.r_[quad.mean(0), 0.0, 0, 0, 0, 1.0])))
+ if self.ceiling is not None:
+ v, f = box_mesh([(x1 - x0) / 2, (y1 - y0) / 2, 0.0025])
+ out.append(("walls", "ceiling", MeshBody("ceiling", vertices=v, faces=f, color=self.color("walls")),
+ self.on_plane([(x0 + x1) / 2, (y0 + y1) / 2, float(self.ceiling) + 0.0025, 0, 0, 0, 1.0])))
+ if self.strip is not None:
+ a, b = np.asarray(self.strip["from"], np.float64), np.asarray(self.strip["to"], np.float64)
+ w, t = self.strip.get("size", (0.02, 0.01))
+ length = float(np.linalg.norm(b - a))
+ v, f = box_mesh([length / 2, w / 2, t / 2])
+ q = _quat_from_two((1.0, 0.0, 0.0), b - a)
+ out.append(("strip", "strip", MeshBody("strip", vertices=v, faces=f, color=self.color("strip")),
+ self.on_plane(np.r_[(a + b) / 2, q[1:], q[0]])))
+ if self.room is not None:
+ v, f = box_mesh(self.room["half"])
+ c = np.asarray(self.room["center"], np.float64)
+ out.append(("room", "room", MeshBody("room", vertices=v, faces=_flip(f), color=self.color("room")),
+ np.r_[c, 0, 0, 0, 1.0]))
+ if self.room.get("floor_z") is not None: # the lab floor under the table (own group)
+ hx, hy, _ = self.room["half"]
+ v, f = box_mesh([hx * 0.98, hy * 0.98, 0.005])
+ out.append(("room_floor", "room_floor", MeshBody("room_floor", vertices=v, faces=f,
+ color=self.color("room_floor")),
+ np.r_[c[0], c[1], float(self.room["floor_z"]) - 0.005, 0, 0, 0, 1.0]))
+ if self.addon_slots: # base add-on slots: hidden until RealDR places them
+ hidden = np.array([0.0, 0.0, HIDDEN_Z, 0, 0, 0, 1.0])
+ for kind, dims in (("block", self.addon_slots.get("blocks", ())),
+ ("cable", self.addon_slots.get("cables", ())),
+ ("flat", self.addon_slots.get("flats", ())),
+ ("drop", self.addon_slots.get("drops", ()))):
+ for k, d in enumerate(dims):
+ half = [d[0] / 2, d[1] / 2, d[2] / 2] if kind == "block" else [d[0] / 2, d[1] / 2, d[1] / 2]
+ v, f = box_mesh(half)
+ name = f"addon_{kind}{k}"
+ out.append(("addon", name, MeshBody(name, vertices=v, faces=f, color=self.color("addon")), hidden))
+ return out
+
+ def floor_pivot(self) -> np.ndarray:
+ """(x, y) of the floor turn's pivot (flat-model frame): ``floor_turn["pivot"]``, else the middle of the floor
+ box's -x edge."""
+ ft = self.floor_turn or {}
+ if ft.get("pivot") is not None:
+ return np.asarray(ft["pivot"], np.float64)
+ x0, x1, y0, y1 = self.floor_xy
+ return np.array([x0, (y0 + y1) / 2])
+
+ def wall_end_slide(self, k: int) -> float:
+ """The slide range s (m) of wall k's end piece (0: no end piece)."""
+ we = self.wall_end
+ if not we or int(we["wall"]) != int(k):
+ return 0.0
+ s = float(we["slide"])
+ w = self.walls[k]
+ length = float(np.linalg.norm(np.asarray(w[1], np.float64) - np.asarray(w[0], np.float64)))
+ if not 0 < 2 * s + self.WALL_END_OVERLAP < length:
+ raise ValueError(f"wall_end slide {s}: needs 0 < 2 slide + {self.WALL_END_OVERLAP} < the wall length "
+ f"{length:.3f} m")
+ return s
+
+ def board_mesh(self, T_parent_cam) -> tuple[np.ndarray, np.ndarray] | None:
+ """The camera board + bracket (vertices in the camera's PARENT body frame, faces), or None."""
+ if not self.board:
+ return None
+ w, h, t = self.board["size"]
+ behind = float(self.board["behind"])
+ bw, bh, bd = self.board.get("bracket", (0.0, 0.0, 0.0))
+ parts = [box_mesh([w / 2, h / 2, t / 2], (0.0, 0.0, -(behind + t / 2)))]
+ if bw > 0:
+ parts.append(box_mesh([bw / 2, bh / 2, bd / 2], (0.0, h / 2 - bh / 2, -(behind + t + bd / 2))))
+ v = np.concatenate([p[0] for p in parts]).astype(np.float64)
+ f = np.concatenate([p[1] + 8 * k for k, p in enumerate(parts)])
+ if (v[:, 2] >= 0).any():
+ raise ValueError("the camera board must lie behind the wrist camera (camera z < 0)")
+ T = np.asarray(T_parent_cam, np.float64) # x y z, qw qx qy qz, OpenCV camera in the parent
+ r = np.zeros((3, 3))
+ qw, qx, qy, qz = T[3:7] / np.linalg.norm(T[3:7])
+ r[:] = [[1 - 2 * (qy * qy + qz * qz), 2 * (qx * qy - qw * qz), 2 * (qx * qz + qw * qy)],
+ [2 * (qx * qy + qw * qz), 1 - 2 * (qx * qx + qz * qz), 2 * (qy * qz - qw * qx)],
+ [2 * (qx * qz - qw * qy), 2 * (qy * qz + qw * qx), 1 - 2 * (qx * qx + qy * qy)]]
+ return (v @ r.T + T[:3]).astype(np.float32), f.astype(np.int32)
+
+
+@dataclass
+class RealDR:
+ """Per-world visual randomisation of the real scene (as build9's ``viral.DRConfig``), ranges centred on the real
+ scene (``real_scene_v1.json`` ``"dr"``: :meth:`from_dict`).
+
+ Per world (:meth:`draw`): per group a brightness factor ``bright`` (lo, hi) and a per-channel tint ``tint`` (+-) of
+ the albedo; camera pose offsets ``cam_pos`` (+- m per world axis) and ``cam_rot`` (+- rad per camera axis); the
+ mat pose (``mat_xy`` +- m, ``mat_yaw`` +- rad); the walls' xy (``wall_xy`` +- m); the tone map (``exposure``
+ (lo, hi) factor, ``wb`` +- per channel, ``black`` (lo, hi) linear offset added, ``gamma`` (lo, hi) factor,
+ ``vignette`` (lo, hi) exponent added; each a value for all cameras or a dict per camera name). Per call: the light
+ directions and point-light positions (:meth:`lights`, ``light_deg``, ``light_pos`` +- m per axis) and the
+ intrinsics (:meth:`camera_models`: ``focal`` +- fraction, ``pp_px`` +- px, quantised to ``focal_levels`` levels so
+ the renderer's ray cache is hit).
+
+ Background randomisation (studentlab external-camera fix, 2026-10-23; all OFF by default, drawn AFTER every other
+ per-world draw, so the other draws of a seed do not change when they are on): ``floor_turn_deg`` (+- deg about the
+ table normal through the scene's floor pivot, :meth:`RealScene.floor_pivot`) and ``floor_xy`` (+- m in x and y of
+ the table frame) move the floor box per world; ``wall_end`` (+- m) slides the scene's wall end piece
+ (``RealScene.wall_end``) along its wall; ``bg`` (dict of :class:`nedm.render.bg_dr.BgDR` fields; {} = off): the
+ image-space layers of the background (texture, clutter, spots, dark-area profile, floor gradient, low texture,
+ mat folds, boundary blur) in linear colour before the tone map; needs a renderer with ``bg_cameras``
+ (:meth:`bg_cameras`) and the output resolution (``draw(..., res=)``).
+
+ Base add-on randomisation (scene v4 round, 2026-10-23; OFF by default, drawn after everything else, also after
+ ``bg``): ``base_addon`` (dict of :class:`nedm.render.base_addon.BaseAddonDR` fields; {} = off): random blocks and
+ cables at the arm base outline in a share ``p`` of the worlds; needs a scene built with its slot bodies
+ (``RealScene.addon_slots`` = :meth:`addon_slots`; ``viral.load_real_setup`` sets them). Its random numbers come
+ from ``draw(..., addon_generator=)`` when given (``viral.DRViews`` gives its own, seed + 917), else from
+ ``generator`` after every other draw. Only with its own generator do the other draws of a seed stay the same over
+ SEVERAL calls (e.g. the online loop's per-world resets) with the add-ons on or off; with the shared generator only
+ the first call is paired.
+
+ Gripper-look randomisation (v12 visual fix, 2026-10-26; OFF by default, drawn after everything else, also after
+ the base add-ons): ``gripper_look`` (dict of :class:`nedm.render.gripper_look.GripperLookDR` fields; {} = off):
+ per world the albedo of the camera bracket plate and the servo bracket, the scene's fitted screws (shown, moved,
+ ring / centre albedo), extra light or dark marks on the gripper parts in the bottom half of the wrist view and a
+ bright plate top edge; needs a scene built with its parts (``RealScene.look_slots`` = :meth:`look_slots`;
+ ``viral.load_real_setup`` sets them); draw key ``part_pose`` [n, K, 7]. Its random numbers come from
+ ``draw(..., look_generator=)`` when given (``viral.DRViews``: seed + 921), else from ``generator`` after every
+ other draw.
+
+ Plate thickness (real2sim v8, from studentlab round C, 2026-10-23; OFF by default, drawn after every other draw
+ except the base add-ons): ``plate_thickness`` (lo, hi) m: per world the goal plate's thickness ~ U(lo, hi) (real plate 3.9 mm, sim 1 mm),
+ VISUAL ONLY (the physics cube still lands on z = 0): draw key ``plate_dz`` [n] = thickness - the scene's
+ ``plate_thickness`` (the plate's top above its nominal top; the renderer needs ``plate_depth=``
+ :meth:`plate_depth`); a cube over the plate is lifted visually so it never sinks deeper into the plate than in the
+ nominal scene (:meth:`SO101Scene._plate_shift`): a resting or placed cube is drawn on the plate's top. Pass the
+ held cubes (``render(..., cube_held=)``, the online loop does): a cube the jaws hold is drawn at its physics pose
+ (it sinks into a thicker plate in the last ``plate_dz`` above the table, as in the MuJoCo gate renders); without
+ ``cube_held`` every cube is lifted, and a held cube would slide up inside the closed jaws there, a cue the robot
+ never shows (its cube stops on the plate and the arm stalls)."""
+
+ bright: dict = field(default_factory=lambda: {"printed": (0.85, 1.1), "servo": (0.6, 2.0), "cube": (0.75, 1.25),
+ "plate": (0.75, 1.25), "floor": (0.8, 1.1), "mat": (0.5, 2.5),
+ "walls": (0.75, 1.1)})
+ tint: dict = field(default_factory=lambda: {"printed": 0.05, "servo": 0.1, "cube": 0.1, "plate": 0.1,
+ "floor": 0.05, "mat": 0.15, "walls": 0.06})
+ cam_pos: dict = field(default_factory=lambda: {"external": 0.01, "wrist": 0.002, "top": 0.01, "front": 0.01})
+ cam_rot: dict = field(default_factory=lambda: {"external": 0.03, "wrist": 0.02, "top": 0.03, "front": 0.03})
+ mat_xy: float = 0.01
+ mat_yaw: float = 0.03
+ wall_xy: float = 0.03
+ light_deg: float = 15.0
+ light_pos: float = 0.0
+ exposure: tuple | dict = (1.0, 1.0)
+ wb: float | dict = 0.0
+ black: tuple | dict = (0.0, 0.0)
+ gamma: tuple | dict = (1.0, 1.0)
+ vignette: tuple | dict = (0.0, 0.0)
+ focal: float = 0.0
+ pp_px: float = 0.0
+ focal_levels: int = 7
+ floor_turn_deg: float = 0.0
+ floor_xy: float = 0.0
+ wall_end: float = 0.0
+ bg: dict = field(default_factory=dict)
+ base_addon: dict = field(default_factory=dict)
+ gripper_look: dict = field(default_factory=dict)
+
+ @property
+ def look_on(self) -> bool:
+ """Gripper look on (``gripper_look`` set with a world probability above 0 and at least one draw)."""
+ return bool(self.gripper_look) and self.look_dr().on
+
+ def look_dr(self):
+ raise NotImplementedError("RealDR.gripper_look (nedm.render.gripper_look) "
+ "is not part of this release (study branch so101-pick-place-study)")
+
+ def look_slots(self, real: "RealScene") -> dict | None:
+ """The parts the scene ``real`` needs for ``gripper_look`` (``RealScene.look_slots``; None when off)."""
+ return self.look_dr().slots(real) if self.look_on else None
+
+ @property
+ def addon_on(self) -> bool:
+ """Base add-ons on (``base_addon`` set with a world probability above 0 and at least one block or cable)."""
+ return bool(self.base_addon) and self.addon_dr().on
+
+ def addon_dr(self):
+ raise NotImplementedError("RealDR.base_addon (nedm.render.base_addon) "
+ "is not part of this release (study branch so101-pick-place-study)")
+
+ def addon_slots(self) -> dict | None:
+ """The slot bodies the scene needs for ``base_addon`` (``RealScene.addon_slots``; None when off)."""
+ return self.addon_dr().slots() if self.addon_on else None
+ plate_thickness: tuple = ()
+
+ @property
+ def plate_on(self) -> bool:
+ """Plate thickness randomisation on (``plate_thickness`` = (lo, hi) m)."""
+ return bool(self.plate_thickness)
+
+ def plate_depth(self) -> float | None:
+ """The plate mesh depth a renderer needs for ``plate_thickness`` (its upper end; None: off)."""
+ if not self.plate_on:
+ return None
+ lo, hi = (float(v) for v in self.plate_thickness)
+ if not 0.0 < lo <= hi:
+ raise ValueError(f"RealDR.plate_thickness {self.plate_thickness}: (lo, hi) m with 0 < lo <= hi")
+ return hi
+
+ @property
+ def bg_on(self) -> bool:
+ """Background layers on (``bg`` set with a world probability above 0)."""
+ return bool(self.bg) and float(self.bg.get("p", 1.0)) > 0
+
+ def bg_dr(self):
+ raise NotImplementedError("RealDR.bg (nedm.render.bg_dr) "
+ "is not part of this release (study branch so101-pick-place-study)")
+
+ def bg_cameras(self, cameras: Sequence[str]) -> tuple:
+ """The cameras (in ``cameras`` order) that get the background layers (none when off)."""
+ return self.bg_dr().cams(cameras) if self.bg_on else ()
+
+ def bg_nominal(self, n: int, cameras: Sequence[str], res: int, device=None) -> dict:
+ """Background layers of n worlds without randomisation ({} when off), for nominal draws."""
+ if not self.bg_on:
+ return {}
+ return self.bg_dr()
+
+ @classmethod
+ def from_dict(cls, d: dict | None) -> "RealDR":
+ """From the scene file's ``"dr"`` section (keys = the field names; lists become tuples; unknown keys are an
+ error)."""
+ d = dict(d or {})
+ bad = set(d) - set(cls.__dataclass_fields__)
+ if bad:
+ raise ValueError(f"unknown RealDR keys {sorted(bad)}")
+ fix = lambda v: {k: tuple(x) if isinstance(x, list) else x for k, x in v.items()} if isinstance(v, dict) \
+ else (tuple(v) if isinstance(v, list) else v) # noqa: E731
+ return cls(**{k: fix(v) for k, v in d.items()})
+
+ @classmethod
+ def from_scene(cls, real: "RealScene") -> "RealDR":
+ """The ranges of a scene file (``real.dr``, real_scene_v1.json); the class defaults are placeholders."""
+ return cls.from_dict(real.dr)
+
+ @staticmethod
+ def _gen_device(generator) -> torch.device:
+ return torch.device(generator.device) if generator is not None else torch.device("cpu")
+
+ def draw(self, scene: "SO101Scene", n: int, generator: torch.Generator | None = None, device=None,
+ res: int | None = None, bg_prior: torch.Tensor | None = None,
+ addon_generator: torch.Generator | None = None, look_generator: torch.Generator | None = None) -> dict:
+ """Per-world draws for n worlds: ``colors`` [n, bodies, 3], ``cam_offset`` [n, C, 6] (dpos, drot),
+ ``env_pose`` [n, n_env, 7] (x y z qx qy qz qw) and, when the scene has a tone map, ``tone`` [n, C, 9]
+ (``camera_fx.TONE_KEYS``), for :meth:`SO101Renderer.render_dr`. Random numbers are drawn on the generator's
+ device (CPU without a generator); the results are on ``device`` (default the scene's). With ``bg`` on, also
+ the background layers ``bg_*`` (:mod:`nedm.render.bg_dr`) at the output resolution ``res`` (default: the
+ student view's output size); ``bg_prior`` [Cb, res, res]: placement weights of their clutter and spots
+ (:meth:`SO101Renderer.bg_prior`; None: uniform). ``addon_generator``: the base add-on draws' own generator
+ (None: ``generator``; class docstring). ``look_generator``: the gripper-look draws' own generator (v12)."""
+ gdev = self._gen_device(generator)
+ dev = torch.device(device or scene.device)
+
+ def u(lo, hi, *shape):
+ return (lo + (hi - lo) * torch.rand(n, *shape, device=gdev, generator=generator,
+ dtype=torch.float64)).to(dev)
+
+ base = torch.tensor([m.color for m in scene.scene.bodies], dtype=torch.float64, device=dev)
+ cols = base.expand(n, *base.shape).clone()
+ for g, idx in scene.groups.items():
+ if not idx or g in ("addon", "look"): # the slots get their colours from base_addon / gripper_look
+ continue
+ lo, hi = self.bright.get(g, (1.0, 1.0))
+ ti = self.tint.get(g, 0.0)
+ cols[:, idx] = (cols[:, idx] * u(lo, hi, 1, 1) * u(1 - ti, 1 + ti, 1, 3)).clamp(0, 1)
+ C = len(scene.cameras)
+ pos = torch.tensor([self.cam_pos.get(c, 0.0) for c in scene.cameras], dtype=torch.float64, device=dev)
+ rot = torch.tensor([self.cam_rot.get(c, 0.0) for c in scene.cameras], dtype=torch.float64, device=dev)
+ off = torch.cat([u(-1, 1, C, 3) * pos[None, :, None], u(-1, 1, C, 3) * rot[None, :, None]], -1)
+ env0 = scene.env_pose.to(dev)
+ env = env0.expand(n, *scene.env_pose.shape).clone()
+ names = list(getattr(scene, "env_names", ()))
+ for k, g in enumerate(scene.env_groups):
+ if g == "mat":
+ env[:, k, :2] += u(-1, 1, 2) * self.mat_xy
+ turn = yaw_quat(u(-1, 1) * self.mat_yaw)
+ env[:, k, 3:] = xyzw(qmul(wxyz(env[:, k, 3:]), turn)) # about the mat's own normal
+ elif g == "walls":
+ if names and names[k].endswith("_end"): # a wall end piece moves with its wall
+ kp = names.index(names[k][:-4])
+ env[:, k, :2] += env[:, kp, :2] - env0[kp, :2]
+ else:
+ env[:, k, :2] += u(-1, 1, 2) * self.wall_xy
+ out = dict(colors=cols.float(), cam_offset=off.float(), env_pose=env)
+ tone = getattr(scene, "tone_params", None)
+ if tone is not None:
+ t = tone.to(dev, torch.float64).expand(n, *tone.shape).clone() # [n, C, 9]
+
+ def rng(v, default):
+ """(lo, hi) [C, 2] of a per-camera dict or one value / pair for all cameras."""
+ vals = [v.get(c, default) if isinstance(v, dict) else v for c in scene.cameras]
+ vals = [(-x, x) if not isinstance(x, (tuple, list)) else tuple(x) for x in vals]
+ return torch.tensor(vals, dtype=torch.float64, device=dev)
+
+ def uc(v, default, *shape):
+ r = rng(v, default)
+ return r[:, 0].view(C, *([1] * len(shape))) + (r[:, 1] - r[:, 0]).view(C, *([1] * len(shape))) \
+ * u(0, 1, C, *shape)
+
+ t[..., 0] *= uc(self.exposure, (1.0, 1.0))
+ t[..., 1:4] *= 1 + uc(self.wb, 0.0, 3)
+ t[..., 4:7] += uc(self.black, (0.0, 0.0), 1)
+ t[..., 7] *= uc(self.gamma, (1.0, 1.0))
+ t[..., 8] += uc(self.vignette, (0.0, 0.0))
+ out["tone"] = t.float()
+ # background randomisation (class docstring): after every other draw
+ if self.floor_turn_deg or self.floor_xy:
+ self._floor_draw(scene, env, names, u, dev)
+ if self.wall_end:
+ self._wall_end_draw(scene, env, names, u, dev)
+ if self.bg_on:
+ cams = self.bg_cameras(scene.cameras)
+ if res is None:
+ views = [scene.real.view(c) for c in cams]
+ if not views or any(v is None for v in views):
+ raise ValueError("RealDR.bg: pass the output resolution (draw(..., res=))")
+ res = views[0].out_wh[0]
+ out.update(self.bg_dr().draw(n, len(cams), int(res), generator, dev, prior=bg_prior))
+ if self.plate_on: # v8: after every other draw but the add-ons (class docstring)
+ if getattr(scene, "plate_depth", None) is None:
+ raise ValueError("RealDR.plate_thickness: build the renderer with plate_depth=RealDR.plate_depth()")
+ hi = self.plate_depth()
+ lo = float(self.plate_thickness[0])
+ if hi > scene.plate_depth + 1e-12:
+ raise ValueError(f"RealDR.plate_thickness {self.plate_thickness} > the renderer's plate_depth "
+ f"{scene.plate_depth}")
+ out["plate_dz"] = u(lo, hi) - float(scene.real.plate_thickness)
+ if self.addon_on: # base add-ons: the very last draws (slots of a scene without it: hidden)
+ ua = u
+ if addon_generator is not None: # their own generator: the main one is not used for them
+ adev = self._gen_device(addon_generator)
+
+ def ua(lo, hi, *shape):
+ return (lo + (hi - lo) * torch.rand(n, *shape, device=adev, generator=addon_generator,
+ dtype=torch.float64)).to(dev)
+ self.addon_dr().draw(scene, n, ua, dev, out)
+ if self.look_on: # v12 gripper look: after everything else (class docstring)
+ if getattr(scene, "look_index", None) is None:
+ raise ValueError("RealDR.gripper_look: the scene has no look parts (build it with "
+ "RealScene(look_slots=RealDR.look_slots(real)); viral.load_real_setup does it)")
+ ul = u
+ if look_generator is not None:
+ ldev = self._gen_device(look_generator)
+
+ def ul(lo, hi, *shape):
+ return (lo + (hi - lo) * torch.rand(n, *shape, device=ldev, generator=look_generator,
+ dtype=torch.float64)).to(dev)
+ self.look_dr().draw(scene, n, ul, dev, out)
+ return out
+
+ def _floor_draw(self, scene, env, names, u, dev) -> None:
+ """Floor box per world: turned by +- floor_turn_deg about the table normal through the scene's floor pivot,
+ then shifted by +- floor_xy in x and y of the table frame (in place on ``env``)."""
+ if "floor" not in names:
+ raise ValueError("RealDR.floor_turn_deg / floor_xy: the scene has no floor")
+ k = names.index("floor")
+ n = env.shape[0]
+ th = u(-1, 1) * math.radians(float(self.floor_turn_deg))
+ sh = u(-1, 1, 2) * float(self.floor_xy)
+ o, qp = scene.plane_o.to(dev), scene.plane_q.to(dev)
+ qi = qp * torch.tensor([1.0, -1.0, -1.0, -1.0], dtype=qp.dtype, device=dev)
+ piv = torch.as_tensor(scene.real.floor_pivot(), dtype=env.dtype, device=dev)
+ pf = qrot(qi.expand(n, 4), env[:, k, :3] - o) # table frame
+ d = pf[:, :2] - piv
+ c, s = torch.cos(th), torch.sin(th)
+ pf = torch.stack([piv[0] + c * d[:, 0] - s * d[:, 1] + sh[:, 0], piv[1] + s * d[:, 0] + c * d[:, 1] + sh[:, 1],
+ pf[:, 2]], -1)
+ env[:, k, :3] = o + qrot(qp.expand(n, 4), pf)
+ env[:, k, 3:] = xyzw(qmul(wxyz(env[:, k, 3:]), yaw_quat(th))) # about its own normal
+
+ def _wall_end_draw(self, scene, env, names, u, dev) -> None:
+ """Wall end pieces per world: slid by +- wall_end along their wall (in place on ``env``)."""
+ ends = [k for k, nm in enumerate(names) if nm.endswith("_end")]
+ if not ends:
+ raise ValueError("RealDR.wall_end needs a wall end piece in the scene (geometry.wall_end)")
+ n = env.shape[0]
+ qp = scene.plane_q.to(dev)
+ for k in ends:
+ w = int(names[k][len("wall"):-4])
+ if float(self.wall_end) > scene.real.wall_end_slide(w) + 1e-12:
+ raise ValueError(f"RealDR.wall_end {self.wall_end} > the scene's wall_end slide "
+ f"{scene.real.wall_end_slide(w)}")
+ a, b = (np.asarray(p, np.float64) for p in scene.real.walls[w][:2])
+ t = torch.tensor(np.r_[(b - a) / np.linalg.norm(b - a), 0.0], dtype=env.dtype, device=dev)
+ env[:, k, :3] += (u(-1, 1) * float(self.wall_end))[:, None] * qrot(qp.expand(n, 4), t.expand(n, 3))
+
+ def lights(self, lights: Sequence[dict], generator: torch.Generator | None = None) -> list[dict]:
+ """The lights with each direction turned by up to ``light_deg`` about a random axis (one draw per call);
+ lights without a direction (point lights) are kept. Random numbers on the generator's device."""
+ gdev = self._gen_device(generator)
+ out = []
+ for lt in lights:
+ lt = dict(lt)
+ if "direction" in lt:
+ d = np.asarray(lt["direction"], np.float64)
+ axis = torch.randn(3, generator=generator, dtype=torch.float64, device=gdev).cpu().numpy()
+ ang = math.radians(self.light_deg) * float(torch.rand(1, generator=generator, dtype=torch.float64,
+ device=gdev))
+ q = np.r_[math.cos(ang / 2), math.sin(ang / 2) * axis / np.linalg.norm(axis)]
+ lt["direction"] = qrot(torch.tensor(q), torch.tensor(d / np.linalg.norm(d))).tolist()
+ elif "position" in lt and self.light_pos > 0:
+ dp = (2 * torch.rand(3, generator=generator, dtype=torch.float64, device=gdev) - 1).cpu().numpy()
+ lt["position"] = (np.asarray(lt["position"], np.float64) + self.light_pos * dp).tolist()
+ out.append(lt)
+ return out
+
+ def camera_models(self, scene: "SO101Scene", generator: torch.Generator | None = None, out_res: int = 224) -> list:
+ """One intrinsics draw per call (rays are shared by all worlds): per calibrated camera fx, fy scaled by one
+ of ``focal_levels`` levels in 1 +- ``focal`` and cx, cy moved by up to +- ``pp_px``, rounded to 0.5 px;
+ other cameras unchanged. For :meth:`SO101Renderer.set_camera_models`."""
+ gdev = self._gen_device(generator)
+ models = []
+ for name, m in zip(scene.cameras, scene.camera_models):
+ if name not in REAL_CAMERAS:
+ models.append(m)
+ continue
+ r = torch.rand(3, generator=generator, dtype=torch.float64, device=gdev).cpu().numpy()
+ L = max(1, int(self.focal_levels))
+ k = 1.0 + (self.focal * (2 * round(r[0] * (L - 1)) / (L - 1) - 1) if L > 1 else 0.0)
+ pp = tuple(round(2 * self.pp_px * (x - 0.5) * 2) / 2 for x in r[1:])
+ models.append(scene.real.camera_model(name, k_scale=k, pp_shift=pp, out_res=out_res))
+ return models
+
+
+def axis_angle_quat(v: torch.Tensor) -> torch.Tensor:
+ """[..., 3] rotation vectors -> quaternions w x y z (as ``viral._quat_axis_angle``)."""
+ a = v.norm(dim=-1, keepdim=True)
+ s = torch.where(a > 1e-12, torch.sin(a / 2) / a.clamp_min(1e-12), torch.full_like(a, 0.5))
+ return torch.cat((torch.cos(a / 2), v * s), -1)
+
+
+def offset_cameras(cam_q: torch.Tensor, cam_offset: torch.Tensor) -> torch.Tensor:
+ """Camera transforms [B, C, 7] (x y z qx qy qz qw) moved by ``cam_offset`` [B, C, 6]: + dpos in the world, then
+ turned by the rotation vector drot in the camera's own frame (build9's camera randomisation)."""
+ cq = cam_q.clone()
+ off = cam_offset.to(cq)
+ cq[..., :3] = cq[..., :3] + off[..., :3]
+ cq[..., 3:] = xyzw(qmul(wxyz(cq[..., 3:]), axis_angle_quat(off[..., 3:])))
+ return cq
+
+
+# ---- renderer -----------------------------------------------------------------------------------------------------
+class SO101Renderer:
+ """Images of ``num_worlds`` SO101 worlds per call from the ``cameras`` (names from VIEWS, default front + wrist),
+ with Kyle's batch renderer.
+
+ ``backend``: ``"newton"`` (Warp: NVIDIA, AMD, CPU; ``device`` = a Warp device, default the GPU if there is one;
+ the study's ``"madrona"`` backend is not part of this release). All cameras share one resolution
+ (``width`` x ``height``, e.g. 224 x 224 for ACT) and the wrist camera's field of view (fovy 61 deg, ``so101.xml``).
+ Calls with fewer than ``num_worlds`` rows are padded (the extra worlds repeat row 0) and the outputs cut back.
+
+ ``real``: a :class:`RealScene` (Newton only, off by default): the real setup with its calibrated cameras (default
+ ``external`` + ``wrist``; every output pixel samples the camera's crop box, pixels without a ray are black), the
+ scene's lights and sky (``sky`` is ignored). Per-world randomisation: :class:`RealDR` + :meth:`render_dr`.
+ With the student-view crop rules (``real.crop`` None) the view's output size must equal ``width`` x ``height``
+ (ValueError otherwise). ``real.tone``: the colour is Newton's linear output through the per-camera tone map
+ (:mod:`nedm.render.camera_fx`) and, with ``real.image_fx``, the nominal camera effects of each camera (blur,
+ chroma bleeding: ``ImageFX.nominal``); ``real.supersample`` s: s x s rays per output pixel, tone-mapped, then
+ averaged.
+ ``segment``: :meth:`render` can also return the body index per pixel (real scene). ``hdr``: keep Newton's linear
+ colour even without a tone map (``render(..., hdr=True)``). At construction the real scene renders one frame and
+ raises if more than ``NEAR_FRAC`` of a calibrated camera's pixels are closer than ``NEAR_M`` (a body in front of
+ the lens, e.g. a camera mount: review finding 2).
+ ``bg_cameras`` (real scene with a tone map; default none): the cameras that take background layers
+ (:class:`RealDR` ``bg``, :mod:`nedm.render.bg_dr`) in :meth:`render_dr` / :meth:`render` (``bg=``); builds the
+ segment output internally (the colours are the same as without it). ``bg_dark_groups``: the groups of the dark
+ area outside the light box (``BgDR.dark_groups``).
+ ``plate_depth`` (real scene; None = off): the plate mesh depth for the per-world plate thickness (:class:`RealDR`
+ ``plate_thickness``, ``render(..., plate_dz=)``; :class:`SO101Scene`).
+ """
+
+ NEAR_M = 0.012
+ NEAR_FRAC = 0.2
+ TONE_CHUNK = 1 << 25 # sub-pixels per tone-map chunk (float temporaries about 0.4 GB each)
+
+ def __init__(self, num_worlds: int, width: int = 128, height: int = 128, backend: str = "newton",
+ shadows: bool = True, assets: SO101Assets | None = None, cube_colors=None, goal: str | None = "plate",
+ front_eye=FRONT_EYE, front_target=FRONT_TARGET, sky=SKY, device=None,
+ cameras: Sequence[str] | None = None, top_eye=TOP_EYE, top_target=TOP_TARGET,
+ table_body: bool = False, real: "RealScene | None" = None, segment: bool = False,
+ hdr: bool = False, bg_cameras: Sequence[str] = (),
+ bg_dark_groups: Sequence[str] = ("room", "room_floor"), plate_depth: float | None = None):
+ from nedm.render.renderer import BatchRenderer
+ if backend == "madrona":
+ torch_device = "cuda:0"
+ else:
+ torch_device = "cuda:0" if ("cuda" in str(device) or (device is None and torch.cuda.is_available())) \
+ else "cpu"
+ self.scene = SO101Scene(assets, cube_colors, goal, front_eye, front_target, device=torch_device,
+ cameras=cameras, top_eye=top_eye, top_target=top_target, table_body=table_body,
+ real=real, **({} if plate_depth is None else dict(plate_depth=plate_depth)))
+ self.cameras = self.scene.cameras
+ self.real = real
+ self.bg_cameras = tuple(bg_cameras or ())
+ if self.bg_cameras:
+ if real is None or real.tone is None:
+ raise ValueError("bg_cameras: background layers need the real scene with a tone map")
+ if not set(self.bg_cameras) <= set(self.cameras):
+ raise ValueError(f"bg_cameras {self.bg_cameras} are not all in the cameras {self.cameras}")
+ self.bg_cameras = tuple(c for c in self.cameras if c in self.bg_cameras) # the cameras' order
+ bad = set(bg_dark_groups) - set(REAL_GROUPS)
+ if bad:
+ raise ValueError(f"bg_dark_groups {sorted(bad)} are not groups of the real scene {REAL_GROUPS}")
+ self._bg_dark_codes = tuple(REAL_GROUPS.index(g) for g in bg_dark_groups)
+ if real is None:
+ if segment or hdr:
+ raise ValueError("segment / hdr outputs need the real scene")
+ self.renderer = BatchRenderer(self.scene.scene, num_worlds, width, height, cameras=len(self.cameras),
+ fov_deg=self.scene.fovy_deg, device=device, shadows=shadows, sky=sky,
+ backend=backend)
+ else:
+ if backend != "newton":
+ raise NotImplementedError("the real scene's calibrated cameras need the newton backend")
+ for name in self.cameras:
+ view = real.view(name, width) if name in REAL_CAMERAS else None
+ if view is not None and view.out_wh != (int(width), int(height)):
+ raise ValueError(f"{name}: the student view's output {view.out_wh} differs from the renderer size "
+ f"{(width, height)} (real_scene student_view / RealScene.student_view)")
+ self.ss = int(real.supersample)
+ if self.ss < 1:
+ raise ValueError("supersample >= 1")
+ self.renderer = BatchRenderer(self.scene.scene, num_worlds, width * self.ss, height * self.ss,
+ cameras=len(self.cameras), fov_deg=self.scene.fovy_deg, device=device,
+ shadows=shadows, sky=tuple(real.sky), backend=backend,
+ camera_models=self.scene.camera_models,
+ hdr=bool(hdr or real.tone is not None),
+ segment=bool(segment or self.bg_cameras))
+ self.set_lights(real.lights, shadows=bool(shadows and real.shadows), ambient=real.ambient)
+ self.device = torch.device(torch_device)
+ self.num_worlds, self.width, self.height, self.backend = int(num_worlds), int(width), int(height), backend
+ self.shadows = bool(shadows)
+ self._nominal = True
+ if real is not None: # per camera: ray length -> z-depth (0 at pixels without a ray)
+ self._fx = None
+ if real.tone is not None and real.image_fx:
+ from nedm.render.camera_fx import ImageFX
+ f = ImageFX.from_dict(real.image_fx)
+ if any(f._per_camera(v, c) > 0 for v in (f.nominal_blur_px, f.nominal_chroma_px)
+ for c in self.cameras):
+ self._fx = f
+ self._update_rays()
+ if self.bg_cameras: # Newton shape index -> group code (REAL_GROUPS order; -1: none)
+ lut = torch.as_tensor(self.renderer.backend.shape_body, dtype=torch.long)
+ body_group = torch.full((int(lut.max()) + 2,), -1, dtype=torch.long)
+ for gi, g in enumerate(REAL_GROUPS):
+ for b in self.scene.groups.get(g, ()):
+ body_group[b] = gi
+ self._shape_group = body_group[lut].to(self.device)
+ self.check_near()
+ return
+ # ray length -> z-depth, at pixel centres (fovy vertical, square pixels)
+ focal = 0.5 * height / math.tan(math.radians(self.scene.fovy_deg) / 2)
+ u = (torch.arange(width, dtype=torch.float64) + 0.5 - width / 2) / focal
+ v = (torch.arange(height, dtype=torch.float64) + 0.5 - height / 2) / focal
+ self.z_per_ray = (1.0 / torch.sqrt(1 + u[None, :] ** 2 + v[:, None] ** 2)).float().to(self.device)
+
+ @property
+ def valid_mask(self) -> torch.Tensor | None:
+ """[C, H, W] bool: pixels with a ray (real scene; with supersampling: all sub-pixels have one). None: the
+ sim scene (Newton's own pinholes, every pixel has a ray)."""
+ if self.real is None:
+ return self.renderer.valid_mask
+ return self._valid_out.cpu()
+
+ def _pool(self, x: torch.Tensor) -> torch.Tensor:
+ """Mean over the s x s sub-pixels: [..., H*s, W*s] -> [..., H, W]."""
+ s = self.ss
+ if s == 1:
+ return x
+ return x.unflatten(-1, (x.shape[-1] // s, s)).unflatten(-3, (x.shape[-2] // s, s)).mean((-1, -3))
+
+ def _update_rays(self) -> None:
+ b = self.renderer.backend
+ self.z_per_ray = torch.from_numpy(b.ray_z).to(self.device) # [C, H*s, W*s]
+ valid = torch.from_numpy(b.valid).to(self.device)
+ self._valid_sub = valid
+ self._valid_out = self._pool(valid.float()) > 0.999
+ # cos of each sub-pixel ray's angle to the optical axis (vignetting)
+ self._cos_theta = self.z_per_ray.clamp_min(0.0)
+
+ def set_camera_models(self, models: Sequence) -> None:
+ """New camera models, one per camera in :attr:`cameras` order (Newton; e.g. intrinsics randomised per call:
+ rays are shared by all worlds of a call; :meth:`RealDR.camera_models`). Updates the z-depth factors. The
+ renderer keeps the last ray sets (``NewtonBackend.RAY_CACHE``), so a few alternating draws cost nothing."""
+ self.renderer.set_camera_models(models)
+ if self.real is None:
+ self.z_per_ray = torch.from_numpy(self.renderer.backend.ray_z).to(self.device)
+ else:
+ self._update_rays()
+
+ def check_near(self, q=None) -> dict:
+ """Render one frame of the nominal real scene (arm at ``q``, default zeros, cube and goal hidden far away) and
+ raise if more than ``NEAR_FRAC`` of the valid pixels of a calibrated camera are closer than ``NEAR_M``.
+ Returns {camera: fraction}."""
+ q = torch.zeros(1, 6, dtype=torch.float64) if q is None else torch.as_tensor(q, dtype=torch.float64)
+ cube = torch.tensor([[0.0, 0.0, HIDDEN_Z]], dtype=torch.float64)
+ quat = torch.tensor([[1.0, 0.0, 0.0, 0.0]], dtype=torch.float64)
+ _, d = self.render(q, cube, quat, None, depth=True)
+ out = {}
+ for c, name in enumerate(self.cameras):
+ if name not in REAL_CAMERAS:
+ continue
+ v = self._valid_out[c]
+ dc = d[0, c][v]
+ frac = float(((dc > 0) & (dc < self.NEAR_M)).float().mean()) if dc.numel() else 0.0
+ out[name] = frac
+ if frac > self.NEAR_FRAC:
+ raise ValueError(f"{name}: {100 * frac:.0f} % of the pixels are closer than {self.NEAR_M} m (a body in "
+ f"front of the lens: hide it with RealScene.hide_bodies)")
+ return out
+
+ def bg_prior(self, q=None) -> torch.Tensor:
+ """[Cb, H, W] float: the share of dark-area sub-pixels (``bg_dark_groups``) per output pixel of the
+ ``bg_cameras`` in one nominal frame (arm at ``q``, default zeros; cube and plate hidden): placement weights
+ of the background clutter and spots (:meth:`RealDR.draw` ``bg_prior``)."""
+ if not self.bg_cameras:
+ raise ValueError("bg_prior: build the renderer with bg_cameras")
+ q = torch.zeros(1, 6, dtype=torch.float64) if q is None else torch.as_tensor(q, dtype=torch.float64)
+ cube = torch.tensor([[0.0, 0.0, HIDDEN_Z]], dtype=torch.float64)
+ quat = torch.tensor([[1.0, 0.0, 0.0, 0.0]], dtype=torch.float64)
+ body_q, cam_q = self.scene.transforms(q, cube, quat, None)
+ body_q = torch.cat([body_q, body_q[:1].expand(self.num_worlds - 1, *body_q.shape[1:])])
+ cam_q = torch.cat([cam_q, cam_q[:1].expand(self.num_worlds - 1, *cam_q.shape[1:])])
+ frames = self.renderer.render(cam_q, body_q=body_q)
+ sh = frames.shape_index_torch()[:1]
+ gid = torch.where(sh >= 0, self._shape_group[sh.clamp_min(0)], torch.full_like(sh, -1))[0]
+ dark = torch.zeros_like(gid, dtype=torch.bool)
+ for c in self._bg_dark_codes:
+ dark |= gid == c
+ idx = [self.cameras.index(c) for c in self.bg_cameras]
+ return self._pool(dark[idx].float())
+
+ def set_lights(self, lights: Sequence[dict], shadows: bool | None = None, ambient: bool | None = None) -> None:
+ """Replace the lights of every world (Newton: :meth:`~nedm.render.backends.newton.NewtonBackend.set_lights`)."""
+ if not hasattr(self.renderer.backend, "set_lights"):
+ raise NotImplementedError("set_lights: newton backend only")
+ self.renderer.backend.set_lights(list(lights), shadows=shadows, ambient=ambient)
+
+ @property
+ def geom_names(self) -> list[str]:
+ """Names of the backend's drawn objects in its order: the bodies, then the statics (base meshes, table)."""
+ return self.scene.body_names + [mesh.name for mesh, _ in self.scene.scene.statics]
+
+ def render(self, q, cube_pos, cube_quat, goal_pose=None, depth: bool = False, copy: bool = True,
+ env_pose=None, cam_offset=None, tone=None, segment: bool = False, hdr: bool = False, bg=None,
+ plate_dz=None, world_plane=None, cube_held=None, part_pose=None):
+ """rgb [B, C, H, W, 3] uint8 (cameras in :attr:`cameras` order), and with ``depth`` also z-depth [B, C, H, W]
+ float32 (m along the camera axis, 0 = nothing hit). Inputs as :meth:`SO101Scene.transforms`, any device and
+ float dtype, B <= num_worlds. ``copy=False`` returns a view of the renderer's buffer (overwritten by the next
+ call). ``env_pose`` [B, n_env, 7] (real scene): floor, mat and wall poses; ``cam_offset`` [B, C, 6]: per-world
+ camera pose offsets (:func:`offset_cameras`).
+
+ Real scene only: ``tone`` [B, C, 9] per-world tone maps (default the scene's); ``segment`` (renderer built with
+ ``segment=True``): also the scene body index per pixel [B, C, H, W] int64 (-1 nothing hit, -2 sub-pixels
+ disagree); ``hdr``: also the linear colour [B, C, H, W, 3] float32 (sub-pixel mean; rays that hit nothing get
+ the sky colour turned linear). Extra outputs follow rgb (and depth) in the order segment, hdr. ``bg``: the
+ background layers (``bg_*`` of :meth:`RealDR.draw`, rows = B) of the ``bg_cameras``, applied to the linear
+ colour before the tone map (the ``hdr`` output stays the renderer's own). ``plate_dz`` [B] (renderer built with
+ ``plate_depth``): the per-world plate thickness (:meth:`SO101Scene._plate_shift`); ``cube_held`` [B]: held
+ cubes (no plate lift); ``world_plane`` [B, 3]: per-world table planes; ``part_pose`` [B, K, 7]: the
+ gripper-look parts' local poses (v12; :meth:`SO101Scene.transforms`)."""
+ if plate_dz is not None or world_plane is not None or cube_held is not None or part_pose is not None:
+ tkw = {k: v for k, v in dict(plate_dz=plate_dz, world_plane=world_plane, cube_held=cube_held,
+ part_pose=part_pose).items() if v is not None}
+ body_q, cam_q = self.scene.transforms(q, cube_pos, cube_quat, goal_pose, env_pose=env_pose, **tkw)
+ elif env_pose is None:
+ body_q, cam_q = self.scene.transforms(q, cube_pos, cube_quat, goal_pose)
+ else:
+ body_q, cam_q = self.scene.transforms(q, cube_pos, cube_quat, goal_pose, env_pose=env_pose)
+ if cam_offset is not None:
+ cam_q = offset_cameras(cam_q, torch.as_tensor(cam_offset, device=cam_q.device))
+ n = body_q.shape[0]
+ if n > self.num_worlds:
+ raise ValueError(f"{n} states for {self.num_worlds} worlds")
+ if n < self.num_worlds:
+ pad = self.num_worlds - n
+ body_q = torch.cat([body_q, body_q[:1].expand(pad, *body_q.shape[1:])])
+ cam_q = torch.cat([cam_q, cam_q[:1].expand(pad, *cam_q.shape[1:])])
+ frames = self.renderer.render(cam_q, body_q=body_q)
+ if self.real is not None:
+ return self._real_outputs(frames, n, depth, tone, segment, hdr, bg)
+ if bg is not None:
+ raise ValueError("bg layers need the real scene")
+ rgb = frames.rgb_torch()[:n]
+ if copy:
+ rgb = rgb.clone(memory_format=torch.contiguous_format)
+ if not depth:
+ return rgb
+ return rgb, frames.depth_torch()[:n] * self.z_per_ray.to(rgb.device)
+
+ def _real_outputs(self, frames, n, depth, tone, segment, hdr, bg=None):
+ """The real scene's outputs: tone map per sub-pixel, then the sub-pixel mean (as the real frame: tone-mapped
+ sensor pixels, then area-averaged to the student size)."""
+ from nedm.render import camera_fx as fx
+ dz = frames.depth_torch()[:n] * self.z_per_ray # [n, C, Hs, Ws] z-depth, 0: no hit
+ sky = (dz == 0) & self._valid_sub[None]
+ sky8 = torch.tensor(self.real.sky, dtype=torch.float32, device=dz.device) / 255.0
+ params = self.scene.tone_params if tone is None else torch.as_tensor(tone, dtype=torch.float32)
+ gid = None
+ if bg is not None:
+ if not self.bg_cameras:
+ raise ValueError("bg layers: build the renderer with bg_cameras")
+ if params is None:
+ raise ValueError("bg layers need the tone map (linear colour)")
+ sh = frames.shape_index_torch()[:n]
+ gid = torch.where(sh >= 0, self._shape_group[sh.clamp_min(0)], torch.full_like(sh, -1))
+ cb = len(self.bg_cameras)
+ for k in ("bg_tex", "bg_low", "bg_mat", "bg_par"):
+ if bg[k].shape[:2] != (n, cb):
+ raise ValueError(f"{k} {tuple(bg[k].shape)}: expected [{n}, {cb}, ...] (bg_cameras "
+ f"{self.bg_cameras})")
+ if params is not None:
+ x = frames.hdr_torch()[:n]
+ rgb = torch.empty(n, x.shape[1], self.height, self.width, 3, dtype=torch.uint8, device=x.device)
+ step = max(1, self.TONE_CHUNK // (x.shape[1] * x.shape[2] * x.shape[3])) # bounded temporaries
+ for i in range(0, n, step):
+ pi = params if params.dim() == 2 else params[i:i + step]
+ xi = x[i:i + step]
+ if gid is not None:
+ xi = self._apply_bg(xi, gid[i:i + step], {k: v[i:i + step] for k, v in bg.items()})
+ y = fx.tone_map(xi, pi, self._cos_theta)
+ y = torch.where(sky[i:i + step, ..., None], sky8, y)
+ y = torch.where(self._valid_sub[None, ..., None], y, 0.0)
+ y = self._pool(y.movedim(-1, 2)).movedim(2, -1)
+ if self._fx is not None: # the real cameras' sharpness and colour bleeding
+ y = torch.stack([self._fx.nominal(y[:, c], cam) for c, cam in enumerate(self.cameras)], 1)
+ rgb[i:i + step] = fx.to_uint8(y)
+ elif self.ss > 1:
+ y = frames.rgb_torch()[:n].float()
+ rgb = (self._pool(y.movedim(-1, 2)).movedim(2, -1) + 0.5).clamp(0, 255).to(torch.uint8)
+ else:
+ rgb = frames.rgb_torch()[:n].clone(memory_format=torch.contiguous_format)
+ out = [rgb]
+ if depth:
+ hit = (dz > 0).float()
+ out.append(self._pool(dz) / self._pool(hit).clamp_min(1e-6) * (self._pool(hit) > 0))
+ if segment:
+ sh = frames.shape_index_torch()[:n]
+ lut = torch.as_tensor(self.renderer.backend.shape_body, device=sh.device)
+ seg = torch.where(sh >= 0, lut[sh.clamp_min(0)], torch.full_like(sh, -1))
+ s = self.ss
+ if s > 1:
+ blk = seg.unflatten(-1, (seg.shape[-1] // s, s)).unflatten(-3, (seg.shape[-2] // s, s))
+ first = blk[..., :1, :, :1]
+ same = (blk == first).all(-1).all(-2)
+ seg = torch.where(same, first[..., 0, :, 0], torch.full_like(same, -2, dtype=seg.dtype))
+ out.append(seg)
+ if hdr:
+ x = frames.hdr_torch()[:n].clone()
+ x = torch.where(sky[..., None], fx.srgb_eotf(sky8), x)
+ out.append(self._pool(x.movedim(-1, 2)).movedim(2, -1))
+ return out[0] if len(out) == 1 else tuple(out)
+
+ def _apply_bg(self, x, gid, bg):
+ """Background layers on the bg cameras: the study's ``bg_dr`` module is not part of this release (study
+ branch so101-pick-place-study)."""
+ raise NotImplementedError("background layers (nedm.render.bg_dr) "
+ "are not part of this release (study branch so101-pick-place-study)")
+
+ def render_dr(self, q, cube_pos, cube_quat, goal_pose=None, draw: dict | None = None, **kw):
+ """:meth:`render` with per-world randomisation ``draw`` (:meth:`RealDR.draw`: colors [B, bodies, 3],
+ cam_offset [B, C, 6], env_pose [B, n_env, 7], tone [B, C, 9], background layers ``bg_*``, plate_dz [B],
+ part_pose [B, K, 7] (gripper look); any
+ key may be missing: a missing key means its nominal value, also for the colours), or the nominal scene with
+ None. Newton colours are per world (rows beyond B repeat row 0)."""
+ if draw is None or draw.get("colors") is None:
+ if not self._nominal:
+ self.set_appearance(reset=True)
+ self._nominal = True
+ if draw is None:
+ return self.render(q, cube_pos, cube_quat, goal_pose, **kw)
+ else:
+ cols = torch.as_tensor(draw["colors"], dtype=torch.float32)
+ if cols.shape[0] < self.num_worlds:
+ cols = torch.cat([cols, cols[:1].expand(self.num_worlds - cols.shape[0], *cols.shape[1:])])
+ self.set_appearance(cols)
+ self._nominal = False
+ if draw.get("tone") is not None:
+ kw["tone"] = draw["tone"]
+ if draw.get("bg_par") is not None:
+ kw["bg"] = {k: draw[k] for k in ("bg_tex", "bg_low", "bg_mat", "bg_par")}
+ if draw.get("plate_dz") is not None:
+ kw["plate_dz"] = draw["plate_dz"]
+ if draw.get("part_pose") is not None: # v12 gripper look (RealDR.gripper_look)
+ kw["part_pose"] = draw["part_pose"]
+ return self.render(q, cube_pos, cube_quat, goal_pose, env_pose=draw.get("env_pose"),
+ cam_offset=draw.get("cam_offset"), **kw)
+
+ def render_state(self, state, goal_pose=None, **kw):
+ """Render a :class:`nedm.so101_policy.world.WorldState` (``q``, ``cube_pos``, true ``cube_quat`` w x y z), the
+ same call for the NRD world and the MuJoCo worlds; ``goal_pose`` and ``kw`` as :meth:`render`."""
+ return self.render(state.q, state.cube_pos, state.cube_quat, goal_pose, **kw)
+
+ # ---- EXPERIMENTAL: per-world appearance (domain randomisation) ----------------------------------------------
+ def set_appearance(self, colors=None, light_dir=None, shadows=None, reset: bool = False) -> None:
+ """Per-world colours and light, for robustness training. Reaches into private attributes of the backends.
+
+ ``colors`` [N, geoms, 3] in 0-1, order :attr:`geom_names` (bodies, then statics), or [geoms, 3] for all worlds.
+ Madrona: every geom of every world; flat colour quantised to 8 bits, shading = colour * max(0.2, n . l)
+ (``bvh_raycast.cpp``), so brightness is randomised through the colour. Newton: the bodies only (arm, cube,
+ goal); the statics (base, table) are one shape shared by all worlds.
+ ``light_dir`` [N, 3] (the direction the light travels, world) and ``shadows`` [N] bool: Madrona only (Newton's
+ lights are shared by all worlds). ``reset`` restores the scene's own materials, light and shadows first.
+
+ Madrona copies materials, colours and lights into its scene only in ``init``; the next :meth:`render` re-runs
+ ``init`` with the new values (it re-sorts the entities by world and rebuilds the render state; measured on
+ the RTX 4090 at 16 worlds: 18.6 ms instead of 3.5 ms, no memory growth over 31 re-inits)."""
+ b = self.renderer.backend
+ if self.backend == "newton":
+ if light_dir is not None or shadows is not None:
+ raise NotImplementedError("the Newton backend has one light for all worlds")
+ nb = len(self.scene.body_names)
+ base = torch.tensor([m.color for m in self.scene.scene.bodies], dtype=torch.float32)
+ if reset:
+ self._newton_colors(base.expand(self.num_worlds, nb, 3))
+ if colors is not None:
+ c = torch.as_tensor(colors, dtype=torch.float32).cpu()
+ self._newton_colors(c[..., :nb, :].expand(self.num_worlds, nb, 3))
+ return
+ if reset:
+ from nedm.render.backends.madrona import LIGHT_DIRECTION
+ b._materials.fill_(-1)
+ b._light_dir.copy_(torch.tensor(LIGHT_DIRECTION, device=b.device).expand_as(b._light_dir))
+ b._light_shadow.fill_(self.shadows)
+ if colors is not None:
+ c = (torch.as_tensor(colors, dtype=torch.float32, device=b.device).clamp(0, 1) * 255).round().long()
+ packed = (c[..., 0] << 16) + (c[..., 1] << 8) + c[..., 2]
+ b._colors.copy_(packed.to(torch.uint32).expand_as(b._colors))
+ b._materials.fill_(-2) # MaterialOverride::UseOverrideColor; -1 = the geom's own colour
+ if light_dir is not None:
+ d = torch.as_tensor(light_dir, dtype=torch.float32, device=b.device)
+ b._light_dir.copy_(torch.nn.functional.normalize(d, dim=-1).expand_as(b._light_dir))
+ if shadows is not None:
+ sh = torch.as_tensor(shadows, dtype=torch.bool, device=b.device)
+ b._light_shadow.copy_(sh.expand_as(b._light_shadow))
+ b._started = False # the next render calls init with these values
+
+ def _newton_colors(self, colors: torch.Tensor) -> None:
+ """Body shape colours [N, bodies, 3] of the Newton backend (world-major shapes, then the shared statics)."""
+ model = self.renderer.backend.model
+ n = colors.shape[0] * colors.shape[1]
+ current = model.shape_color.numpy()
+ current[:n] = colors.reshape(n, 3).numpy()
+ model.shape_color.assign(current)
+
+ def base_colors(self) -> torch.Tensor:
+ """The scene's colours [geoms, 3] in 0-1, order :attr:`geom_names`."""
+ return torch.tensor([m.color for m in self.scene.scene.bodies] + [m.color for m, _ in self.scene.scene.statics])
diff --git a/so101_pick_place/code/src/nedm/render/student_view.py b/so101_pick_place/code/src/nedm/render/student_view.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f99a2cd76e47234d9db812a3d2f78386b3e733a
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/student_view.py
@@ -0,0 +1,118 @@
+"""The student's view of a real camera: ONE crop box of the 640 x 480 frame and ONE output size, shared by the
+renderer (``nedm.render.so101.RealScene``: the rays of each output pixel) and the real-robot code
+(``scripts/so101_policy/real2sim/hw/hw_lib.py``: crop + resize of the camera frame).
+
+numpy only (cv2 inside :func:`crop_resize`): the robot's Jetson has no mujoco, newton or warp, and ``hw_lib`` loads
+this file by path (no ``nedm.render`` package import).
+
+Spec layout (``real_scene_v1.json`` / ``calib_v1.json`` key ``"student_view"``), per camera::
+
+ {"crop": [x0, y0, w, h], "out": [W, H], "interp": "area"}
+
+``"crop_xywh"`` is the same as ``"crop"``; ``"crop_xyxy": [x0, y0, x1, y1]`` is also accepted; ``"out_wh"`` is the
+same as ``"out"``. No entry: a centred square of side min(width, height) (the old ``hw_lib`` default).
+
+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,
+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,
+v = y0 + (i + 0.5) h / H - 0.5 (pixel centres at integers, OpenCV). ``cv2.resize(..., INTER_AREA)`` averages over that
+area; the renderer samples it at ``supersample``^2 sub-pixel centres and averages (same centre).
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+WIDTH, HEIGHT = 640, 480 # the real camera frames (LeRobot, both cameras)
+_INTERP = {"area": 3, "linear": 1, "nearest": 0, "cubic": 2} # cv2.INTER_* values
+
+
+@dataclass
+class ViewSpec:
+ """Crop box (x, y, w, h in the camera image) and output size (W, H) of one student camera."""
+ crop_xywh: tuple
+ out_wh: tuple
+ interp: str = "area"
+ source: str = ""
+
+ def __post_init__(self):
+ self.crop_xywh = tuple(int(v) for v in self.crop_xywh)
+ self.out_wh = tuple(int(v) for v in self.out_wh)
+ x, y, w, h = self.crop_xywh
+ if w <= 0 or h <= 0 or x < 0 or y < 0:
+ raise ValueError(f"bad crop {self.crop_xywh}")
+ if self.interp not in _INTERP:
+ raise ValueError(f"interp {self.interp!r}: one of {sorted(_INTERP)}")
+
+ def check_inside(self, width: int = WIDTH, height: int = HEIGHT) -> None:
+ x, y, w, h = self.crop_xywh
+ if x + w > width or y + h > height:
+ raise ValueError(f"crop {self.crop_xywh} outside the {width} x {height} image")
+
+ def to_dict(self) -> dict:
+ return {"crop": list(self.crop_xywh), "out": list(self.out_wh), "interp": self.interp}
+
+
+def centre_square(width=WIDTH, height=HEIGHT, out=224, interp="area") -> ViewSpec:
+ s = min(width, height)
+ return ViewSpec(((width - s) // 2, (height - s) // 2, s, s), (out, out), interp, "centre square (no student_view)")
+
+
+def parse_view(d: dict, out_res: int | None = None, interp: str = "area", source: str = "student_view") -> ViewSpec:
+ """One camera's entry (module docstring) -> ViewSpec. ``out_res``: the default square output if the entry has
+ none."""
+ if "crop" in d:
+ box = d["crop"]
+ elif "crop_xywh" in d:
+ box = d["crop_xywh"]
+ elif "crop_xyxy" in d:
+ x0, y0, x1, y1 = d["crop_xyxy"]
+ box = (x0, y0, x1 - x0, y1 - y0)
+ else:
+ raise ValueError(f"student_view entry {d!r}: needs 'crop', 'crop_xywh' or 'crop_xyxy'")
+ wh = d.get("out", d.get("out_wh"))
+ if wh is None:
+ if out_res is None:
+ raise ValueError(f"student_view entry {d!r}: no 'out' size and no default")
+ wh = (out_res, out_res)
+ return ViewSpec(box, wh, d.get("interp", interp), source)
+
+
+def view_specs(calib, real_cams, out_res, width=WIDTH, height=HEIGHT, interp="area") -> dict:
+ """{camera: ViewSpec} from ``calib["student_view"][camera]`` (``calib``: any dict with that key, e.g. the
+ calibration contract or real_scene_v1.json); cameras without an entry get the centred square."""
+ sv = (calib or {}).get("student_view") or {}
+ out = {}
+ for cam in real_cams:
+ d = sv.get(cam)
+ out[cam] = centre_square(width, height, out_res, interp) if d is None else parse_view(d, out_res, interp)
+ return out
+
+
+def crop_resize(img, spec: ViewSpec, bgr: bool = False) -> np.ndarray:
+ """Camera image uint8 [H, W, 3] (BGR if ``bgr``: cv2 decode; RGB: LeRobot camera with color_mode rgb) -> the
+ student's RGB uint8 [out_h, out_w, 3]: crop box, then resize (cv2, ``spec.interp``)."""
+ import cv2
+ a = np.asarray(img)
+ if a.ndim != 3 or a.shape[2] != 3 or a.dtype != np.uint8:
+ raise ValueError(f"expected uint8 [H, W, 3], got {a.dtype} {a.shape}")
+ x, y, w, h = spec.crop_xywh
+ if y + h > a.shape[0] or x + w > a.shape[1]:
+ raise ValueError(f"crop {spec.crop_xywh} outside the image {a.shape[1]} x {a.shape[0]}")
+ c = a[y:y + h, x:x + w]
+ if bgr:
+ c = c[..., ::-1]
+ if (w, h) != spec.out_wh:
+ c = cv2.resize(np.ascontiguousarray(c), spec.out_wh, interpolation=_INTERP[spec.interp])
+ return np.ascontiguousarray(c)
+
+
+def output_pixel_centres(spec: ViewSpec, supersample: int = 1) -> tuple[np.ndarray, np.ndarray]:
+ """Real-image coordinates (u, v), each (H_out * s, W_out * s) float64, of the (sub-)pixel centres the renderer
+ samples: s x s sub-pixels per output pixel, whose mean is the output pixel centre of the module docstring."""
+ x0, y0, w, h = spec.crop_xywh
+ W, H = spec.out_wh
+ s = int(supersample)
+ u = x0 + (np.arange(W * s) + 0.5) * w / (W * s) - 0.5
+ v = y0 + (np.arange(H * s) + 0.5) * h / (H * s) - 0.5
+ return np.broadcast_to(u[None, :], (H * s, W * s)).copy(), np.broadcast_to(v[:, None], (H * s, W * s)).copy()
diff --git a/so101_pick_place/code/src/nedm/render/urdf.py b/so101_pick_place/code/src/nedm/render/urdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a9380b2f46375811c1aa43aacdc7b63be1c474d
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/urdf.py
@@ -0,0 +1,199 @@
+"""URDF -> link meshes and batched forward kinematics, with no renderer and no simulator.
+
+Only what drawing needs: each link's visual (or collision) geometry as one triangle mesh in
+the link frame, and the joint tree. Forward kinematics is batched torch, so it runs on the
+device the NRD model is on and the result goes to the renderer without leaving it.
+
+Joint coordinates of one world are a row: a floating base first (position, then quaternion
+xyzw) when the model has one, then every movable joint in depth-first order, children in
+file order. That is the order Newton's importer produces for the same file, which keeps
+saved trajectories readable by either renderer.
+"""
+
+from __future__ import annotations
+
+import xml.etree.ElementTree as ET
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+import torch
+
+MOVABLE = ("revolute", "continuous", "prismatic")
+
+
+def _floats(text: str | None, default: tuple[float, ...]) -> np.ndarray:
+ return np.array([float(v) for v in text.split()] if text else default, dtype=np.float64)
+
+
+def _rpy_matrix(rpy: np.ndarray) -> np.ndarray:
+ """URDF fixed-axis roll, pitch, yaw: R = Rz(yaw) Ry(pitch) Rx(roll)."""
+ cr, sr, cp, sp, cy, sy = np.cos(rpy[0]), np.sin(rpy[0]), np.cos(rpy[1]), np.sin(rpy[1]), np.cos(rpy[2]), np.sin(rpy[2])
+ return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
+ [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
+ [-sp, cp * sr, cp * cr]])
+
+
+def _origin(element: ET.Element | None) -> np.ndarray:
+ matrix = np.eye(4)
+ origin = element.find("origin") if element is not None else None
+ if origin is not None:
+ matrix[:3, :3] = _rpy_matrix(_floats(origin.get("rpy"), (0.0, 0.0, 0.0)))
+ matrix[:3, 3] = _floats(origin.get("xyz"), (0.0, 0.0, 0.0))
+ return matrix
+
+
+def _resolve(filename: str, urdf_dir: Path) -> Path:
+ if filename.startswith("package://"):
+ tail = Path(filename[len("package://"):])
+ for up in (urdf_dir, *urdf_dir.parents): # the package root is some ancestor
+ for candidate in (up / tail, up / Path(*tail.parts[1:])):
+ if candidate.is_file():
+ return candidate
+ raise FileNotFoundError(f"cannot find {filename} above {urdf_dir}")
+ path = Path(filename.removeprefix("file://"))
+ return path if path.is_absolute() else (urdf_dir / path).resolve()
+
+
+def _geometry_mesh(geometry: ET.Element, urdf_dir: Path) -> tuple[np.ndarray, np.ndarray]:
+ import trimesh
+ shape = geometry[0]
+ if shape.tag == "mesh":
+ mesh = trimesh.load(str(_resolve(shape.get("filename"), urdf_dir)), force="mesh", process=False)
+ vertices = np.asarray(mesh.vertices, dtype=np.float64) * _floats(shape.get("scale"), (1.0, 1.0, 1.0))
+ return vertices, np.asarray(mesh.faces, dtype=np.int64)
+ if shape.tag == "box":
+ mesh = trimesh.creation.box(extents=_floats(shape.get("size"), (1.0, 1.0, 1.0)))
+ elif shape.tag == "cylinder":
+ mesh = trimesh.creation.cylinder(radius=float(shape.get("radius")), height=float(shape.get("length")), sections=24)
+ elif shape.tag == "sphere":
+ mesh = trimesh.creation.icosphere(subdivisions=2, radius=float(shape.get("radius")))
+ else:
+ raise ValueError(f"unsupported URDF geometry <{shape.tag}>")
+ return np.asarray(mesh.vertices, dtype=np.float64), np.asarray(mesh.faces, dtype=np.int64)
+
+
+@dataclass
+class Link:
+ name: str
+ vertices: np.ndarray | None = None # (V, 3) in the link frame, None if nothing to draw
+ faces: np.ndarray | None = None # (F, 3)
+
+
+@dataclass
+class Joint:
+ name: str
+ kind: str
+ parent: int
+ child: int
+ origin: np.ndarray # (4, 4), child frame in the parent frame at q = 0
+ axis: np.ndarray # (3,), in the child frame
+ coord: int = -1 # index into a joint_q row, -1 if not movable
+
+
+@dataclass
+class UrdfModel:
+ links: list[Link]
+ joints: list[Joint] = field(default_factory=list) # in the order forward kinematics visits them
+ root: int = 0
+ floating: bool = True
+ coord_count: int = 0
+
+ @property
+ def joint_index(self) -> dict[str, int]:
+ index = {"floating_base": 0} if self.floating else {}
+ index.update({j.name: j.coord for j in self.joints if j.coord >= 0})
+ return index
+
+ def forward_kinematics(self, joint_q: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Joint coordinates (N, coord_count) -> every link's world rotation (N, L, 3, 3) and position (N, L, 3)."""
+ n, device = joint_q.shape[0], joint_q.device
+ q = joint_q.float()
+ rotation: list[torch.Tensor | None] = [None] * len(self.links)
+ position: list[torch.Tensor | None] = [None] * len(self.links)
+ if self.floating:
+ x, y, z, w = (q[:, 3 + i] for i in range(4))
+ rotation[self.root] = torch.stack([
+ 1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w),
+ 2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),
+ 2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], dim=-1).reshape(n, 3, 3)
+ position[self.root] = q[:, :3]
+ else:
+ rotation[self.root] = torch.eye(3, device=device).expand(n, 3, 3)
+ position[self.root] = torch.zeros(n, 3, device=device)
+ for joint in self.joints:
+ origin = torch.as_tensor(joint.origin, dtype=torch.float32, device=device)
+ parent_r, parent_p = rotation[joint.parent], position[joint.parent]
+ r = parent_r @ origin[:3, :3]
+ p = parent_p + parent_r @ origin[:3, 3]
+ if joint.coord >= 0:
+ value = q[:, joint.coord]
+ axis = torch.as_tensor(joint.axis, dtype=torch.float32, device=device)
+ if joint.kind == "prismatic":
+ p = p + r @ axis * value[:, None]
+ else:
+ r = r @ _axis_angle(axis, value)
+ rotation[joint.child], position[joint.child] = r, p
+ return torch.stack(rotation, dim=1), torch.stack(position, dim=1)
+
+
+def _axis_angle(axis: torch.Tensor, angle: torch.Tensor) -> torch.Tensor:
+ """Rodrigues: rotation matrices (N, 3, 3) about a fixed unit axis."""
+ x, y, z = axis.tolist()
+ skew = torch.tensor([[0.0, -z, y], [z, 0.0, -x], [-y, x, 0.0]], device=angle.device)
+ eye = torch.eye(3, device=angle.device)
+ s, c = torch.sin(angle)[:, None, None], torch.cos(angle)[:, None, None]
+ return eye + s * skew + (1 - c) * (skew @ skew)
+
+
+def load_urdf(path: str | Path, floating: bool = True, draw: str = "visual") -> UrdfModel:
+ """Parse a URDF. ``draw`` picks which geometry becomes each link's mesh: ``visual`` or ``collision``."""
+ if draw not in ("visual", "collision"):
+ raise ValueError(f"draw must be visual or collision, got {draw!r}")
+ path = Path(path)
+ robot = ET.parse(path).getroot()
+ names = [link.get("name") for link in robot.findall("link")]
+ index = {name: i for i, name in enumerate(names)}
+
+ links = []
+ for element in robot.findall("link"):
+ vertices, faces, offset = [], [], 0
+ for item in element.findall(draw):
+ geometry = item.find("geometry")
+ if geometry is None or len(geometry) == 0:
+ continue
+ v, f = _geometry_mesh(geometry, path.parent)
+ frame = _origin(item) # bake the visual's own offset into the vertices
+ vertices.append(v @ frame[:3, :3].T + frame[:3, 3])
+ faces.append(f + offset)
+ offset += len(v)
+ links.append(Link(element.get("name"), np.concatenate(vertices).astype(np.float32),
+ np.concatenate(faces).astype(np.int32)) if vertices else Link(element.get("name")))
+
+ children: dict[int, list[Joint]] = {}
+ has_parent = set()
+ for element in robot.findall("joint"):
+ axis = _floats(element.find("axis").get("xyz") if element.find("axis") is not None else None, (1.0, 0.0, 0.0))
+ length = np.linalg.norm(axis) # fixed joints are often written with a zero axis
+ joint = Joint(element.get("name"), element.get("type"), index[element.find("parent").get("link")],
+ index[element.find("child").get("link")], _origin(element), axis / length if length > 0 else axis)
+ if joint.kind not in (*MOVABLE, "fixed"):
+ raise ValueError(f"joint {joint.name!r} has unsupported type {joint.kind!r}")
+ if joint.kind in MOVABLE and length == 0:
+ raise ValueError(f"joint {joint.name!r} moves but has a zero axis")
+ children.setdefault(joint.parent, []).append(joint)
+ has_parent.add(joint.child)
+ roots = [i for i in range(len(links)) if i not in has_parent]
+ if len(roots) != 1:
+ raise ValueError(f"expected one root link, found {[names[i] for i in roots]}")
+
+ model = UrdfModel(links, root=roots[0], floating=floating, coord_count=7 if floating else 0)
+ stack = list(reversed(children.get(roots[0], [])))
+ while stack: # depth first, children in file order
+ joint = stack.pop()
+ if joint.kind in MOVABLE:
+ joint.coord = model.coord_count
+ model.coord_count += 1
+ model.joints.append(joint)
+ stack.extend(reversed(children.get(joint.child, [])))
+ return model
diff --git a/so101_pick_place/code/src/nedm/render/video.py b/so101_pick_place/code/src/nedm/render/video.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb420a236495bba523d8c21e1734966c3cebd93d
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/render/video.py
@@ -0,0 +1,50 @@
+"""Collage videos and contact sheets from batches of rendered images."""
+
+from __future__ import annotations
+
+import math
+from pathlib import Path
+
+import numpy as np
+
+
+def grid(tiles: np.ndarray, cols: int) -> np.ndarray:
+ """Tiles (K, H, W, 3) laid out row by row, ``cols`` per row."""
+ k, h, w = tiles.shape[:3]
+ rows = int(math.ceil(k / cols))
+ sheet = np.zeros((rows * h, cols * w, 3), dtype=np.uint8)
+ for i in range(k):
+ sheet[(i // cols) * h:(i // cols + 1) * h, (i % cols) * w:(i % cols + 1) * w] = tiles[i]
+ return sheet
+
+
+def depth_to_gray(depth: np.ndarray, near: float = 0.5, far: float = 6.0) -> np.ndarray:
+ """Depth (..., H, W) -> gray (..., H, W, 3): near is bright, misses are black."""
+ gray = np.where(depth > 0, 255.0 * (1.0 - np.clip(depth, near, far) / far), 0.0).astype(np.uint8)
+ return np.repeat(gray[..., None], 3, axis=-1)
+
+
+def save_sheet(tiles: np.ndarray, path: str | Path, cols: int = 32) -> None:
+ """Every world in one PNG, the evidence that all of them rendered."""
+ from PIL import Image
+ Image.fromarray(grid(tiles, cols)).save(path)
+
+
+class CollageRecorder:
+ """Video of a random sample of worlds, the same sample in every frame."""
+
+ def __init__(self, path: str | Path, num_worlds: int, sample: int = 50, cols: int = 10,
+ fps: float = 50.0, seed: int = 0) -> None:
+ import imageio.v2 as imageio
+ rng = np.random.default_rng(seed)
+ self.pick = np.sort(rng.choice(num_worlds, size=min(sample, num_worlds), replace=False))
+ self.cols = cols
+ self._writer = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=8,
+ macro_block_size=None)
+
+ def add(self, tiles: np.ndarray) -> None:
+ """``tiles`` (N, H, W, 3) uint8 for all worlds. The sample is taken here."""
+ self._writer.append_data(grid(tiles[self.pick], self.cols))
+
+ def close(self) -> None:
+ self._writer.close()
diff --git a/so101_pick_place/code/src/nedm/so101_policy/__init__.py b/so101_pick_place/code/src/nedm/so101_policy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..18538f68091238b92d767475f405eb8748f405e9
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/__init__.py
@@ -0,0 +1 @@
+"""SO101 + cube policies synthesized in the grasp contact NRD (study 2026-10-11). Spec: ~/so101_policy/docs/spec_v1.md."""
diff --git a/so101_pick_place/code/src/nedm/so101_policy/cube_symmetry.py b/so101_pick_place/code/src/nedm/so101_policy/cube_symmetry.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ccd9c75ea8b904a07263513ce74b8cfa422e9a7
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/cube_symmetry.py
@@ -0,0 +1,157 @@
+"""The 24 rotations of a cube, and the canonical relabelling of the cube's orientation for the grasp NRD.
+
+A plain cube looks the same after each of the 24 rotations that map it onto itself (the rotation group of the cube).
+The grasp NRD is not invariant to them: the same physical state with another body-frame labelling gives other
+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
+relabel about the cube z axis, 119 mm after 180 deg). The canonical relabelling below restores the accuracy.
+
+Conventions: quaternions w x y z, unit, world <- body (``q`` turns cube-body vectors into the world frame), float64.
+A relabelling by the group element r gives the orientation q' = q r: the same physical cube, with its body axes
+renamed. Position, world-frame velocity and world-frame spin do not change.
+
+Canonical rule (``~/so101_policy/scripts/critic/symmetry_canon.py``, tested there on 1,984 validation windows): choose
+the r that maximises ||, with Q_REF a flat cube at yaw 45 deg (the middle of the data's 0-90 deg yaw band);
+ties keep the lowest group index (index 0 is the identity). For a flat cube the rule maps any yaw into (0, 90) deg.
+
+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
+group index means the same rotation in both places. Entries are snapped to the exact values 0, +-1/2, +-1/sqrt(2), +-1.
+"""
+from __future__ import annotations
+
+import math
+
+import torch
+
+ORDER = 24
+Q_REF = (math.cos(math.pi / 8), 0.0, 0.0, math.sin(math.pi / 8)) # flat cube, yaw 45 deg
+
+
+def qmul(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
+ """Hamilton product a b of quaternions [..., 4] (w x y z), broadcast."""
+ w1, x1, y1, z1 = a.unbind(-1)
+ w2, x2, y2, z2 = b.unbind(-1)
+ return torch.stack((w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2), -1)
+
+
+def qconj(q: torch.Tensor) -> torch.Tensor:
+ return q * q.new_tensor([1.0, -1.0, -1.0, -1.0])
+
+
+def axis_quat(axis: str, deg: float, dtype=torch.float64, device=None) -> torch.Tensor:
+ """Rotation by deg about the world/body axis "x", "y" or "z" -> [4]."""
+ t = math.radians(deg) / 2
+ v = [0.0, 0.0, 0.0]
+ v["xyz".index(axis)] = math.sin(t)
+ return torch.tensor([math.cos(t)] + v, dtype=dtype, device=device)
+
+
+def _snap(g: torch.Tensor) -> torch.Tensor:
+ vals = torch.tensor([0.0, 0.5, math.sqrt(0.5), 1.0], dtype=torch.float64)
+ a = g.abs()
+ k = (a[..., None] - vals).abs().argmin(-1)
+ if (a - vals[k]).abs().max() > 1e-9:
+ raise AssertionError("cube group entries must be 0, 1/2, 1/sqrt(2) or 1")
+ return torch.sign(g) * vals[k]
+
+
+def _build_group() -> torch.Tensor:
+ """The 24 cube rotations [24, 4] (float64, CPU), in the critic's order; one sign each (the closure's)."""
+ gens = [axis_quat(a, 90) for a in "xyz"]
+ group = [torch.tensor([1.0, 0.0, 0.0, 0.0], dtype=torch.float64)]
+ while True:
+ new = []
+ for g in group:
+ for h in gens:
+ q = qmul(g, h)
+ if all(abs(float((q * x).sum())) < 1 - 1e-9 for x in group + new):
+ new.append(q)
+ if not new:
+ break
+ group += new
+ out = _snap(torch.stack(group))
+ if len(out) != ORDER:
+ raise AssertionError(f"cube group has {len(out)} elements")
+ return out
+
+
+_GROUP = _build_group()
+
+
+def _tables(group):
+ prod = qmul(group[:, None, :], group[None, :, :]) # [24, 24, 4]
+ dots = (prod[:, :, None, :] * group[None, None]).sum(-1) # [24, 24, 24]
+ mul = dots.abs().argmax(-1)
+ if not torch.allclose(dots.abs().amax(-1), torch.ones(ORDER, ORDER, dtype=torch.float64), atol=1e-12):
+ raise AssertionError("cube group is not closed")
+ inv = (mul == 0).to(torch.long).argmax(-1)
+ return mul, inv
+
+
+_MUL, _INV = _tables(_GROUP)
+
+
+def group(dtype=torch.float64, device=None) -> torch.Tensor:
+ """The 24 rotations [24, 4] (w x y z); index 0 = identity."""
+ return _GROUP.to(dtype=dtype, device=device)
+
+
+def mul_table(device=None) -> torch.Tensor:
+ """[24, 24] long: G[i] G[j] = +-G[mul[i, j]]."""
+ return _MUL.to(device)
+
+
+def inverse_table(device=None) -> torch.Tensor:
+ """[24] long: G[i] G[inv[i]] = +-identity."""
+ return _INV.to(device)
+
+
+def score_matrix(q_ref=Q_REF, dtype=torch.float64, device=None) -> torch.Tensor:
+ """[4, 24] M with (q @ M)[k] = for any quaternion q (as = )."""
+ ref = torch.as_tensor(q_ref, dtype=torch.float64)
+ return qmul(ref.expand(ORDER, 4), qconj(_GROUP)).T.contiguous().to(dtype=dtype, device=device)
+
+
+def canonical_index(q: torch.Tensor, scores: torch.Tensor | None = None, margin: float = 0.0) -> torch.Tensor:
+ """q [..., 4] -> [...] long: the group index k of the canonical relabelling q G[k] (argmax ||, ties
+ to the lowest index). margin > 0 adds hysteresis: keep the identity (0) unless another element scores more than
+ margin above it. scores: score_matrix() on q's device (pass it to avoid a host-to-device copy per call)."""
+ m = score_matrix(dtype=q.dtype, device=q.device) if scores is None else scores
+ s = (q @ m).abs()
+ k = s.argmax(-1)
+ if margin > 0:
+ k = torch.where(s.amax(-1) > s[..., 0] + margin, k, torch.zeros_like(k))
+ return k
+
+
+def relabel(q: torch.Tensor, k: torch.Tensor, g: torch.Tensor | None = None, newest_sign: bool = True) -> torch.Tensor:
+ """q [B, ..., 4] relabelled by G[k] (k [B] long, one element per world for all its entries) -> q G[k]. With
+ newest_sign, every entry of a world is multiplied by the sign that makes w >= 0 in its last entry along dim -2
+ (q [B, K, 4]: one sign per history, so differences stay continuous); without, the sign is left as the product
+ gives it."""
+ gg = (group(q.dtype, q.device) if g is None else g)[k]
+ gg = gg.view(gg.shape[0], *([1] * (q.dim() - 2)), 4)
+ out = qmul(q, gg)
+ if newest_sign:
+ ref = out[:, -1:, :1] if q.dim() >= 3 else out[:, :1]
+ out = out * torch.where(ref < 0, -1.0, 1.0).to(out.dtype)
+ return out
+
+
+def canonicalise(q: torch.Tensor, margin: float = 0.0) -> tuple[torch.Tensor, torch.Tensor]:
+ """q [B, 4] -> (canonical q G[k] with w >= 0 [B, 4], k [B])."""
+ k = canonical_index(q, margin=margin)
+ return relabel(q, k), k
+
+
+def true_from_canonical(q_canon: torch.Tensor, c: torch.Tensor, g: torch.Tensor | None = None) -> torch.Tensor:
+ """The true orientation q_canon conj(G[c]) [B, 4] of a canonical one, with c [B] the cumulative relabelling
+ (q_canon = q_true G[c] up to sign). The sign is the product's; align it with a previous value if needed."""
+ gg = (group(q_canon.dtype, q_canon.device) if g is None else g)[c]
+ return qmul(q_canon, qconj(gg))
+
+
+def yaw_of_flat(q: torch.Tensor) -> torch.Tensor:
+ """Yaw (rad) of the body x axis projected on the world xy plane, for orientations q [..., 4]."""
+ w, x, y, z = q.unbind(-1)
+ return torch.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
diff --git a/so101_pick_place/code/src/nedm/so101_policy/decoder.py b/so101_pick_place/code/src/nedm/so101_policy/decoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a72db7a894c23e8fb015bc5155f6871260653ee
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/decoder.py
@@ -0,0 +1,1406 @@
+"""Policy action -> 6 absolute joint targets inside the scripted command family of the grasp NRD data.
+
+The grasp NRD is accurate only on the collector's commands (critic 3.5; review_spec_feasibility sec. 3): top-down
+gripper, straight grasp-point lines with minimum-jerk timing, the arm still while the jaw moves, a firm jaw command
+to grip and an open command, per-joint command steps and accelerations at the data's p99. ``DecoderV2`` (spec_v2 B1,
+review_spec_feasibility P0-1..3) is the study's action design; ``DecoderV1`` (spec_v1 2.4: per-step velocity, binary
+jaw) stays for the ablation. Frames: world = arm base (z up, table top z = 0), metres, radians; TCP = the collector's
+grasp point (``kin.GRASP_POINT``); yaw = direction of the gripper closing axis (``kin.yaw_of``).
+
+DecoderV2
+---------
+Action a [B, 6] in [-1, 1], read by ``decide`` once per decision (``decision_steps`` = 5 control steps = 0.1 s):
+
+ a[0:3] TCP target displacement over the decision, world frame, x d_max = 35 mm (norm clipped to d_max)
+ a[3] yaw change of the closing axis over the decision, x dyaw_max = 0.2 rad
+ a[4] trigger: > 0 starts GRASP (mode free, jaw open) or PLACE (mode hold) if the trigger is armed; while GRASP
+ has not started to close the jaw, a[4] <= 0 at a decision aborts it (the policy holds the trigger through
+ the descent). A macro start disarms the trigger; a decision with a[4] <= 0 arms it again, so a trigger
+ held through a GRASP cannot start a PLACE right after the lift (``armed``, in the observation)
+ a[5] GRASP lift height, read at the trigger: h = 3 + 9 (a[5] + 1) / 2 cm
+ a[6] only with ``abort_action`` (PPO options below): the explicit abort of a GRASP / CARRY line (> 0)
+
+Modes (``MODES``): ``free`` (jaw open, free motion) -GRASP-> g_brake, g_descend, g_settle, g_close, g_grip, g_lift ->
+``hold`` (jaw closed, free motion with the held-cube rules) -PLACE-> p_brake, p_settle, p_lower, p_open, p_retreat ->
+``free``. Decisions inside a macro are ignored except the GRASP abort (no exploration noise inside a macro).
+
+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
+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:
+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
+rad/s^2); then the change is scaled down (one factor) so that the joint rates of the blend (Jacobian map at the last
+IK solution) keep every joint's peak step <= dq_max and step change <= ddq_max. Then, wall by wall, the velocity
+toward a wall at distance D is capped so that the target can still stop before it (D = (v_wall + v) T_d / 2 +
+v^2 / (2 a), a = ``wall_margin`` x the joint-limited deceleration along the wall normal; walls: TCP z floor
+(``low_min`` + the lowest-point offset of the last IK solution) and ceiling (``z_max`` = 0.15 m; in mode hold also
+cube bottom <= 12 cm), radius about the pan axis ``r_range``, pan angle ``angle_max``; yaw: the hold turn cap and the
+wrist roll range); walls win. A target outside a radius / angle / ceiling bound (a start pose) only cannot move
+farther out. The target then follows the push-T cosine velocity blend (``blend``; so101_planar_decoder): from
+the current velocity to v_new over T_d, then constant until the next decision. Yaw rules (P0-3): in mode free, with the
+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
+are within ``yaw_free_gap`` = 2 cm (+ the target's travel in one decision) of the cube; in mode hold the gripper yaw
+stays within ``hold_turn_max`` = 0.6 rad of its yaw at the end of the GRASP lift.
+
+Macros (copied from the collector's ``Plan.cart`` / ``Plan.jaw`` / ``grasp_approach`` / ``carry_and_place``; every
+duration drawn uniformly from the collector's range by a counter-based hash of (world seed, draw counter), so a world
+is reproducible on any device and in any batch; a line's duration is then raised, if needed, to keep its minimum-jerk
+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
+that a joint cannot follow):
+
+ GRASP: g_brake cosine blend of the target velocity and yaw rate to 0 in max(T_d, pi |v| / (2 a_max),
+ pi |w| / (2 alpha_max)) (skipped at rest)
+ 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
+ g_settle hold U(0, 0.15) s (nominal's "descend" hold)
+ 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
+ g_grip hold U(0.1, 0.25) s
+ g_lift vertical line up by h (policy; capped: TCP z <= z_max, cube bottom <= 12 cm), U(0.35, 0.8) s
+ PLACE: p_brake as g_brake
+ p_settle hold U(0.1, 0.3) s (carry_and_place hold2)
+ p_lower vertical line to the TCP height that puts the lowest cube corner (cube state at the trigger)
+ U(0, 3) mm above the table, U(0.35, 0.7) s
+ p_open jaw to 0.7 rad in max(U(0.15, 0.35) s, 1.875 |dtheta| / 4.5 rad/s), arm still
+ 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
+ 4 cm retreat leaves the TCP 25-30 mm above the cube top, below the success rule's 3 cm)
+
+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.
+The GRASP trigger is ignored while the jaw is still opening (after a reset); the descent's (x, y, z, yaw) end is
+``macro_goal`` (for the task's grasp-box rule at the trigger).
+
+Per control step (``step``): the target increment of the mode (blend, minimum-jerk line, or none), the workspace clip
+(free motion), the start tilt blended out over ``tilt_s`` = 0.6 s (data start poses tilt up to 60 deg), IK
+(``SO101Kin.ik_track``, warm-started, top-down where reachable, the collector's tilt fallback above it), then:
+
+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
+ 0.0423, wrist flex 0.0475, wrist roll 0.0409 rad), the TCP and yaw step are scaled down to fit (free motion: the
+ lost part is not caught up; macros: the line's clock slows, so the line keeps its shape and end).
+2. Floor: if the lowest gripper / moving-jaw collision point of the IK solution (``SO101Kin.lowest_point``, fast set)
+ 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
+ [measured, commanded, scheduled end] with the deepest moving jaw (about 0.17 rad, 14.2 mm below the TCP top-down).
+3. Command limiter per arm joint: the command c follows the IK solution with |dc| <= dq_max and |d2c| <= ddq_max
+ (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
+ of the collector phase it copies, ``ddq_line``: the collector's lifts and retreats reach 0.028-0.046 rad), braking-
+ aware (the lag behind a target that moves at its own speed closes without overshoot), stopping before the joint
+ limits; inactive when the IK solution itself is within the bounds.
+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
+ rad); the band wins over the acceleration bound. Then the collector's target range (``kin.TLO`` .. ``kin.THI``).
+5. Jaw: minimum-jerk schedule (Plan.jaw rule), steps clipped to 0.09 rad.
+
+Same code on CPU and GPU (all state per world, [B, ...] float64 tensors; a few ``.any()`` checks skip work). Flags
+per step in ``info`` and summed per world in ``counts``. ``macro()`` gives the task's macro phase codes (``MACROS``).
+
+Ablation option ``blend="filter"``: the decision's velocity is the set point of a critically damped 2nd-order filter
+(natural frequency ``wn`` = 12.5 rad/s, the v1 filter) instead of the cosine blend: the acceleration is continuous
+across decisions (a cosine blend returns the acceleration to 0 at every decision boundary, a 10 Hz ripple while the
+target accelerates); the brake ends when the filter has stopped. Measured 2026-10-11 (64 tasks, FSM expert): MuJoCo
+63/64, NRD s61 48/64 against 64/64 and 46/64 with the cosine blend: no clear gain (build2_kin_decoder_expert.md).
+
+Option b1, ``blend="hann"`` (build3_fixes.md): every decision starts one more blend of the target velocity, the change
+of the set point (u_k - u_{k-1}) spread over 2 T_d with a Hann (raised-cosine) acceleration window; the blends of
+consecutive decisions overlap by half and their windows sum to a constant, so equal set-point changes give a constant
+acceleration (no ripple at the decision rate) and the acceleration is continuous. Peak acceleration of a decision's
+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
+(the response lags the set point). The GRASP / PLACE brake is one more Hann blend to 0 of length max(2 T_d,
+2 |u| / a_max, 2 |w| / alpha_max, joint bound); ``macro_goal`` is its exact rest point. ``rest_terms()`` gives the
+linear rest-point model the expert plans with (cosine: pos + T_d v + v0 T_d / 2).
+
+Option b2, ``carry_macro=True`` (build3_fixes.md): in mode hold there is no free motion. A decision at rest gives a
+CARRY target: TCP xy + a[0:2] ``carry_reach`` (norm clipped; relative to the current target), the same height, yaw +
+a[3] ``hold_turn_max`` (within the hold turn cap and the wrist roll range); radius / pan-angle bounds as free motion,
+and a straight line that would pass inside the inner radius ends where it would cross it (``carry_target``). A target
+within ``carry_min_d`` / ``carry_min_yaw`` of the current one is no move. The line copies the collector's
+carry_and_place 'move' (Plan.cart): straight TCP line, minimum-jerk timing, the yaw turning with the same timing,
+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 =
+the collector's 3 rad/s); the command limiter uses ``dq_carry`` / ``ddq_carry`` on the line. Decisions during the line
+are ignored (also PLACE), except a[5] > ``carry_abort_thr``: a cosine brake of the target to rest, after which the next
+decision may carry again (re-targeting only from rest). PLACE starts from rest as before. Counts: ``carries``,
+``carry_aborts``.
+
+Macro-duration seeds (review F5): ``reset`` without ``seed`` gives each world a fresh stream per episode (the first
+episode of a world keeps the earlier default base_seed * 1,000,003 + world index); a trainer may pass its own episode
+seeds, a paired evaluation passes the task seed.
+
+Trigger arming (review_code_v2 R5, 2026-10-11): a decision re-arms the trigger (a[4] <= trigger_thr) only where it
+reads a[4]: mode free (also right after an abort), mode hold, and the GRASP descent before the close (the abort,
+without ``grasp_latch``); inside the other macro phases a[4] is not read at all. The FSM expert's episodes are
+bit-identical to the earlier rule (it holds a[4] = +1 through a GRASP and never triggers at the first decision after a
+PLACE; checked on the 1,024 gate tasks, build4_ppo2.md).
+
+PPO options (all off by default; build4_ppo2.md; the same in every world):
+
+- ``grasp_gate``: GRASP precondition. A GRASP trigger is ignored (no macro, no cost; counted as ``trigger_ignored``
+ and ``gate_blocked``, the trigger stays armed) unless the descent end it would set (``brake_stop`` = ``macro_goal``
+ x, y, yaw of a GRASP started now, every blend) has the cube centre within ``gate_box`` in that pose's yaw frame
+ (|x| along the closing axis, |y| along the jaw width, |cube yaw - gripper yaw| mod 90) and the descent end height
+ within ``gate_z`` of the cube centre for the whole range of its random 0-2 mm (``grasp_dz``). Default box 4.5 mm /
+ 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
+ harness's noisy triggers (gate_expert.md sec. 5).
+- ``grasp_latch``: a started GRASP runs to the lift; a[4] is not read in g_brake / g_descend / g_settle. With
+ ``abort_action`` the explicit abort a[6] > ``abort_act_thr`` there aborts it (as a[4] <= 0 did); else no abort.
+- ``abort_action``: the action has 7 columns; a[6] is a separate abort output (review_code_v2 R3: the CARRY abort
+ shared the lift-height output a[5] and its exploration noise). It aborts a running CARRY line (option b2; a[5] is
+ then not read there) and, with ``grasp_latch``, a pre-close GRASP. A 6-column action (e.g. the FSM expert) keeps
+ a[5] as the CARRY abort and has no GRASP abort under ``grasp_latch``.
+"""
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+
+import torch
+
+from nedm.so101_policy.kin import PAN_AXIS_XY, SO101Kin, quat_mat, rotvec, rotz, wrap, yaw_of
+
+CONTROL_DT = 0.02
+CUBE_HALF = 0.015
+CUBE_REST_Z = 0.014993 # resting cube centre height in the data (m)
+MODES = ("free", "g_brake", "g_descend", "g_settle", "g_close", "g_grip", "g_lift", "hold", "p_brake", "p_settle",
+ "p_lower", "p_open", "p_retreat")
+M = {n: k for k, n in enumerate(MODES)}
+GRASP_PRE_CLOSE = (M["g_brake"], M["g_descend"], M["g_settle"])
+# macro phases of the task rules (task.MACROS, same names and order) for each decoder mode
+MACROS = ("free", "grasp_descend", "grasp_close", "grasp_grip", "grasp_lift", "place_lower", "place_open",
+ "place_retreat")
+MACRO_OF_MODE = ("free", "grasp_descend", "grasp_descend", "grasp_descend", "grasp_close", "grasp_grip", "grasp_lift",
+ "free", "place_lower", "place_lower", "place_lower", "place_open", "place_retreat")
+ACTION_DIM = 6
+FLAGS = ("guard_scaled", "limited", "lead_clipped", "floor_raised", "floor_override", "range_clipped", "ws_clipped",
+ "yaw_blocked", "yaw_capped", "trigger_ignored", "aborted", "carries", "carry_aborts", "gate_blocked")
+
+
+def minjerk(s):
+ s = s.clamp(0.0, 1.0)
+ return s * s * s * (10 - 15 * s + 6 * s * s)
+
+
+def expmap(v):
+ """Rotation vectors [..., 3] -> rotation matrices (Rodrigues)."""
+ th = v.norm(dim=-1, keepdim=True)[..., None]
+ k = v / v.norm(dim=-1, keepdim=True).clamp_min(1e-300)
+ z = torch.zeros_like(k[..., 0])
+ kx = torch.stack((z, -k[..., 2], k[..., 1], k[..., 2], z, -k[..., 0], -k[..., 1], k[..., 0], z), -1).reshape(*v.shape, 3)
+ eye = torch.eye(3, dtype=v.dtype, device=v.device).expand(*v.shape[:-1], 3, 3)
+ return eye + torch.sin(th) * kx + (1 - torch.cos(th)) * (kx @ kx)
+
+
+def blend(v0, vn, tau, td):
+ """Cosine velocity blend from v0 to vn over td (s), closed form (push-T so101_planar_decoder.blend, per-world td).
+ v0, vn [B] or [B, 3]; tau, td [B] (s). -> (displacement since the blend start, velocity at tau)."""
+ if v0.dim() == 2:
+ tau, td = tau[:, None], td[:, None]
+ tdp = td.clamp_min(1e-12)
+ x = torch.minimum(tau, td)
+ p = v0 * x + (vn - v0) * (x / 2 - tdp / (2 * math.pi) * torch.sin(math.pi * x / tdp)) + vn * (tau - x)
+ v = torch.where(tau >= td, vn, v0 + (vn - v0) * (1 - torch.cos(math.pi * x / tdp)) / 2)
+ return p, v
+
+
+def hann_P(x):
+ """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)
+ on [0, 1] (S = 1 after): the displacement of a unit Hann velocity increment of length 1 (option b1)."""
+ xc = x.clamp(0.0, 1.0)
+ return xc * xc / 2 + (torch.cos(2 * math.pi * xc) - 1) / (4 * math.pi * math.pi) + (x - 1).clamp_min(0)
+
+
+def hann_R(x):
+ """Integral from x to 1 of (1 - S): the displacement still missing (against a velocity step) of a unit Hann
+ increment at clock x (units of its length; 0 for x >= 1)."""
+ xc = x.clamp(0.0, 1.0)
+ return 0.5 - xc + hann_P(xc)
+
+
+def filter_step(x, xd, u, wn, dt=CONTROL_DT):
+ """Critically damped 2nd-order filter x'' = wn^2 (u - x) - 2 wn x', input u held over one step of dt (exact).
+ -> (x, x', integral of x over the step)."""
+ E = math.exp(-wn * dt)
+ e0 = x - u
+ x1 = u + E * (e0 * (1 + wn * dt) + xd * dt)
+ xd1 = E * (xd * (1 - wn * dt) - e0 * wn * wn * dt)
+ disp = u * dt + e0 * (2 - E * (2 + wn * dt)) / wn + xd * (1 - E * (1 + wn * dt)) / (wn * wn)
+ return x1, xd1, disp
+
+
+_M32 = 0xFFFFFFFF
+EPISODE_MIX = 0x5851F42D # default macro-duration seed step per reset of a world (DecoderV2.reset, review F5)
+
+
+def _mul32(x, c):
+ """(x * c) mod 2^32 for int64 tensors x in [0, 2^32) and a constant c < 2^32, without int64 overflow."""
+ return ((((x >> 16) * c) & 0xFFFF) * 65536 + (x & 0xFFFF) * c) & _M32
+
+
+def hash_uniform(seed, counter, stream=0):
+ """Counter-based uniform [0, 1) numbers (lowbias32 hash of seed, counter, stream; int64 tensors): the same values on
+ every device and batch layout."""
+ x = (seed & _M32) ^ ((counter * 0x9E3779B1 + stream * 0x85EBCA77 + 0x165667B1) & _M32)
+ for _ in range(2):
+ x = x ^ (x >> 16)
+ x = _mul32(x, 0x7FEB352D)
+ x = x ^ (x >> 15)
+ x = _mul32(x, 0x846CA68B)
+ x = x ^ (x >> 16)
+ return x.to(torch.float64) / 4294967296.0
+
+
+@dataclass
+class DecoderV2Config:
+ decision_steps: int = 5
+ d_max: float = 0.035 # m per decision (0.35 m/s)
+ dyaw_max: float = 0.2 # rad per decision (2 rad/s)
+ a_max: float = 1.5 # m/s^2, TCP target acceleration (free motion)
+ alpha_max: float = 6.0 # rad/s^2, yaw acceleration (free motion)
+ wall_margin: float = 0.5 # walls brake at this fraction of the estimated joint-limited deceleration
+ dq_max: tuple = (0.0347, 0.0347, 0.0423, 0.0475, 0.0409) # rad per 20 ms, data p99 (RF P0-2)
+ ddq_max: tuple = (0.0028, 0.0069, 0.0087, 0.0095, 0.0034) # rad per 20 ms^2, data p99
+ # macro lines: the larger of ddq_max and the data's p99 in the collector phase the line copies (val_only task
+ # families: descend, lift, lower, retreat; runs/kin_decoder_expert/v2/data_cmd_stats.json)
+ ddq_line: dict = field(default_factory=lambda: dict(
+ g_descend=(0.0028, 0.0071, 0.0101, 0.0112, 0.0034), g_lift=(0.0028, 0.0278, 0.0392, 0.0302, 0.0040),
+ p_lower=(0.0028, 0.0070, 0.0087, 0.0095, 0.0034), p_retreat=(0.0028, 0.0311, 0.0460, 0.0351, 0.0053)))
+ lead: tuple = (0.0445, 0.1235, 0.0552, 0.0559, 0.0476) # rad, |cmd - q| data p99.9
+ r_range: tuple = (0.12, 0.30) # m, TCP radius about the pan axis (free motion)
+ angle_max: float = math.radians(85) # rad, |pan angle| of the TCP
+ z_max: float = 0.15 # m, TCP height in free motion (spec <= 0.20; above about 0.15 m the IK
+ # needs tilts of 30-50 deg and tracks badly; starts above stay there)
+ low_min: float = 0.0015 # m, lowest collision point of the IK solution
+ roll_max: float = 2.5 # rad, |yaw - pan angle| (wrist roll range)
+ cube_bottom_max: float = 0.12 # m, lowest cube corner while held
+ yaw_free_gap: float = 0.02 # m, yaw lock distance jaws-cube (free mode)
+ cube_on_table: float = 0.005 # m, lowest cube corner below this = on the table (yaw lock)
+ hold_turn_max: float = 0.6 # rad, gripper yaw change while holding
+ jaw_open: float = 0.7
+ jaw_closed: float = 0.0
+ jaw_speed: float = 4.5 # rad/s, Plan.jaw
+ jaw_min_s: float = 0.2 # s, jaw move after a reset
+ jaw_step: float = 0.09 # rad per step
+ lift_range: tuple = (0.03, 0.12) # m, GRASP lift (a[5])
+ v_macro: float = 0.35 # m/s, peak speed of a macro line
+ a_macro: float = 2.5 # m/s^2, peak acceleration of a macro line
+ line_margin: float = 1.1 # joint-feasible macro line duration x this
+ t_descend: tuple = (0.25, 0.5) # s, grasp_approach
+ grasp_dz: tuple = (0.0, 0.002) # m above the cube centre, fam_nominal
+ t_settle: tuple = (0.0, 0.15) # s, fam_nominal
+ t_close: tuple = (0.2, 0.4)
+ t_grip: tuple = (0.1, 0.25)
+ t_lift: tuple = (0.35, 0.8)
+ t_place_settle: tuple = (0.1, 0.3)
+ t_lower: tuple = (0.35, 0.7)
+ place_dz: tuple = (0.0, 0.003) # m, lowest cube corner above the table
+ t_open: tuple = (0.15, 0.35)
+ retreat: tuple = (0.05, 0.10) # m (collector 4-10 cm; >= 5 cm so the TCP ends >= 3 cm above the cube top)
+ t_retreat: tuple = (0.25, 0.5)
+ trigger_thr: float = 0.0
+ abort_thr: float = 0.0
+ blend: str = "cosine" # "cosine" (spec_v2 B1, push-T) | "filter" (ablation: the decision's velocity
+ wn: float = 12.5 # is the set point of a critically damped 2nd-order filter, natural freq.)
+ # | "hann" (option b1: overlap-added Hann velocity blends, 2 decisions long)
+ tilt_s: float = 0.6
+ ik_iters: int = 3
+ # option b2: CARRY macro in mode hold (module docstring, "CARRY macro"); False = free motion while holding
+ carry_macro: bool = False
+ carry_reach: float = 0.32 # m, |a[0:2]| = 1 -> this horizontal displacement of the TCP target
+ carry_t: tuple = (0.5, 0.9) # s, collector carry_and_place move_s, then x 1.3 until the peak joint step
+ carry_arm_step: float = 0.06 # <= this (rad per 20 ms; the collector's Plan.cart, arm_max 3 rad/s)
+ carry_min_d: float = 0.001 # m, a smaller carry displacement (and yaw change below carry_min_yaw) is no
+ carry_min_yaw: float = math.radians(0.5) # move (dead band; below the expert's 1.5 mm / 1 deg PLACE tolerance)
+ carry_abort_thr: float = 0.5 # a[5] above this during a CARRY line brakes it to rest (cosine brake, as a
+ # macro start); the next carry starts from there (re-target from rest)
+ # command limiter on a carry line: steps <= the collector's arm_max step, step changes <= the larger of ddq_max and
+ # 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 /
+ # 0.057 / 0.018 / 0.059 rad, max 0.060; d2 p99.9 below; ~/so101_policy/docs/build3_fixes.md)
+ dq_carry: tuple = (0.06, 0.06, 0.06, 0.06, 0.06)
+ ddq_carry: tuple = (0.0061, 0.0109, 0.0148, 0.0095, 0.0301)
+ # PPO options (module docstring, "PPO options"; build4_ppo2.md); all off = the gate's decoder
+ grasp_gate: bool = False # GRASP precondition: a trigger whose descent end puts the cube outside
+ gate_box: tuple = (0.0045, 0.010, math.radians(2.5)) # (|x| closing axis m, |y| m, |yaw mod 90| rad) is ignored
+ gate_z: tuple = (-0.0125, 0.0015) # m, cube centre z minus the descent end z (the task's box_z)
+ grasp_latch: bool = False # a started GRASP is not aborted by a[4] (a[4] unread in g_brake..g_settle)
+ abort_action: bool = False # action a[6] (7 columns): > abort_act_thr aborts a pre-close GRASP (with
+ abort_act_thr: float = 0.0 # grasp_latch) and a running CARRY line (instead of a[5] > carry_abort_thr)
+
+
+class DecoderV2:
+ """Batched decoder v2 (module docstring) for B worlds on one device. Per decision ``decide(a, state)``, then
+ ``decision_steps`` x ``step(q_measured)`` -> (joint targets [B, 6] rad, info)."""
+
+ def __init__(self, num_envs, device="cpu", kin: SO101Kin | None = None, cfg: DecoderV2Config | None = None,
+ seed: int = 0):
+ self.cfg = c = cfg or DecoderV2Config()
+ self.dev = torch.device(device)
+ self.kin = kin or SO101Kin(self.dev)
+ self.B = B = int(num_envs)
+ self.base_seed = int(seed)
+ f = dict(dtype=torch.float64, device=self.dev)
+ z = lambda *s: torch.zeros(*s, **f)
+ self.f = f
+ self.T_d = c.decision_steps * CONTROL_DT
+ self.dq_max, self.ddq_max = torch.tensor(c.dq_max, **f), torch.tensor(c.ddq_max, **f)
+ self.ddq_mode = self.ddq_max.expand(len(MODES), 5).clone() # step-change bound per mode
+ for name, v in c.ddq_line.items():
+ self.ddq_mode[M[name]] = torch.tensor(v, **f)
+ self.lead_band = torch.tensor(c.lead, **f)
+ self.pan_axis = torch.tensor(PAN_AXIS_XY, **f)
+ self.mode = torch.zeros(B, dtype=torch.long, device=self.dev)
+ self.pos, self.yaw = z(B, 3), z(B) # Cartesian target: TCP (world, m), closing-axis yaw
+ self.vel, self.yrate = z(B, 3), z(B) # last target step / dt (m/s, rad/s)
+ self.v0, self.vn, self.w0, self.wn = z(B, 3), z(B, 3), z(B), z(B) # active cosine blend
+ self.tau, self.tb = z(B), torch.full((B,), self.T_d, **f) # blend clock and length (s)
+ self.fv, self.fa, self.fw, self.fwa = z(B, 3), z(B, 3), z(B), z(B) # blend "filter": velocity, its rate
+ if c.blend not in ("cosine", "filter", "hann"):
+ raise ValueError(f"blend {c.blend!r}: 'cosine', 'filter' or 'hann'")
+ self.filt, self.hann = c.blend == "filter", c.blend == "hann"
+ # peak acceleration of a blend per unit velocity change (1/s): cosine pi / (2 T_d), filter wn / e, hann 1 / T_d
+ # (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)
+ 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))
+ self.dv_max, self.dw_max = c.a_max / self.k_peak, c.alpha_max / self.k_peak
+ self.lp0, self.lp1, self.lk, self.ln = z(B, 3), z(B, 3), z(B), z(B) # macro line / hold: ends, clock, length
+ self.jaw_from, self.jaw_to, self.jaw_k, self.jaw_n = z(B), z(B), z(B), torch.ones(B, **f)
+ self.q_des, self.q_cmd, self.dq = z(B, 5), z(B, 6), z(B, 5) # IK solution, command, last arm step
+ self.low_off = torch.full((B,), 0.0143, **f) # TCP z minus lowest collision point (m), last solution
+ self.z_goal, self.h = z(B), z(B) # macro line end height (m), GRASP lift (m)
+ self.z_ceil = torch.full((B,), c.z_max, **f) # TCP ceiling while holding (m)
+ self.yaw_hold0 = z(B)
+ self.goal = z(B, 4) # GRASP descent end (x, y, z, yaw)
+ self.tilt0, self.t = z(B, 3), z(B)
+ self.seed = torch.arange(B, dtype=torch.long, device=self.dev)
+ self.draws = torch.zeros(B, dtype=torch.long, device=self.dev)
+ self.episode = torch.zeros(B, dtype=torch.long, device=self.dev) # resets per world (default seed stream)
+ # "hann" blend state: velocity of the finished blends, then two running blends A (older) and B (newest):
+ # increment (m/s, rad/s), length T (s) and clock tau (s)
+ self.hv, self.hw = z(B, 3), z(B)
+ 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)
+ 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)
+ # CARRY macro (option b2): active flag and the line's yaw ends
+ self.carry_on = torch.zeros(B, dtype=torch.bool, device=self.dev)
+ self.carry_brk = torch.zeros(B, dtype=torch.bool, device=self.dev) # an aborted CARRY brakes to rest
+ self.ly0, self.ly1 = z(B), z(B)
+ self.dq_carry, self.ddq_carry = torch.tensor(c.dq_carry, **f), torch.tensor(c.ddq_carry, **f)
+ self.ik_err = z(B, 2)
+ self.armed = torch.ones(B, dtype=torch.bool, device=self.dev) # a trigger can start a macro
+ self.counts = {k: torch.zeros(B, dtype=torch.long, device=self.dev) for k in FLAGS}
+ self.theta_worst = self._worst_jaw()
+
+ # ---- helpers ------------------------------------------------------------------------------------------------
+ def _ids(self, idx):
+ if idx is None:
+ return torch.arange(self.B, device=self.dev)
+ idx = torch.as_tensor(idx, device=self.dev)
+ return idx.nonzero().flatten() if idx.dtype == torch.bool else idx.long().flatten()
+
+ def _worst_jaw(self):
+ """Jaw angle (rad, within the target range up to 0.6) with the deepest moving jaw below the TCP, top-down."""
+ th = torch.linspace(float(self.kin.tlo[5]), 0.6, 241, **self.f)
+ q, _, _, _ = self.kin.ik_topdown(None, torch.tensor([[0.25, 0.0, 0.05]], **self.f).expand(len(th), 3),
+ torch.zeros(len(th), **self.f))
+ low = self.kin.lowest_point(torch.cat((q, th[:, None]), -1), per_body=True)[:, 1]
+ return float(th[low.argmin()])
+
+ def _draw(self, mask, rng):
+ u = hash_uniform(self.seed, self.draws)
+ self.draws = self.draws + mask.long()
+ return rng[0] + (rng[1] - rng[0]) * u
+
+ def _line_steps(self, t_draw, end, mode, samples=8, yaw_end=None, dq=None, ddq=None):
+ """Steps of a minimum-jerk TCP line from the target to end [B, 3]: the drawn duration, raised to keep the peak
+ TCP speed <= v_macro and acceleration <= a_macro, and every joint's peak step <= dq_max and peak step change
+ <= ddq_max. The joint path q(u) comes from warm-started IK at ``samples`` points of the line; with u(t) minimum
+ jerk (|u'| <= 1.875 / T, |u''| <= 5.77 / T^2): T >= 1.875 max|q'| / dq_max and
+ 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
+ with the same timing (CARRY line); dq, ddq [5]: other joint bounds (default dq_max and the mode's bound)."""
+ c = self.cfg
+ dist = (end - self.pos).norm(dim=-1)
+ t = torch.maximum(t_draw, torch.maximum(1.875 * dist / c.v_macro, torch.sqrt(5.7735 * dist / c.a_macro)))
+ rot = self._rot(self.yaw)
+ qs, q = [self.q_des], self.q_des
+ for k in range(1, samples + 1):
+ if yaw_end is not None:
+ rot = self._rot(self.yaw + (yaw_end - self.yaw) * (k / samples))
+ q, _, _ = self.kin.ik_track(q, self.pos + (end - self.pos) * (k / samples), rot, 2 * c.ik_iters)
+ qs.append(q)
+ qs = torch.stack(qs, 1) # [B, K + 1, 5]
+ d1 = qs.diff(dim=1).abs().amax(1) * samples # max |dq/du|
+ d2 = qs.diff(n=2, dim=1).abs().amax(1) * samples * samples # max |d2q/du2|
+ A = self.ddq_mode[M[mode]] if ddq is None else ddq
+ dqm = self.dq_max if dq is None else dq
+ steps = torch.maximum(1.875 * d1 / dqm, torch.sqrt((3.516 * d2 + 5.7735 * d1) / A)).amax(-1)
+ t = torch.maximum(t, c.line_margin * steps * CONTROL_DT)
+ return torch.round(t / CONTROL_DT).clamp_min(1)
+
+ def _jaw_move(self, mask, goal, t_draw):
+ jaw = self.q_cmd[:, 5]
+ n = torch.round(torch.maximum(t_draw, 1.875 * (goal - jaw).abs() / self.cfg.jaw_speed) / CONTROL_DT).clamp_min(1)
+ self.jaw_from = torch.where(mask, jaw, self.jaw_from)
+ self.jaw_to = torch.where(mask, goal, self.jaw_to)
+ self.jaw_k = torch.where(mask, torch.zeros_like(jaw), self.jaw_k)
+ self.jaw_n = torch.where(mask, n, self.jaw_n)
+
+ def _rot(self, yaw):
+ lam = 1 - minjerk((self.t + 1) * CONTROL_DT / self.cfg.tilt_s)
+ return rotz(yaw) @ expmap(self.tilt0 * lam[:, None])
+
+ def _jaw_check(self, q_meas):
+ """Jaw angle for the floor: the angle in the jaw's range of this step nearest to theta_worst."""
+ j = [self.q_cmd[:, 5], self.jaw_to]
+ if q_meas is not None:
+ j.append(q_meas[:, 5].to(self.pos))
+ j = torch.stack(j, -1)
+ return torch.minimum(torch.maximum(torch.full_like(j[:, 0], self.theta_worst), j.amin(-1)), j.amax(-1))
+
+ def _low_offset(self, q5, jaw):
+ """TCP z minus the lowest collision point (m) at arm angles q5 [B, 5] and jaw [B]."""
+ q = torch.cat((q5, jaw[:, None]), -1)
+ return self.kin.fk(q)[0][:, 2] - self.kin.lowest_point(q, exact=False)
+
+ def _polar(self, p):
+ rel = p[:, :2] - self.pan_axis
+ r = rel.norm(dim=-1)
+ return r, torch.atan2(rel[:, 1], rel[:, 0]), rel / r.clamp_min(1e-9)[:, None]
+
+ def _allow(self, dist, v_wall, acc):
+ """Largest speed toward a wall at distance dist (>= 0) that a decision may end with and still stop before it
+ (cosine blend from v_wall over T_d, then braking at the average deceleration acc [B]). Blend "hann": v_wall =
+ the current set point, and the blend counts 2 T_d (its response lags the cosine blend by about T_d / 2 on
+ the way up and on the way down)."""
+ td = 2 * self.T_d if self.hann else self.T_d
+ disc = td * td / 4 - 2 * (v_wall * td / 2 - dist.clamp_min(0)) / acc
+ return acc * (-td / 2 + torch.sqrt(disc.clamp_min(0)))
+
+ # ---- "hann" blend (option b1) ----------------------------------------------------------------------------------
+ def setpoint(self):
+ """(velocity [B, 3], yaw rate [B]) the free-motion target is heading to: the last decision's set point (blend
+ "hann": the sum of all its increments; "cosine": the blend's end velocity; "filter": its set point)."""
+ if self.hann:
+ return self.hv + self.hA_d + self.hB_d, self.hw + self.hA_w + self.hB_w
+ return self.vn.clone(), self.wn.clone()
+
+ def _hann_missing(self):
+ """Displacement (m [B, 3], rad [B]) the running Hann blends still owe against a velocity step to their
+ increments: sum of d T R(tau / T)."""
+ rA = self.hA_T * hann_R(self.hA_tau / self.hA_T)
+ rB = self.hB_T * hann_R(self.hB_tau / self.hB_T)
+ return self.hA_d * rA[:, None] + self.hB_d * rB[:, None], self.hA_w * rA + self.hB_w * rB
+
+ def rest_terms(self):
+ """Free motion: where the target comes to rest if this decision sets the velocity v (and yaw rate w) and the
+ next decision sets 0: pos + alpha v + beta, yaw + alpha w + beta_yaw -> (alpha (s), beta [B, 3], beta_yaw [B]).
+ Cosine: alpha = T_d, beta = v0 T_d / 2 (v0 = the last step's velocity); hann: alpha = T_d, beta = u T_d - the
+ running blends' missing displacement (u = the current set point). Not for blend "filter" (the expert solves
+ it numerically)."""
+ if self.hann:
+ u, w = self.setpoint()
+ mp, mw = self._hann_missing()
+ return self.T_d, u * self.T_d - mp, w * self.T_d - mw
+ return self.T_d, self.vel * self.T_d / 2, self.yrate * self.T_d / 2
+
+ def _hann_zero(self, mask, v=None, w=None):
+ """Hann blend state of the worlds in mask at a constant velocity v [B, 3] / yaw rate w [B] (default rest)."""
+ m3 = mask[:, None]
+ self.hv = torch.where(m3, torch.zeros_like(self.hv) if v is None else v, self.hv)
+ self.hw = torch.where(mask, torch.zeros_like(self.hw) if w is None else w, self.hw)
+ for x in (self.hA_d, self.hB_d):
+ x.copy_(torch.where(m3, 0.0, x))
+ for x in (self.hA_w, self.hB_w):
+ x.copy_(torch.where(mask, 0.0, x))
+ for x in (self.hA_tau, self.hA_T, self.hB_tau, self.hB_T):
+ x.copy_(torch.where(mask, 1.0, x))
+
+ def _hann_done(self):
+ """[B] bool: no Hann blend is running."""
+ return (self.hA_tau >= self.hA_T - 1e-9) & (self.hB_tau >= self.hB_T - 1e-9)
+
+ def _hann_shift(self, mask, d, w, T):
+ """Decision of the worlds in mask: the finished blend A folds into the base velocity, B becomes A, and a new
+ blend B starts with increment d [B, 3] / w [B] and length T [B] (s)."""
+ m3 = mask[:, None]
+ # with decisions every T_d (the API) blend A started 2 T_d ago and has finished; were it not (decide called at
+ # other times), folding it in whole would step the velocity by its missing part
+ self.hv = torch.where(m3, self.hv + self.hA_d, self.hv)
+ self.hw = torch.where(mask, self.hw + self.hA_w, self.hw)
+ self.hA_d, self.hA_w = torch.where(m3, self.hB_d, self.hA_d), torch.where(mask, self.hB_w, self.hA_w)
+ self.hA_T, self.hA_tau = torch.where(mask, self.hB_T, self.hA_T), torch.where(mask, self.hB_tau, self.hA_tau)
+ self.hB_d, self.hB_w = torch.where(m3, d, self.hB_d), torch.where(mask, w, self.hB_w)
+ self.hB_T = torch.where(mask, T, self.hB_T)
+ self.hB_tau = torch.where(mask, torch.zeros_like(self.hB_tau), self.hB_tau)
+
+ def _hann_step(self):
+ """Target displacement (m [B, 3], rad [B]) of the Hann blends over one control step (closed form)."""
+ dt = CONTROL_DT
+ kA = self.hA_T * (hann_P((self.hA_tau + dt) / self.hA_T) - hann_P(self.hA_tau / self.hA_T))
+ kB = self.hB_T * (hann_P((self.hB_tau + dt) / self.hB_T) - hann_P(self.hB_tau / self.hB_T))
+ return (self.hv * dt + self.hA_d * kA[:, None] + self.hB_d * kB[:, None],
+ self.hw * dt + self.hA_w * kA + self.hB_w * kB)
+
+ # ---- CARRY macro (option b2) ---------------------------------------------------------------------------------
+ def carry_target(self, a):
+ """CARRY end of action a [B, 6] from the current target (module docstring): TCP xy + a[0:2] carry_reach (norm
+ clipped), same height; radius and pan-angle bounds as free motion; the straight line shortened where it would
+ pass inside the inner radius; yaw + a[3] hold_turn_max within the hold turn cap and the wrist roll range.
+ -> (end [B, 3], yaw [B])."""
+ c = self.cfg
+ dxy = a[:, 0:2] * c.carry_reach
+ n = dxy.norm(dim=-1, keepdim=True)
+ dxy = dxy * torch.where(n > c.carry_reach, c.carry_reach / n.clamp_min(1e-12), torch.ones_like(n))
+ r_lo, r_hi, a_lo, a_hi = self._bounds()
+ r, ang, _ = self._polar(torch.cat((self.pos[:, :2] + dxy, self.pos[:, 2:]), -1))
+ r = torch.minimum(torch.maximum(r, r_lo), r_hi)
+ ang = torch.minimum(torch.maximum(ang, a_lo), a_hi)
+ p = self.pos[:, :2] - self.pan_axis # line start about the pan axis
+ d = torch.stack((torch.cos(ang), torch.sin(ang)), -1) * r[:, None] - p
+ dd, pd = (d * d).sum(-1), (p * d).sum(-1)
+ disc = pd * pd - dd * ((p * p).sum(-1) - r_lo * r_lo)
+ t1 = (-pd - torch.sqrt(disc.clamp_min(0))) / dd.clamp_min(1e-18) # first crossing of the r_lo circle
+ cut = (disc > 0) & (t1 >= 0) & (t1 < 1) & (dd > 1e-18)
+ d = d * torch.where(cut, t1, torch.ones_like(t1))[:, None]
+ end = torch.cat((self.pos[:, :2] + d, self.pos[:, 2:]), -1)
+ _, ang_e, _ = self._polar(end)
+ y1 = self.yaw + a[:, 3] * c.hold_turn_max
+ y1 = torch.minimum(torch.maximum(y1, self.yaw_hold0 - c.hold_turn_max), self.yaw_hold0 + c.hold_turn_max)
+ rho = wrap(y1 - ang_e)
+ y1 = y1 - (rho - rho.clamp(-c.roll_max, c.roll_max))
+ return end, y1
+
+ def _carry_steps(self, t_draw, end, yaw_end, samples=16):
+ """Steps of a CARRY line (the collector's Plan.cart timing): the drawn duration, x 1.3 (up to 6 times) while the
+ largest joint step of the minimum-jerk line exceeds ``carry_arm_step``. The joint path comes from warm-started
+ IK at ``samples`` points (the yaw turning along); the largest step of a line of n steps is
+ max over the time fraction s of |dq/du|(u(s)) 30 s^2 (1 - s)^2 / n (chord slopes, the collector's actual
+ largest step rather than the bound 1.875 max|dq/du| / n)."""
+ c = self.cfg
+ qs, q = [self.q_des], self.q_des
+ for k in range(1, samples + 1):
+ rot = self._rot(self.yaw + (yaw_end - self.yaw) * (k / samples))
+ q, _, _ = self.kin.ik_track(q, self.pos + (end - self.pos) * (k / samples), rot, 2 * c.ik_iters)
+ qs.append(q)
+ slope = (torch.stack(qs, 1).diff(dim=1).abs() * samples).amax(-1) # [B, K] max over joints, per chord
+ sg = torch.linspace(0, 1, 201, **self.f)
+ chord = (minjerk(sg) * samples).long().clamp(0, samples - 1) # chord of u(s)
+ peak = (slope[:, chord] * (30 * sg * sg * (1 - sg) ** 2)).amax(-1) # max |dq/ds| [B]
+ n = torch.round(t_draw / CONTROL_DT).clamp_min(1)
+ for _ in range(6):
+ n = torch.where(peak / n > c.carry_arm_step, torch.round(n * 1.3), n)
+ return n
+
+ def _carry_abort(self, mask):
+ """Stop the CARRY lines of the worlds in mask: a cosine brake of the target velocity of the last step to 0 (the
+ free-motion brake rule: max(T_d, pi |v| / (2 a_max), pi |w| / (2 alpha_max)), rounded up to the step), then
+ rest in mode hold. -> mask."""
+ if not bool(mask.any()):
+ return mask
+ c = self.cfg
+ sp, wr = self.vel.norm(dim=-1), self.yrate.abs()
+ tbk = torch.maximum(torch.maximum(torch.full_like(sp, self.T_d), math.pi * sp / (2 * c.a_max)),
+ math.pi * wr / (2 * c.alpha_max))
+ tbk = torch.ceil(tbk / CONTROL_DT - 1e-9) * CONTROL_DT
+ m3 = mask[:, None]
+ self.v0, self.vn = torch.where(m3, self.vel, self.v0), torch.where(m3, 0.0, self.vn)
+ self.w0, self.wn = torch.where(mask, self.yrate, self.w0), torch.where(mask, 0.0, self.wn)
+ self.tau, self.tb = torch.where(mask, 0.0, self.tau), torch.where(mask, tbk, self.tb)
+ self._hann_zero(mask) # (a Hann world brakes with the cosine rule here)
+ self.carry_on = self.carry_on & ~mask
+ self.carry_brk = self.carry_brk | mask
+ self.counts["carry_aborts"] += mask.long()
+ return mask
+
+ def _carry_start(self, a, mask):
+ """Start CARRY lines in the worlds of mask whose target differs from the current one by more than the dead
+ band. -> started [B] bool."""
+ c = self.cfg
+ end, y1 = self.carry_target(a)
+ start = mask & (((end - self.pos)[:, :2].norm(dim=-1) >= c.carry_min_d)
+ | ((y1 - self.yaw).abs() >= c.carry_min_yaw))
+ if not bool(start.any()):
+ return start
+ ln = self._carry_steps(self._draw(start, c.carry_t), end, y1)
+ m3 = start[:, None]
+ self.lp0, self.lp1 = torch.where(m3, self.pos, self.lp0), torch.where(m3, end, self.lp1)
+ self.ly0, self.ly1 = torch.where(start, self.yaw, self.ly0), torch.where(start, y1, self.ly1)
+ self.ln = torch.where(start, ln, self.ln)
+ self.lk = torch.where(start, torch.zeros_like(self.lk), self.lk)
+ self.carry_on = self.carry_on | start
+ self.counts["carries"] += start.long()
+ return start
+
+ def _ceiling(self):
+ """TCP ceiling (m) [B]: z_max, in mode hold also the held-cube ceiling; never below the current target (a
+ start above it can only move down: no jump)."""
+ top = torch.where(self.mode == M["hold"], torch.minimum(self.z_ceil, torch.full_like(self.z_ceil, self.cfg.z_max)),
+ torch.full_like(self.z_ceil, self.cfg.z_max))
+ return torch.maximum(top, self.pos[:, 2])
+
+ def _bounds(self):
+ """Free-motion radius and pan-angle bounds [B], relaxed to the current target (push-T rule: a target outside
+ never jumps, it only cannot move farther out)."""
+ c = self.cfg
+ r, ang, _ = self._polar(self.pos)
+ return (torch.clamp_max(r, c.r_range[0]), torch.clamp_min(r, c.r_range[1]),
+ torch.clamp_max(ang, -c.angle_max), torch.clamp_min(ang, c.angle_max))
+
+ def _rate_map(self):
+ """Damped least-squares map of a target velocity (v [3] m/s, yaw rate w rad/s) to joint rates at the last IK
+ solution, with the IK's weight 0.1 m/rad on the rotation: [B, 5, 4] (columns vx, vy, vz, w)."""
+ jp, jr, _, _ = self.kin.jacobian(self.q_des)
+ jac = torch.cat((jp, 0.1 * jr), -2) # [B, 6, 5]
+ jt = jac.transpose(-1, -2)
+ eye = torch.eye(5, **self.f)
+ pinv = torch.linalg.solve(jt @ jac + 1e-4 * eye, jt) # [B, 5, 6]
+ return torch.cat((pinv[:, :, :3], 0.1 * pinv[:, :, 5:6]), -1)
+
+ def _acc_along(self, rmap, n):
+ """Average deceleration (m/s^2 or rad/s^2) of a cosine blend along task direction n [B, 4] that keeps every
+ joint's peak step change <= ddq_max (and <= the Cartesian a_max / alpha_max)."""
+ qn = (rmap @ n[..., None])[..., 0].abs() # joint rate per unit rate
+ k = 1 / (self.k_peak * CONTROL_DT * CONTROL_DT) # peak accel -> blend dv
+ dv = (k * self.ddq_max / qn.clamp_min(1e-9)).amin(-1)
+ lin = n[:, :3].norm(dim=-1) > 0.5
+ cap = torch.where(lin, self.dv_max, self.dw_max)
+ return self.cfg.wall_margin * torch.minimum(dv, cap) / self.T_d
+
+ def _walls(self, vn, v0, rmap):
+ """Cap the velocity toward each workspace wall (module docstring). -> (vn, capped [B])."""
+ c = self.cfg
+ p = self.pos
+ r, ang, er = self._polar(p)
+ zero = torch.zeros_like(r)
+ et = torch.stack((-er[:, 1], er[:, 0], zero), -1)
+ er3 = torch.cat((er, zero[:, None]), -1)
+ ez = torch.zeros_like(p)
+ ez[:, 2] = 1.0
+ floor = c.low_min + self.low_off
+ r_lo, r_hi, a_lo, a_hi = self._bounds()
+ walls = ((-ez, p[:, 2] - floor), (ez, self._ceiling() - p[:, 2]), (-er3, r - r_lo),
+ (er3, r_hi - r), (et, r * (a_hi - ang)), (-et, r * (ang - a_lo)))
+ capped = torch.zeros_like(r, dtype=torch.bool)
+ for n, dist in walls:
+ acc = self._acc_along(rmap, torch.cat((n, zero[:, None]), -1))
+ allow = self._allow(dist, (v0 * n).sum(-1), acc)
+ over = ((vn * n).sum(-1) - allow).clamp_min(0)
+ capped |= over > 1e-12
+ vn = vn - over[:, None] * n
+ return vn, capped
+
+ def _yaw_walls(self, wn, w0, rmap):
+ c = self.cfg
+ hold = self.mode == M["hold"]
+ _, ang, _ = self._polar(self.pos)
+ rho = wrap(self.yaw - ang)
+ big = torch.full_like(wn, 1e9)
+ ew = torch.zeros(self.B, 4, **self.f)
+ ew[:, 3] = 1.0
+ acc = self._acc_along(rmap, ew)
+ walls = ((1.0, torch.where(hold, self.yaw_hold0 + c.hold_turn_max - self.yaw, big)),
+ (-1.0, torch.where(hold, self.yaw - (self.yaw_hold0 - c.hold_turn_max), big)),
+ (1.0, c.roll_max - rho), (-1.0, c.roll_max + rho))
+ capped = torch.zeros_like(wn, dtype=torch.bool)
+ for sgn, dist in walls:
+ allow = self._allow(dist, sgn * w0, acc)
+ over = (sgn * wn - allow).clamp_min(0)
+ capped |= over > 1e-12
+ wn = wn - sgn * over
+ return wn, capped & hold
+
+ def _joint_scale(self, rmap, v0, vn, w0, wn):
+ """Largest lam in [0, 1] for the velocity change (v0, w0) -> (vn, wn) such that the blend keeps every joint's
+ step change <= ddq_max and its step <= dq_max (Jacobian estimate at the decision)."""
+ qd0 = (rmap @ torch.cat((v0, w0[:, None]), -1)[..., None])[..., 0] # rad/s
+ dqd = (rmap @ torch.cat((vn - v0, (wn - w0)[:, None]), -1)[..., None])[..., 0]
+ dt = CONTROL_DT
+ lam_acc = (self.ddq_max / (self.k_peak * dt * dt) / dqd.abs().clamp_min(1e-12)).amin(-1)
+ room = self.dq_max / dt - torch.sign(dqd) * qd0 # rate left in the move direction
+ lam_spd = torch.where(dqd.abs() > 1e-12, room.clamp_min(0) / dqd.abs().clamp_min(1e-12),
+ torch.full_like(room, 1e9)).amin(-1)
+ return torch.minimum(torch.minimum(lam_acc, lam_spd), torch.ones_like(lam_acc)).clamp_min(0)
+
+ def _clip(self, pos, yaw, apply):
+ """Hard workspace clip of a free-motion target (the walls of ``_walls``). -> (pos, yaw, clipped [B])."""
+ c = self.cfg
+ floor = c.low_min + self.low_off
+ z = torch.minimum(torch.maximum(pos[:, 2], floor), self._ceiling())
+ r, ang, _ = self._polar(pos)
+ r_lo, r_hi, a_lo, a_hi = self._bounds()
+ r2, ang2 = torch.minimum(torch.maximum(r, r_lo), r_hi), torch.minimum(torch.maximum(ang, a_lo), a_hi)
+ xy = self.pan_axis + torch.stack((torch.cos(ang2), torch.sin(ang2)), -1) * r2[:, None]
+ p2 = torch.cat((xy, z[:, None]), -1)
+ rho = wrap(yaw - ang2)
+ y2 = yaw - (rho - rho.clamp(-c.roll_max, c.roll_max))
+ hold = self.mode == M["hold"]
+ y2 = torch.where(hold, torch.minimum(torch.maximum(y2, self.yaw_hold0 - c.hold_turn_max),
+ self.yaw_hold0 + c.hold_turn_max), y2)
+ clipped = apply & (((p2 - pos).abs().amax(-1) > 1e-12) | ((y2 - yaw).abs() > 1e-12))
+ return torch.where(apply[:, None], p2, pos), torch.where(apply, y2, yaw), clipped
+
+ # ---- brake rest point and the GRASP gate (PPO options) -----------------------------------------------------------
+ @property
+ def action_dim(self):
+ """Columns of the action: 7 with ``abort_action`` (a[6] = abort), else 6."""
+ return 7 if self.cfg.abort_action else ACTION_DIM
+
+ @torch.no_grad()
+ def brake_stop(self, rmap=None):
+ """Where a GRASP / PLACE trigger at this decision brings the target to rest, without changing any state:
+ (TCP position [B, 3] m, yaw [B] rad) = ``macro_goal`` x, y, yaw of a GRASP started now (``decide``'s brake rule
+ for the blends "cosine", "filter" and "hann"; review_code_v2 R4). rmap: ``_rate_map()`` if already computed."""
+ c = self.cfg
+ v0, w0 = self.setpoint() if self.hann else (self.vel, self.yrate)
+ if self.filt: # where the filter comes to rest with the set point 0
+ 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)
+ rmap = self._rate_map() if rmap is None else rmap
+ sp, wr = v0.norm(dim=-1), w0.abs()
+ qd0 = (rmap @ torch.cat((v0, w0[:, None]), -1)[..., None])[..., 0].abs()
+ rest = (sp < 1e-9) & (wr < 1e-9)
+ if self.hann: # decide's shift: blend B becomes A, the brake (increment -v0 over T_bk) the new B at clock 0
+ tjh = (2 * qd0 * CONTROL_DT * CONTROL_DT / self.ddq_max).amax(-1)
+ tbh = torch.maximum(torch.maximum(torch.full_like(sp, 2 * self.T_d), 2 * sp / c.a_max),
+ torch.maximum(2 * wr / c.alpha_max, tjh))
+ tbh = torch.ceil(tbh / CONTROL_DT - 1e-9) * CONTROL_DT
+ tbh = torch.where(rest & self._hann_done(), torch.full_like(tbh, 1e-9), tbh)
+ rA = self.hB_T * hann_R(self.hB_tau / self.hB_T)
+ rB = tbh * hann_R(torch.zeros_like(tbh))
+ mp = self.hB_d * rA[:, None] + (torch.zeros_like(v0) - v0) * rB[:, None]
+ mw = self.hB_w * rA + (torch.zeros_like(w0) - w0) * rB
+ return self.pos - mp, self.yaw - mw
+ tj = (math.pi * qd0 * CONTROL_DT * CONTROL_DT / (2 * self.ddq_max)).amax(-1)
+ tbk = torch.maximum(torch.maximum(torch.full_like(sp, self.T_d), math.pi * sp / (2 * c.a_max)),
+ torch.maximum(math.pi * wr / (2 * c.alpha_max), tj))
+ tbk = torch.ceil(tbk / CONTROL_DT - 1e-9) * CONTROL_DT
+ tb = torch.where(rest, torch.zeros_like(tbk), tbk)
+ return self.pos + v0 * (tb / 2)[:, None], self.yaw + w0 * tb / 2
+
+ @torch.no_grad()
+ def gate_ok(self, state, stop=None):
+ """GRASP precondition (``grasp_gate``, module docstring) [B] bool for the cube of ``state`` (WorldState: cube_pos,
+ cube_quat) and the brake rest point ``stop`` = (position [B, 3], yaw [B]) (default ``brake_stop()``)."""
+ from nedm.so101_policy.task import cube_yaw_tilt, wrap90
+ c = self.cfg
+ sp, syaw = self.brake_stop() if stop is None else stop
+ cube = state.cube_pos.to(**self.f)
+ cyaw, _ = cube_yaw_tilt(state.cube_quat.to(**self.f))
+ d = cube[:, :2] - sp[:, :2]
+ cs, sn = torch.cos(syaw), torch.sin(syaw)
+ x, y = cs * d[:, 0] + sn * d[:, 1], -sn * d[:, 0] + cs * d[:, 1]
+ q_w = torch.cat((self.q_des, torch.full_like(self.yaw[:, None], self.theta_worst)), -1)
+ floor = c.low_min + self.kin.fk(q_w)[0][:, 2] - self.kin.lowest_point(q_w, exact=False)
+ z_hi = torch.maximum(cube[:, 2] + c.grasp_dz[1], floor) # the descent end over the drawn 0-2 mm
+ z_lo = torch.maximum(cube[:, 2] + c.grasp_dz[0], floor)
+ return ((x.abs() <= c.gate_box[0]) & (y.abs() <= c.gate_box[1]) & (wrap90(syaw - cyaw).abs() <= c.gate_box[2])
+ & (cube[:, 2] - z_hi >= c.gate_z[0]) & (cube[:, 2] - z_lo <= c.gate_z[1]))
+
+ # ---- reset --------------------------------------------------------------------------------------------------
+ def reset(self, idx, q, hold=None, seed=None, z_ceil=None):
+ """Worlds idx (index tensor or bool mask) start at rest at the measured joint angles q [n, 6]. hold [n] bool:
+ start in mode hold (cube in the jaws; z_ceil [n] = TCP ceiling, default z_max), else free (the jaw opens to
+ jaw_open). seed [n] int64: macro-duration seeds; the same seed gives the same durations (paired evaluations:
+ pass the task seed). Default (review F5): a fresh stream per episode, base_seed * 1,000,003 + world index +
+ EPISODE_MIX * (number of earlier resets of that world), so the first episode of a world keeps the old default;
+ a trainer may also pass its own episode seed (e.g. episode counter * B + slot)."""
+ c = self.cfg
+ idx = self._ids(idx)
+ n = len(idx)
+ q = torch.minimum(torch.maximum(q.to(**self.f), self.kin.tlo), self.kin.thi)
+ hold = torch.zeros(n, dtype=torch.bool, device=self.dev) if hold is None else torch.as_tensor(hold, device=self.dev)
+ p, r = self.kin.fk(q)
+ yaw = yaw_of(r)
+ self.mode[idx] = torch.where(hold, M["hold"], M["free"])
+ self.pos[idx], self.yaw[idx] = p, yaw
+ for x in (self.vel, self.yrate, self.v0, self.vn, self.w0, self.wn, self.tau, self.lk, self.ln, self.dq,
+ self.fv, self.fa, self.fw, self.fwa,
+ self.t, self.ik_err, self.h, self.z_goal, self.goal):
+ x[idx] = 0.0
+ self.tb[idx] = self.T_d
+ self.lp0[idx], self.lp1[idx] = p, p
+ self.q_des[idx], self.q_cmd[idx] = q[:, :5], q
+ self.tilt0[idx] = rotvec(rotz(yaw).transpose(-1, -2) @ r)
+ self.yaw_hold0[idx] = yaw
+ self.z_ceil[idx] = c.z_max if z_ceil is None else torch.as_tensor(z_ceil, **self.f)
+ goal = torch.where(hold, torch.full((n,), c.jaw_closed, **self.f), torch.full((n,), c.jaw_open, **self.f))
+ jaw = q[:, 5]
+ self.jaw_from[idx], self.jaw_to[idx], self.jaw_k[idx] = jaw, goal, 0.0
+ self.jaw_n[idx] = torch.round(torch.clamp_min(1.875 * (goal - jaw).abs() / c.jaw_speed, c.jaw_min_s)
+ / CONTROL_DT).clamp_min(1)
+ jc = torch.minimum(torch.maximum(torch.full_like(jaw, self.theta_worst), torch.minimum(jaw, goal)),
+ torch.maximum(jaw, goal))
+ self.low_off[idx] = self._low_offset(q[:, :5], jc)
+ self.seed[idx] = (torch.as_tensor(seed, dtype=torch.long, device=self.dev).clone() if seed is not None
+ else self.base_seed * 1000003 + idx + EPISODE_MIX * self.episode[idx])
+ self.episode[idx] += 1
+ self.draws[idx] = 0
+ self.armed[idx] = True
+ sel = torch.zeros(self.B, dtype=torch.bool, device=self.dev)
+ sel[idx] = True
+ self._hann_zero(sel)
+ self.carry_on[idx] = False
+ self.carry_brk[idx] = False
+ self.ly0[idx], self.ly1[idx] = yaw, yaw
+ for v in self.counts.values():
+ v[idx] = 0
+
+ # ---- one decision -------------------------------------------------------------------------------------------
+ @torch.no_grad()
+ def decide(self, action, state=None):
+ """action [B, 6] (or [B, 7] with ``abort_action``) in [-1, 1] (module docstring); state: the WorldState of the
+ decision (q, cube_pos, cube_quat used; None: no yaw lock, GRASP height from the resting cube height; required
+ with ``grasp_gate``). -> info dict of [B] bools."""
+ c = self.cfg
+ a = action.to(**self.f).clamp(-1.0, 1.0)
+ a7 = c.abort_action and a.shape[1] > ACTION_DIM # the separate abort output a[6] (PPO options)
+ mode = self.mode
+ free, hold = mode == M["free"], mode == M["hold"]
+ pre = (mode == M["g_brake"]) | (mode == M["g_descend"]) | (mode == M["g_settle"])
+ if c.grasp_latch: # a started GRASP: abort only by the abort output
+ abort = pre & (a[:, 6] > c.abort_act_thr) if a7 else torch.zeros_like(pre)
+ else:
+ abort = pre & (a[:, 4] <= c.abort_thr)
+ free = free | abort
+ self.mode = torch.where(abort, M["free"], mode)
+ if self.filt:
+ self.fv = torch.where(abort[:, None], self.vel, self.fv)
+ self.fa = torch.where(abort[:, None], torch.zeros_like(self.fa), self.fa)
+ self.fw = torch.where(abort, self.yrate, self.fw)
+ self.fwa = torch.where(abort, torch.zeros_like(self.fwa), self.fwa)
+ if self.hann:
+ self._hann_zero(abort, self.vel, self.yrate)
+ moving = hold & (self.carry_on | self.carry_brk) # a CARRY line or its abort brake runs: decision ignored
+ take = free | (hold & ~moving) if not c.carry_macro else free # free-motion decisions
+ v0, w0 = self.setpoint() if self.hann else (self.vel, self.yrate)
+ d = a[:, :3] * c.d_max
+ dn = d.norm(dim=-1, keepdim=True)
+ d = d * torch.where(dn > c.d_max, c.d_max / dn.clamp_min(1e-12), torch.ones_like(dn))
+ dv = d / self.T_d - v0
+ dvn = dv.norm(dim=-1, keepdim=True)
+ vn = v0 + dv * torch.where(dvn > self.dv_max, self.dv_max / dvn.clamp_min(1e-12), torch.ones_like(dvn))
+ wn = w0 + (a[:, 3] * c.dyaw_max / self.T_d - w0).clamp(-self.dw_max, self.dw_max)
+ rmap = self._rate_map()
+ lam = self._joint_scale(rmap, v0, vn, w0, wn)
+ vn = v0 + lam[:, None] * (vn - v0)
+ wn = w0 + lam * (wn - w0)
+ vn, ws_capped = self._walls(vn, v0, rmap)
+ blocked = torch.zeros_like(free)
+ cube_z = torch.full_like(self.yaw, CUBE_REST_Z)
+ bottom = torch.zeros_like(self.yaw)
+ if state is not None:
+ cube_p = state.cube_pos.to(**self.f)
+ rc = quat_mat(state.cube_quat.to(**self.f))
+ cube_z = cube_p[:, 2]
+ bottom = cube_z - CUBE_HALF * rc[:, 2, :].abs().sum(-1) # lowest cube corner (m)
+ near = free & (self.q_cmd[:, 5] > 0.3) & (bottom < c.cube_on_table)
+ if bool(near.any()):
+ dist = self.kin.box_distance(self.q_cmd, cube_p, state.cube_quat, CUBE_HALF)
+ blocked = near & (dist < c.yaw_free_gap + v0.norm(dim=-1) * self.T_d)
+ wn = torch.where(blocked, torch.zeros_like(wn), wn)
+ wn, yaw_capped = self._yaw_walls(wn, w0, rmap)
+ trig = (a[:, 4] > c.trigger_thr) & self.armed
+ reads4 = free | hold | (torch.zeros_like(pre) if c.grasp_latch else pre) # where a[4] is read (R5)
+ self.armed = self.armed | (reads4 & (a[:, 4] <= c.trigger_thr))
+ g_trig = free & ~abort & trig
+ jaw_ready = (self.jaw_k >= self.jaw_n) & ((self.jaw_to - c.jaw_open).abs() < 1e-9)
+ ignored = g_trig & ~jaw_ready
+ g_trig = g_trig & jaw_ready
+ gated = torch.zeros_like(g_trig)
+ if c.grasp_gate: # GRASP precondition (PPO options): before any state change
+ if state is None:
+ raise ValueError("grasp_gate needs the WorldState in decide")
+ gated = g_trig & ~self.gate_ok(state, self.brake_stop(rmap))
+ g_trig = g_trig & ~gated
+ ignored = ignored | gated
+ p_trig = hold & ~moving & trig
+ self.armed = self.armed & ~(g_trig | p_trig)
+ go = take & ~g_trig & ~p_trig
+ # free-motion decisions
+ self.v0 = torch.where(take[:, None], v0, self.v0)
+ self.w0 = torch.where(take, w0, self.w0)
+ self.vn = torch.where(go[:, None], vn, torch.where((g_trig | p_trig)[:, None], torch.zeros_like(vn), self.vn))
+ self.wn = torch.where(go, wn, torch.where(g_trig | p_trig, torch.zeros_like(wn), self.wn))
+ self.tau = torch.where(take, torch.zeros_like(self.tau), self.tau)
+ # macro starts: brake to rest first (skipped at rest)
+ brake = g_trig | p_trig
+ sp, wr = v0.norm(dim=-1), w0.abs()
+ qd0 = (rmap @ torch.cat((v0, w0[:, None]), -1)[..., None])[..., 0].abs()
+ tj = (math.pi * qd0 * CONTROL_DT * CONTROL_DT / (2 * self.ddq_max)).amax(-1) # joint step-change bound
+ tbk = torch.maximum(torch.maximum(torch.full_like(sp, self.T_d), math.pi * sp / (2 * c.a_max)),
+ torch.maximum(math.pi * wr / (2 * c.alpha_max), tj))
+ tbk = torch.ceil(tbk / CONTROL_DT - 1e-9) * CONTROL_DT
+ rest = (sp < 1e-9) & (wr < 1e-9)
+ self.tb = torch.where(brake, torch.where(rest, torch.zeros_like(tbk), tbk), torch.where(take, self.T_d, self.tb))
+ stop = self.pos + v0 * (self.tb / 2)[:, None]
+ ystop = self.yaw + w0 * self.tb / 2
+ if self.filt: # where the filter comes to rest with the set point 0
+ stop = self.pos + 2 * self.fv / c.wn + self.fa / (c.wn * c.wn)
+ ystop = self.yaw + 2 * self.fw / c.wn + self.fwa / (c.wn * c.wn)
+ 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)
+ tjh = (2 * qd0 * CONTROL_DT * CONTROL_DT / self.ddq_max).amax(-1)
+ tbh = torch.maximum(torch.maximum(torch.full_like(sp, 2 * self.T_d), 2 * sp / c.a_max),
+ torch.maximum(2 * wr / c.alpha_max, tjh))
+ tbh = torch.ceil(tbh / CONTROL_DT - 1e-9) * CONTROL_DT
+ tbh = torch.where(brake & rest & self._hann_done(), torch.full_like(tbh, 1e-9), tbh)
+ vgo = torch.where(go[:, None], vn, torch.zeros_like(vn))
+ wgo = torch.where(go, wn, torch.zeros_like(wn))
+ self._hann_shift(take, vgo - v0, wgo - w0, torch.where(brake, tbh, torch.full_like(tbh, 2 * self.T_d)))
+ mp, mw = self._hann_missing()
+ stop, ystop = self.pos - mp, self.yaw - mw # rest point of the brake: sum of d T R(tau / T)
+ # GRASP: descent end and the hold ceiling
+ if bool(g_trig.any()):
+ q_w = torch.cat((self.q_des, torch.full_like(self.yaw[:, None], self.theta_worst)), -1)
+ off = self.kin.fk(q_w)[0][:, 2] - self.kin.lowest_point(q_w, exact=False)
+ zg = torch.maximum(cube_z + self._draw(g_trig, c.grasp_dz), c.low_min + off)
+ self.z_goal = torch.where(g_trig, zg, self.z_goal)
+ self.h = torch.where(g_trig, c.lift_range[0] + (a[:, 5] + 1) / 2 * (c.lift_range[1] - c.lift_range[0]), self.h)
+ ceil = torch.clamp_max(zg + c.cube_bottom_max - bottom.clamp_min(0), c.z_max)
+ self.z_ceil = torch.where(g_trig, ceil, self.z_ceil)
+ self.goal = torch.where(g_trig[:, None], torch.stack((stop[:, 0], stop[:, 1], zg, ystop), -1), self.goal)
+ if bool(p_trig.any()):
+ zp = self.pos[:, 2] - bottom + self._draw(p_trig, c.place_dz)
+ self.z_goal = torch.where(p_trig, zp, self.z_goal)
+ self.mode = torch.where(g_trig, M["g_brake"], torch.where(p_trig, M["p_brake"], self.mode))
+ carry_started = torch.zeros_like(p_trig)
+ carry_aborted = torch.zeros_like(p_trig)
+ if c.carry_macro: # option b2: a hold decision at rest gives the CARRY target; a[5] aborts a running line
+ stop_line = a[:, 6] > c.abort_act_thr if a7 else a[:, 5] > c.carry_abort_thr # R3: own output with a[6]
+ carry_aborted = self._carry_abort(hold & self.carry_on & stop_line)
+ carry_started = self._carry_start(a, hold & ~moving & ~p_trig)
+ info = dict(grasp_started=g_trig, place_started=p_trig, aborted=abort, trigger_ignored=ignored,
+ yaw_blocked=blocked & take, yaw_capped=yaw_capped & take, ws_capped=ws_capped & go,
+ carry_started=carry_started, carry_aborted=carry_aborted, gate_blocked=gated)
+ for k in ("aborted", "trigger_ignored", "yaw_blocked", "yaw_capped", "gate_blocked"):
+ self.counts[k] += info[k].long()
+ return info
+
+ # ---- one control step ---------------------------------------------------------------------------------------
+ @torch.no_grad()
+ def step(self, q_meas=None):
+ """One 20 ms step. q_meas [B, 6]: measured joint angles (lead band; None: no band). -> (joint targets [B, 6]
+ rad, info dict)."""
+ c, kin = self.cfg, self.kin
+ mode = self.mode
+ carry = self.carry_on & (mode == M["hold"]) # a CARRY line (option b2) runs or waits for rest
+ blendm = (mode == M["free"]) | ((mode == M["hold"]) & ~carry) | (mode == M["g_brake"]) | (mode == M["p_brake"])
+ linem = ((mode == M["g_descend"]) | (mode == M["g_lift"]) | (mode == M["p_lower"]) | (mode == M["p_retreat"])
+ | carry)
+ linem = linem & (self.lk < self.ln - 1e-9) # a finished line waits for rest without IK
+ still = ~blendm & ~linem
+ if q_meas is not None:
+ q_meas = q_meas.to(**self.f)
+ # nominal target step of the mode
+ tau1 = self.tau + CONTROL_DT
+ p0, _ = blend(self.v0, self.vn, self.tau, self.tb)
+ p1, _ = blend(self.v0, self.vn, tau1, self.tb)
+ y0, _ = blend(self.w0, self.wn, self.tau, self.tb)
+ y1, _ = blend(self.w0, self.wn, tau1, self.tb)
+ n = self.ln.clamp_min(1.0)
+ u0, u1 = minjerk(self.lk / n), minjerk((self.lk + 1) / n)
+ dline = (self.lp1 - self.lp0) * (u1 - u0)[:, None]
+ if self.filt: # (a CARRY abort brake keeps the cosine rule)
+ fv1, fa1, fdisp = filter_step(self.fv, self.fa, self.vn, c.wn)
+ fw1, fwa1, fydisp = filter_step(self.fw, self.fwa, self.wn, c.wn)
+ cb = self.carry_brk
+ p1 = torch.where(cb[:, None], p1 - p0, fdisp)
+ y1 = torch.where(cb, y1 - y0, fydisp)
+ p0, y0 = torch.zeros_like(p1), torch.zeros_like(y1)
+ if self.hann: # (a CARRY abort brake keeps the cosine rule)
+ hdisp, hydisp = self._hann_step()
+ cb = self.carry_brk
+ p1 = torch.where(cb[:, None], p1 - p0, hdisp)
+ y1 = torch.where(cb, y1 - y0, hydisp)
+ p0, y0 = torch.zeros_like(p1), torch.zeros_like(y1)
+ dp = torch.where(blendm[:, None], p1 - p0, torch.where(linem[:, None], dline, torch.zeros_like(dline)))
+ cline = linem & carry
+ dy = torch.where(blendm, y1 - y0, torch.where(cline, (self.ly1 - self.ly0) * (u1 - u0), torch.zeros_like(y1)))
+ pos1, yaw1, ws_clip = self._clip(self.pos + dp, self.yaw + dy, blendm)
+ # IK and the speed guard
+ rot = self._rot(yaw1)
+ q_try, ep, ea = kin.ik_track(self.q_des, pos1, rot, c.ik_iters)
+ q_try = torch.where(still[:, None], self.q_des, q_try)
+ dqb = torch.where(carry[:, None], self.dq_carry, self.dq_max) # step bound (CARRY: data 'move')
+ m = ((q_try - self.q_des).abs() / dqb).amax(-1)
+ s = torch.where(m > 1, 1 / m.clamp_min(1e-12), torch.ones_like(m))
+ guard = m > 1
+ k1 = torch.where(linem, torch.minimum(self.lk + s, n), self.lk + 1)
+ u_s = minjerk(k1 / n)
+ ratio = torch.where(linem, (u_s - u0) / (u1 - u0).clamp_min(1e-15), s)
+ ratio = torch.where(linem & ((u1 - u0) <= 1e-15), s, ratio)
+ pos_new = torch.where(linem[:, None], self.lp0 + (self.lp1 - self.lp0) * u_s[:, None],
+ self.pos + s[:, None] * (pos1 - self.pos))
+ yaw_new = torch.where(blendm, self.yaw + s * (yaw1 - self.yaw),
+ torch.where(cline, self.ly0 + (self.ly1 - self.ly0) * u_s, self.yaw))
+ q_new = self.q_des + ratio[:, None] * (q_try - self.q_des)
+ if bool((guard & ~still).any()): # a scaled step: solve again for the scaled target (push-T guard)
+ q_re, ep2, ea2 = kin.ik_track(self.q_des, pos_new, self._rot(yaw_new), c.ik_iters)
+ redo = guard & ~still
+ q_new = torch.where(redo[:, None], q_re, q_new)
+ ep, ea = torch.where(redo, ep2, ep), torch.where(redo, ea2, ea)
+ # floor: lowest collision point of the solution >= low_min
+ jc = self._jaw_check(q_meas)
+ qj = torch.cat((q_new, jc[:, None]), -1)
+ low = kin.lowest_point(qj, exact=False)
+ need = ~still & (low < c.low_min - 1e-9)
+ if bool(need.any()):
+ pos_new = pos_new + torch.where(need, c.low_min - low, torch.zeros_like(low))[:, None] * \
+ torch.tensor([0.0, 0.0, 1.0], **self.f)
+ q_fix, _, _ = kin.ik_track(q_new, pos_new, self._rot(yaw_new), c.ik_iters)
+ q_new = torch.where(need[:, None], q_fix, q_new)
+ qj = torch.cat((q_new, jc[:, None]), -1)
+ low = kin.lowest_point(qj, exact=False)
+ self.low_off = torch.where(still, self.low_off, kin.fk(qj)[0][:, 2] - low)
+ # command limiter: steps <= dq_max, step changes <= ddq_max, braking-aware
+ cprev = self.q_cmd[:, :5]
+ tv = q_new - self.q_des
+ lag = self.q_des - cprev
+ A = self.ddq_mode[mode] # [B, 5]: per-mode bound (module docstring)
+ A = torch.where(carry[:, None], self.ddq_carry, A)
+ sb = A * (torch.sqrt(0.25 + 2 * lag.abs() / A) - 0.5)
+ want = tv + torch.sign(lag) * torch.minimum(lag.abs(), sb)
+ inc = torch.minimum(torch.maximum(want, self.dq - A), self.dq + A)
+ Ab = 0.9 * A # braking margin for the discrete form of the stop law
+ lim_hi = Ab * (torch.sqrt(0.25 + 2 * (kin.thi[:5] - cprev).clamp_min(0) / Ab) - 0.5) # stop before a limit
+ lim_lo = Ab * (torch.sqrt(0.25 + 2 * (cprev - kin.tlo[:5]).clamp_min(0) / Ab) - 0.5)
+ inc = torch.minimum(torch.maximum(inc, -torch.minimum(dqb, lim_lo)), torch.minimum(dqb, lim_hi))
+ inc = torch.minimum(torch.maximum(inc, self.dq - A), self.dq + A) # the step-change bound wins
+ limited = ((inc - want).abs() > 1e-12).any(-1)
+ cnew = cprev + inc
+ # floor on the command itself: a lagging command below the floor takes the IK solution (step bounds broken)
+ low_c = kin.lowest_point(torch.cat((cnew, jc[:, None]), -1), exact=False)
+ over = (low_c < torch.minimum(low, torch.full_like(low, c.low_min)) - 1e-6)
+ cnew = torch.where(over[:, None], q_new, cnew)
+ lead_clip = torch.zeros_like(limited)
+ if q_meas is not None:
+ band = torch.minimum(torch.maximum(cnew, q_meas[:, :5] - self.lead_band), q_meas[:, :5] + self.lead_band)
+ lead_clip = ((band - cnew).abs() > 1e-12).any(-1)
+ cnew = band
+ rng = torch.minimum(torch.maximum(cnew, kin.tlo[:5]), kin.thi[:5])
+ range_clip = ((rng - cnew).abs() > 1e-12).any(-1)
+ cnew = rng
+ # jaw schedule
+ self.jaw_k = torch.minimum(self.jaw_k + 1, self.jaw_n)
+ jaw = self.jaw_from + (self.jaw_to - self.jaw_from) * minjerk(self.jaw_k / self.jaw_n)
+ jprev = self.q_cmd[:, 5]
+ jaw = (jprev + (jaw - jprev).clamp(-c.jaw_step, c.jaw_step)).clamp(float(kin.tlo[5]), float(kin.thi[5]))
+ # commit
+ self.dq = cnew - cprev
+ self.vel = (pos_new - self.pos) / CONTROL_DT
+ self.yrate = (yaw_new - self.yaw) / CONTROL_DT
+ self.pos, self.yaw, self.q_des = pos_new, yaw_new, q_new
+ self.tau = torch.where(blendm, tau1, self.tau)
+ if self.filt: # a clipped target restarts its filter at rest (anti-windup)
+ keep = (blendm & ~ws_clip)[:, None]
+ self.fv = torch.where(keep, fv1, torch.where(blendm[:, None], torch.zeros_like(fv1), self.fv))
+ self.fa = torch.where(keep, fa1, torch.where(blendm[:, None], torch.zeros_like(fa1), self.fa))
+ self.fw = torch.where(keep[:, 0], fw1, torch.where(blendm, torch.zeros_like(fw1), self.fw))
+ self.fwa = torch.where(keep[:, 0], fwa1, torch.where(blendm, torch.zeros_like(fwa1), self.fwa))
+ if self.hann: # blend clocks; a clipped target restarts at rest
+ self.hA_tau = torch.where(blendm, self.hA_tau + CONTROL_DT, self.hA_tau)
+ self.hB_tau = torch.where(blendm, self.hB_tau + CONTROL_DT, self.hB_tau)
+ self._hann_zero(blendm & ws_clip)
+ self.lk = torch.where(linem, k1, torch.where(still, self.lk + 1, self.lk))
+ self.t = self.t + 1
+ self.ik_err = torch.where(still[:, None], self.ik_err, torch.stack((ep, ea), -1))
+ self.q_cmd = torch.cat((cnew, jaw[:, None]), -1)
+ flags = dict(guard_scaled=guard & ~still, limited=limited, lead_clipped=lead_clip, floor_raised=need,
+ floor_override=over, range_clipped=range_clip, ws_clipped=ws_clip)
+ for k, v in flags.items():
+ self.counts[k] += v.long()
+ events = self._advance()
+ info = dict(flags, mode=mode, **events)
+ return self.q_cmd.clone(), info
+
+ def _advance(self):
+ """Mode transitions at the end of a step (module docstring)."""
+ mode = self.mode
+ seg = self.lk >= self.ln - 1e-9
+ brk = self.tau >= self.tb - 1e-9
+ if self.filt: # the filter has (nearly) stopped, or 1 s has passed
+ brk = (((self.fv.norm(dim=-1) < 1e-3) & (self.fw.abs() < 1e-3) & (self.fa.norm(dim=-1) < 0.02)
+ & (self.fwa.abs() < 0.05)) | (self.tau >= 1.0))
+ if self.hann: # every Hann blend has finished
+ brk = self._hann_done()
+ jaw = self.jaw_k >= self.jaw_n
+ rest = (self.dq.abs().amax(-1) < 1e-9) & ((self.q_des - self.q_cmd[:, :5]).abs().amax(-1) < 1e-9)
+ rules = (("g_brake", brk, "g_descend"), ("g_descend", seg, "g_settle"), ("g_settle", seg & rest, "g_close"),
+ ("g_close", jaw, "g_grip"), ("g_grip", seg, "g_lift"), ("g_lift", seg, "hold"),
+ ("p_brake", brk, "p_settle"), ("p_settle", seg, "p_lower"), ("p_lower", seg & rest, "p_open"),
+ ("p_open", jaw, "p_retreat"), ("p_retreat", seg, "free"))
+ moves = [((mode == M[a]) & ok, b) for a, ok, b in rules]
+ cdone = self.carry_on & (mode == M["hold"]) & seg & rest # a CARRY line ends at rest: hold again
+ bdone = self.carry_brk & (mode == M["hold"]) & (self.tau >= self.tb - 1e-9) & rest # an abort brake too
+ if bool((cdone | bdone).any()):
+ self.carry_on = self.carry_on & ~cdone
+ self.carry_brk = self.carry_brk & ~bdone
+ self._rest_motion(cdone | bdone)
+ for mask, b in moves:
+ self.mode = torch.where(mask, M[b], self.mode)
+ for mask, b in moves:
+ if bool(mask.any()):
+ self._enter(mask, b)
+ return dict(close_started=moves[2][0], grasp_done=moves[5][0], open_started=moves[8][0],
+ place_done=moves[10][0])
+
+ def _enter(self, mask, mode):
+ """Set up the segment of ``mode`` for the worlds in mask (all at rest except g_descend / p_settle after a
+ brake, which also ends at rest)."""
+ c = self.cfg
+ zero = torch.zeros_like(self.lk)
+ up = torch.tensor([0.0, 0.0, 1.0], **self.f)
+
+ def line(end, t_rng):
+ self.lp0 = torch.where(mask[:, None], self.pos, self.lp0)
+ self.lp1 = torch.where(mask[:, None], end, self.lp1)
+ self.ln = torch.where(mask, self._line_steps(self._draw(mask, t_rng), end, mode), self.ln)
+ self.lk = torch.where(mask, zero, self.lk)
+
+ def hold(t_rng):
+ self.ln = torch.where(mask, torch.round(self._draw(mask, t_rng) / CONTROL_DT), self.ln)
+ self.lk = torch.where(mask, zero, self.lk)
+
+ if mode == "g_descend":
+ line(torch.cat((self.pos[:, :2], self.z_goal[:, None]), -1), c.t_descend)
+ elif mode == "g_settle":
+ hold(c.t_settle)
+ elif mode == "g_close":
+ self._jaw_move(mask, torch.full_like(self.lk, c.jaw_closed), self._draw(mask, c.t_close))
+ elif mode == "g_grip":
+ hold(c.t_grip)
+ elif mode == "g_lift":
+ rise = torch.minimum(self.h, (self.z_ceil - self.pos[:, 2]).clamp_min(0))
+ line(self.pos + rise[:, None] * up, c.t_lift)
+ elif mode == "p_settle":
+ hold(c.t_place_settle)
+ elif mode == "p_lower":
+ line(torch.cat((self.pos[:, :2], self.z_goal[:, None]), -1), c.t_lower)
+ elif mode == "p_open":
+ self._jaw_move(mask, torch.full_like(self.lk, c.jaw_open), self._draw(mask, c.t_open))
+ elif mode == "p_retreat":
+ rise = torch.minimum(self._draw(mask, c.retreat), (c.z_max - self.pos[:, 2]).clamp_min(0))
+ line(self.pos + rise[:, None] * up, c.t_retreat)
+ if mode in ("hold", "free", "g_descend", "p_settle"): # free motion (or the macro) starts from rest
+ self._rest_motion(mask)
+ if mode == "hold":
+ self.yaw_hold0 = torch.where(mask, self.yaw, self.yaw_hold0)
+
+ def _rest_motion(self, mask):
+ """Free-motion state of the worlds in mask at rest (blends, filter, Hann blends, target velocity)."""
+ m3 = mask[:, None]
+ self.v0 = torch.where(m3, 0.0, self.v0)
+ self.vn = torch.where(m3, 0.0, self.vn)
+ self.w0 = torch.where(mask, 0.0, self.w0)
+ self.wn = torch.where(mask, 0.0, self.wn)
+ self.tau = torch.where(mask, self.T_d, self.tau)
+ self.tb = torch.where(mask, self.T_d, self.tb)
+ self.vel = torch.where(m3, 0.0, self.vel) # a macro line ends at rest (its last discrete step is not
+ self.yrate = torch.where(mask, 0.0, self.yrate) # exactly 0): the next decision blends from rest
+ for x in (self.fv, self.fa):
+ x.copy_(torch.where(m3, 0.0, x))
+ for x in (self.fw, self.fwa):
+ x.copy_(torch.where(mask, 0.0, x))
+ self._hann_zero(mask)
+
+ # ---- views --------------------------------------------------------------------------------------------------
+ @property
+ def macro_goal(self):
+ """[B, 4] end of the last GRASP descent: TCP x, y, z (m) and yaw (rad)."""
+ return self.goal
+
+ @property
+ def holding(self):
+ """[B] bool: modes in which the decoder holds the jaw closed on a cube (g_grip .. p_lower)."""
+ m = self.mode
+ return (m == M["g_grip"]) | (m == M["g_lift"]) | (m == M["hold"]) | (m == M["p_brake"]) | \
+ (m == M["p_settle"]) | (m == M["p_lower"])
+
+ def progress(self):
+ """[B] in [0, 1]: fraction of the current macro segment done (0 in free and hold)."""
+ m = self.mode
+ brk = (m == M["g_brake"]) | (m == M["p_brake"])
+ jawm = (m == M["g_close"]) | (m == M["p_open"])
+ seg = (self.lk / self.ln.clamp_min(1)).clamp(0, 1)
+ out = torch.where(brk, (self.tau / self.tb.clamp_min(1e-9)).clamp(0, 1), seg)
+ out = torch.where(jawm, self.jaw_k / self.jaw_n, out)
+ return torch.where((m == M["free"]) | ((m == M["hold"]) & ~self.carry_on), torch.zeros_like(out), out)
+
+ def macro(self):
+ """[B] long: the task's macro phase code (``MACROS`` = task.MACROS) of the current mode (``MACRO_OF_MODE``:
+ g_brake, g_descend, g_settle -> grasp_descend; hold -> free; p_brake, p_settle, p_lower -> place_lower)."""
+ if not hasattr(self, "_macro_lut"):
+ self._macro_lut = torch.tensor([MACROS.index(n) for n in MACRO_OF_MODE], dtype=torch.long, device=self.dev)
+ return self._macro_lut[self.mode]
+
+ OBS_DIM = 24
+
+ def observation(self):
+ """Decoder state for a policy [B, 24]: target TCP (3), sin and cos of the target yaw (2), target velocity (3),
+ yaw rate (1), jaw command (1), trigger armed (1), mode one-hot (13)."""
+ oh = torch.nn.functional.one_hot(self.mode, len(MODES)).to(self.pos)
+ return torch.cat((self.pos, torch.sin(self.yaw)[:, None], torch.cos(self.yaw)[:, None], self.vel,
+ self.yrate[:, None], self.q_cmd[:, 5:6], self.armed[:, None].to(self.pos), oh), -1)
+
+
+# ---- DecoderV1 (ablation) -------------------------------------------------------------------------------------
+# 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),
+# 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
+# velocity and yaw-rate commands pass a critically damped 2nd-order low pass (wn 12.5 rad/s, exact for a command held
+# over the step, the integral kept); the Cartesian target integrates it, clamped to the workspace (radius 0.10-0.32 m,
+# |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
+# tilt is blended out over 0.6 s; IK (SO101Kin.ik_track) -> arm targets with steps <= 0.06 rad and the target range;
+# the Cartesian target is pulled back to within 1 cm of the commanded pose (anti-windup); the jaw makes a minimum-jerk
+# move to the commanded end (Plan.jaw duration rule), restarted when the command flips, steps <= 0.09 rad.
+
+
+@dataclass
+class DecoderV1Config:
+ v_max: float = 0.35 # m/s, grasp-point speed (norm)
+ yaw_rate_max: float = 2.0 # rad/s
+ wn: float = 12.5 # rad/s, natural frequency of the critically damped velocity filter
+ jaw_closed: float = 0.0 # rad, firm command (the data close to -0.1245..0.05)
+ jaw_open: float = 0.7 # rad (the data open to 0.55-0.9)
+ jaw_speed: float = 4.5 # rad/s, Plan.jaw
+ jaw_min_s: float = 0.2 # s, shortest jaw move
+ arm_step: float = 0.06 # rad per step
+ jaw_step: float = 0.09 # rad per step
+ r_range: tuple = (0.10, 0.32) # m, grasp point radius about the pan axis
+ angle_max: float = 1.75 # rad, |pan angle| of the grasp point
+ z_range: tuple = (0.015, 0.22) # m, grasp point height
+ roll_max: float = 2.5 # rad, |yaw - radial direction|
+ tilt_s: float = 0.6 # s, removal of the start tilt
+ max_lead: float = 0.01 # m, Cartesian target ahead of the commanded arm pose at most
+ ik_iters: int = 3 # IK iterations per weight per step (SO101Kin.ik_track)
+
+
+class DecoderV1:
+ """Decoder v1 (ablation arm; module docstring, section DecoderV1). ``step(a) -> targets [B, 6]`` (rad, jaw last)."""
+
+ def __init__(self, num_envs, device="cpu", kin: SO101Kin | None = None, cfg: DecoderV1Config | None = None):
+ self.cfg = cfg or DecoderV1Config()
+ self.dev = torch.device(device)
+ self.kin = kin or SO101Kin(self.dev)
+ self.B = num_envs
+ f = dict(dtype=torch.float64, device=self.dev)
+ self.pos = torch.zeros(num_envs, 3, **f) # Cartesian target: grasp point (world, m)
+ self.yaw = torch.zeros(num_envs, **f) # target yaw of the closing axis (rad, not wrapped)
+ self.vel = torch.zeros(num_envs, 3, **f) # filtered velocity (m/s) and its derivative
+ self.acc = torch.zeros(num_envs, 3, **f)
+ self.yrate = torch.zeros(num_envs, **f)
+ self.yacc = torch.zeros(num_envs, **f)
+ self.tilt0 = torch.zeros(num_envs, 3, **f) # start tilt (rotation vector in the top-down frame)
+ self.t = torch.zeros(num_envs, **f) # steps since reset
+ self.q_cmd = torch.zeros(num_envs, 6, **f) # last joint targets
+ self.jaw_from = torch.zeros(num_envs, **f) # jaw minimum-jerk segment: start, end, step, length
+ self.jaw_to = torch.zeros(num_envs, **f)
+ self.jaw_k = torch.ones(num_envs, **f)
+ self.jaw_n = torch.ones(num_envs, **f)
+ self.jaw_mode = torch.full((num_envs,), -1, dtype=torch.long, device=self.dev) # -1 none, 0 open, 1 closed
+ self.ik_err = torch.zeros(num_envs, 2, **f) # position (m) and angle (rad) error of the last IK
+ self.lead = torch.zeros(num_envs, **f) # Cartesian target minus commanded arm pose (m)
+ self.pan_axis = torch.tensor(PAN_AXIS_XY, **f)
+
+ # ---- reset ---------------------------------------------------------------------------------------------
+ def reset(self, idx, q):
+ """Worlds idx (index tensor or bool mask) start holding the measured joint angles q [n, 6]."""
+ q = torch.minimum(torch.maximum(q.to(self.q_cmd), self.kin.tlo), self.kin.thi)
+ p, r = self.kin.fk(q)
+ yaw = yaw_of(r)
+ self.q_cmd[idx] = q
+ self.pos[idx], self.yaw[idx] = p, yaw
+ self.tilt0[idx] = rotvec(rotz(yaw).transpose(-1, -2) @ r)
+ for x in (self.vel, self.acc, self.yrate, self.yacc, self.t, self.ik_err, self.lead):
+ x[idx] = 0.0
+ self.jaw_from[idx], self.jaw_to[idx] = q[:, 5], q[:, 5]
+ self.jaw_k[idx], self.jaw_n[idx] = 1.0, 1.0
+ self.jaw_mode[idx] = -1
+
+ # ---- one step ------------------------------------------------------------------------------------------
+ def _filter(self, x, xd, u):
+ """Critically damped 2nd-order filter x'' = wn^2 (u - x) - 2 wn x', input held over one step ->
+ (x, x', integral of x over the step)."""
+ w, T = self.cfg.wn, CONTROL_DT
+ E = math.exp(-w * T)
+ e0 = x - u
+ x1 = u + E * (e0 * (1 + w * T) + xd * T)
+ xd1 = E * (xd * (1 - w * T) - e0 * w * w * T)
+ disp = u * T + e0 * (2 - E * (2 + w * T)) / w + xd * (1 - E * (1 + w * T)) / (w * w)
+ return x1, xd1, disp
+
+ def target_rot(self):
+ """Target gripper rotation [B, 3, 3]: top-down at the target yaw, with the start tilt blended out."""
+ lam = 1 - minjerk(self.t * CONTROL_DT / self.cfg.tilt_s)
+ return rotz(self.yaw) @ expmap(self.tilt0 * lam[:, None])
+
+ @torch.no_grad()
+ def step(self, action):
+ """action [B, 5] in [-1, 1] -> joint targets [B, 6] (rad)."""
+ c = self.cfg
+ a = action.to(self.pos).clamp(-1.0, 1.0)
+ u = a[:, :3] * c.v_max
+ n = u.norm(dim=-1, keepdim=True)
+ u = u * torch.where(n > c.v_max, c.v_max / n.clamp_min(1e-12), torch.ones_like(n))
+ self.vel, self.acc, disp = self._filter(self.vel, self.acc, u)
+ self.yrate, self.yacc, ydisp = self._filter(self.yrate, self.yacc, a[:, 3] * c.yaw_rate_max)
+ pos = self.pos + disp
+ yaw = self.yaw + ydisp
+ # workspace clamp (anti-windup: a clamped axis loses its filter state)
+ z = pos[:, 2].clamp(*c.z_range)
+ zc = z != pos[:, 2]
+ rel = pos[:, :2] - self.pan_axis
+ r = rel.norm(dim=-1)
+ ang = torch.atan2(rel[:, 1], rel[:, 0])
+ r2, ang2 = r.clamp(*c.r_range), ang.clamp(-c.angle_max, c.angle_max)
+ xyc = (r2 != r) | (ang2 != ang)
+ xy = self.pan_axis + torch.stack((torch.cos(ang2), torch.sin(ang2)), -1) * r2[:, None]
+ pos = torch.cat((xy, z[:, None]), -1)
+ roll = wrap(yaw - ang2)
+ yc = roll.abs() > c.roll_max
+ yaw = yaw - (roll - roll.clamp(-c.roll_max, c.roll_max))
+ self.vel[:, 2] = torch.where(zc, 0.0, self.vel[:, 2])
+ self.acc[:, 2] = torch.where(zc, 0.0, self.acc[:, 2])
+ self.vel[:, :2] = torch.where(xyc[:, None], 0.0, self.vel[:, :2])
+ self.acc[:, :2] = torch.where(xyc[:, None], 0.0, self.acc[:, :2])
+ self.yrate = torch.where(yc, 0.0, self.yrate)
+ self.yacc = torch.where(yc, 0.0, self.yacc)
+ self.pos, self.yaw = pos, yaw
+ self.t = self.t + 1
+ # IK, rate limit, joint range
+ q, ep, ea = self.kin.ik_track(self.q_cmd[:, :5], self.pos, self.target_rot(), c.ik_iters)
+ q = self.q_cmd[:, :5] + (q - self.q_cmd[:, :5]).clamp(-c.arm_step, c.arm_step)
+ q = torch.minimum(torch.maximum(q, self.kin.tlo[:5]), self.kin.thi[:5])
+ self.ik_err = torch.stack((ep, ea), -1)
+ p_cmd, _ = self.kin.fk(q)
+ lead = self.pos - p_cmd
+ ln = lead.norm(dim=-1, keepdim=True)
+ self.pos = p_cmd + lead * torch.where(ln > c.max_lead, c.max_lead / ln.clamp_min(1e-12), torch.ones_like(ln))
+ self.lead = ln[:, 0].clamp_max(c.max_lead)
+ # jaw: minimum-jerk move to the commanded end, restarted when the command flips
+ mode = (a[:, 4] > 0).long()
+ flip = mode != self.jaw_mode
+ goal = torch.where(mode == 1, c.jaw_closed, c.jaw_open).to(self.pos)
+ jaw = self.q_cmd[:, 5]
+ steps = torch.maximum(torch.full_like(jaw, round(c.jaw_min_s / CONTROL_DT)),
+ torch.ceil(1.875 * (goal - jaw).abs() / (c.jaw_speed * CONTROL_DT)))
+ self.jaw_from = torch.where(flip, jaw, self.jaw_from)
+ self.jaw_to = torch.where(flip, goal, self.jaw_to)
+ self.jaw_n = torch.where(flip, steps, self.jaw_n)
+ self.jaw_k = torch.where(flip, torch.zeros_like(jaw), self.jaw_k)
+ self.jaw_mode = mode
+ self.jaw_k = torch.minimum(self.jaw_k + 1, self.jaw_n)
+ j = self.jaw_from + (self.jaw_to - self.jaw_from) * minjerk(self.jaw_k / self.jaw_n)
+ j = jaw + (j - jaw).clamp(-c.jaw_step, c.jaw_step)
+ j = j.clamp(float(self.kin.tlo[5]), float(self.kin.thi[5]))
+ self.q_cmd = torch.cat((q, j[:, None]), -1)
+ return self.q_cmd.clone()
+
+ # ---- views ---------------------------------------------------------------------------------------------
+ @property
+ def jaw_done(self):
+ """[B] bool: the jaw target has reached the end of its move."""
+ return self.jaw_k >= self.jaw_n
+
+ def macro(self):
+ """None: decoder v1 has no macros (review F6). ``task.PickPlaceTask.step(state, macro=None)`` then treats every
+ step as free motion and finds the close start geometrically (the jaw closing through ``close_jaw``)."""
+ return None
+
+ @property
+ def macro_goal(self):
+ """None: no GRASP descent is planned (the task's trigger-box rule then uses the measured TCP)."""
+ return None
+
+ def observation(self):
+ """Decoder target state for a policy [B, 11]: target position (3), sin and cos of the target yaw, filtered
+ velocity (3), filtered yaw rate, jaw target (rad), jaw command (1 closed, 0 open, -1 none)."""
+ return torch.cat((self.pos, torch.sin(self.yaw)[:, None], torch.cos(self.yaw)[:, None], self.vel,
+ self.yrate[:, None], self.q_cmd[:, 5:6], self.jaw_mode[:, None].to(self.pos)), -1)
+
+
+CommandDecoder = DecoderV1 # name of the draft (01:20)
diff --git a/so101_pick_place/code/src/nedm/so101_policy/joint_env.py b/so101_pick_place/code/src/nedm/so101_policy/joint_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c5b257bdc30fed1b5c0e31438b5917ab3ae1d19
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/joint_env.py
@@ -0,0 +1,2005 @@
+"""Joint-target task env and the Markov joint teacher of build9 (``~/so101_policy/docs/build9_viral_student.md``).
+
+Why: the study's PPO teacher acts through ``decoder.DecoderV2`` (hidden macro phases, clocks, line plans that read the
+true cube pose), so its label at a state that a camera student reached is ill-defined (build8: DAgger 36 -> 1 %). The
+joint teacher ("JT") is Markov: its action at ANY state is a function of the privileged observation of that state.
+
+Observation (``OBS_DIM`` = 47): ``task.observation`` without the decoder state and macro phase (q, qd, TCP, gripper axes,
+cube position / yaw / tilt / v / w, cube in the grasp frame, relative yaw, goal, goal - cube, yaw error, the "lifted"
+flag and the held-in-air time: the last two are task-tracker values owned by the env, as VIRAL's task stage).
+
+Action (``ACT_DIM`` = 18): one decision every 0.1 s = the 5 joint targets of the next 5 control steps (20 ms) relative
+to q at the decision start, D[j] = PHI[j] @ c, c = 3 coefficients per joint (``PHI``: 1, x, (3 x^2 - 1) / 2 over
+x = -1 .. 1), normalised: c = mean + std * a (``Codec``; a in data units, no tanh). The env executes the targets
+through the ACTION LAYER (``safety``, the same for the student): each arm target clamped to the decoder's lead band
+around the MEASURED q of that step (``LEAD``, data p99.9), every target to the collector's target range, and the table
+floor (``floor_guard``: the decoder's floor rule in joint space, lowest gripper / moving-jaw point >= 1.5 mm unless the
+measured pose is already lower). Stateless: it needs only the measured q and the robot's kinematics, so the label stays
+a function of the state.
+
+``JointVecEnv``: B worlds (``vec_env.make_world``: nrd, mujoco) + ``task.PickPlaceTask`` with build8's
+macro-free rules (``tray.LOG_ONLY`` log only) + the lenient success tracker (``attach_lenient``). PPO interface of
+``ppo.PPO`` (num_envs, num_obs, num_actions, steps_per_decision, reset, step -> obs, reward, done, extras with
+action_mask / time_outs / final_obs / episode, gen, ep_count, resolved). ``step(a, targets=...)`` takes absolute
+targets [B, 5, 6] instead (student-driven rows). Auto reset from the start bank + ``task.sample_goals`` (training), or
+``reset_tasks`` (fixed tasks: evaluation, DAgger collection).
+
+Lenient success (build9 sec. 1.3): released (not held, jaw >= open_jaw, TCP >= tcp_clear above the cube top), at rest
+(speed < rest_speed, tilt <= flat_tilt, on the table), after a firm lift, the cube centre inside the goal block's square
+(|x|, |y| <= ``BLOCK_HALF`` in the block frame, any yaw), no failure rule in that step; latched per episode. The task
+still ends at strict success (15 mm / 15 deg), a failure or the time-out.
+
+Robot dynamics (real2sim, OFF by default: ``JointEnvConfig.dyn`` None): ``RobotDyn`` sits between the action layer and
+the world step of every 20 ms step and emulates the real SO101's timing and servo per world (command delay with jitter,
+weaker arm servo, first-order command lag, gravity sag of shoulder_lift / elbow with the robot guard's integral
+correction, command noise; ``RobotDynConfig``), drawn at every episode reset. ``joint_teacher.make_env`` reads a fixed
+evaluation setting from ``$NEDM_SO101_DYN``. ``RobotDynConfig.servo`` (off: {}) replaces the crude gain / lag / sag by
+the servo model fitted on the robot logs (``RealServo``: delay, lag, dead band, gravity compliance, speed limit).
+
+Goal jumps (studentlab, OFF by default: ``JointEnvConfig.goal_jump`` None): ``GoalJump`` moves the goal at the end of a
+step while the cube is held and lifted near it, so the cube ends past (or before) the new goal (``GoalJumpConfig``);
+the observation rows of those worlds are recomputed, so the next decision's teacher input, task rules and renders all
+use the moved goal.
+
+Wrist-roll cap (real2sim 2026-10-23, OFF by default: ``JointEnvConfig.roll_hi_deg`` None): the real wrist roll cannot go
+above +101.2 sim deg (the motor's calibrated range ends at +-180 real deg, real = sim + 75.8 deg; the robot guard
+clamps the roll command there), the sim target range goes to ``kin.THI[4]`` = 159.9 deg. With ``roll_hi_deg`` set
+(sim deg) the action layer's range is min(THI, cap) for the wrist roll (``safety``: the executed targets ``u_exe``,
+as the guard's ``prev``; the robot dynamics stage's actuator range), and the target sent to the world is capped once
+more after every stage (``cap_roll``; the world's own clamps ``kin.TLO`` .. ``THI`` in the NRD / MuJoCo worlds are
+wider). With a joint offset (``set_table(q_offset=...)``, evaluation only) the cap is in the policy's joint frame, as
+the guard's. The teacher's observation does not change (it reads the measured q). Start-bank rows whose wrist roll is
+above the cap are dropped (``drop_high_roll``); fixed tasks with such a start warn. Per episode the env records
+``roll_cmd_max`` (the largest commanded wrist roll, before the action layer, policy frame) and ``roll_q_max`` (the
+largest measured one) in ``extras["episode"]`` (rad).
+
+Held-cube rest starts (real2sim round v9, 2026-10-25, OFF by default: ``JointEnvConfig.rest`` None): a share of the
+automatic resets starts from a rest bank (``RestConfig``: the cube held at rest, low and far from the goal, the task's
+lifted flag and held time preset), the state where the robot student stopped on 2026-10-24. With the arm pause
+(``PauseConfig``) widened to the whole carry (``near_m`` up to 0.30 m, ``z_lo`` 0.002 m; a config change only) the
+PPO teacher learns to start again from rest.
+
+Kinematic arm-table end (real2sim round v9c, 2026-10-25, OFF by default: ``JointEnvConfig.arm_table`` None): the NRD has
+no arm-table contact; with ``ArmTableConfig`` the env raises the world's arm_table flag (the task's world_arm_table
+end) when the lowest gripper / moving-jaw collision point at q + tau x qd is below the table (before the first firm
+lift), the MuJoCo contact end of a fast grasp descent.
+
+Grasp target toward the fixed jaw (real2sim round v11, 2026-10-25, OFF by default: ``JointEnvConfig.grasp_shift``
+None): ``GraspShiftConfig`` charges the offset of the cube from a grasp target moved ``d_m`` along the closing axis
+toward the fixed jaw (cube centre wanted at hx = +d_m: nearer the middle of the open jaws, more fixed-jaw margin) at
+the moment the fingertips reach the cube-top level and at the close start (training reward only).
+
+Floor raise (real2sim round v12, 2026-10-26, OFF by default: ``JointEnvConfig.floor_raise`` None): the action layer's
+table floor is ``FLOOR`` above z = raise(xy) = c0 + c1 x + c2 y instead of above z = 0; the table, the cube, the task
+rules, the observation and the kinematic arm-table end stay at the sim table (z = 0). Why: the real table is 8-17 mm
+below the sim table relative to the arm and the robot keeps its floor flat at 1.5 mm above z = 0 of the ARM frame; a
+student distilled with the table frame map (``table_bias``: the student reads Phi(q), the joints of an arm whose world
+lies on the table plane) sees that robot floor at z = -plane(xy) in the TRUE (physics) frame, i.e. raised by the drop
+(``raise_of_table``). A flat raise (c1 = c2 = 0) is the robot's ``--table-z c0`` rule (``floor`` = FLOOR + c0); a tilted
+one measures each pose's lowest gripper / moving-jaw point from raise(x_g, y_g) at THAT pose's grasp point
+(``floor_guard`` lift): the frame map moves the whole gripper by the plane height at the grasp point, so this is the
+robot's flat arm-frame floor exactly (the guard's pull-back line is straight in the true joints, the robot's in the
+read joints: the clamped target can differ slightly where the floor acts). The PPO teacher env, the fixed-task
+envs (``joint_teacher.make_env``: teacher / student evaluations, PPO dev evaluations) and the online env
+(``viral.OnlineConfig.student_floor`` "observed") take it. ``set_table`` (MuJoCo evaluations) allows only its floor
+"zero" with a raise.
+"""
+from __future__ import annotations
+
+import copy
+import json
+import math
+import os
+from dataclasses import asdict, dataclass, field, fields, replace
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from nedm.so101_policy import task as T
+from nedm.so101_policy.paths import DATA
+from nedm.so101_policy.world import CONTROL_DT, WorldState
+
+OBS_DIM = 47
+STEPS = 5
+NB = 3
+ACT_DIM = NB * 6
+ACTION_GROUPS = (("arm", NB * 5), ("jaw", NB)) # a = c.view(3, 6) flattened: [k0 j0..j5, k1 ..., k2 ...]
+LEAD = (0.0445, 0.1235, 0.0552, 0.0559, 0.0476) # decoder lead band (rad), |cmd - q| data p99.9
+BLOCK_HALF = 0.025 # goal block half side (m): lenient success square
+LOG_ONLY = ("grasp_box", "keep_out", "cube_slide") # build8's macro-defined rules: log only
+PP_DATA = DATA / "nrd_data" / "production_plus"
+_X = (torch.arange(STEPS, dtype=torch.float64) - (STEPS - 1) / 2) / ((STEPS - 1) / 2)
+PHI = torch.stack((torch.ones_like(_X), _X, (3 * _X ** 2 - 1) / 2), -1) # [5, 3]
+
+
+# ---- action codec ------------------------------------------------------------------------------------------------
+class Codec:
+ """Normalised coefficients a [B, 18] <-> relative targets D [B, 5, 6] (module docstring)."""
+
+ def __init__(self, mean, std, device="cpu"):
+ self.dev = torch.device(device)
+ self.mean = torch.as_tensor(mean, dtype=torch.float64).reshape(NB, 6).to(self.dev)
+ self.std = torch.as_tensor(std, dtype=torch.float64).reshape(NB, 6).to(self.dev)
+ self.phi = PHI.to(self.dev)
+ self.pinv = torch.linalg.pinv(PHI).to(self.dev) # [3, 5]
+
+ @staticmethod
+ def fit(D, floor=(1e-3, 1e-3, 1e-3)):
+ """Codec from relative targets D [N, 5, 6] (float): mean / std of the least-squares coefficients."""
+ D = torch.as_tensor(D, dtype=torch.float64)
+ c = torch.einsum("kj,njd->nkd", torch.linalg.pinv(PHI), D)
+ fl = torch.as_tensor(floor, dtype=torch.float64)[:, None]
+ return Codec(c.mean(0), torch.maximum(c.std(0), fl))
+
+ def to(self, device):
+ return Codec(self.mean, self.std, device)
+
+ def state(self):
+ return dict(mean=self.mean.cpu().numpy(), std=self.std.cpu().numpy())
+
+ def coefs(self, D):
+ return torch.einsum("kj,njd->nkd", self.pinv.to(D), D)
+
+ def encode(self, D):
+ """[N, 5, 6] -> normalised a [N, 18]."""
+ return ((self.coefs(D) - self.mean.to(D)) / self.std.to(D)).reshape(D.shape[0], ACT_DIM)
+
+ def decode(self, a):
+ """normalised a [N, 18] -> relative targets [N, 5, 6]."""
+ c = self.mean.to(a) + self.std.to(a) * a.reshape(a.shape[0], NB, 6)
+ return torch.einsum("jk,nkd->njd", self.phi.to(a), c)
+
+ def targets(self, a, q):
+ """normalised a [B, 18], q [B, 6] at the decision start -> absolute targets [B, 5, 6]."""
+ return q[:, None, :].to(a) + self.decode(a)
+
+
+FLOOR = 0.0015 # m, the decoder's low_min (lowest gripper / moving-jaw point)
+# evaluation only (real2sim debugging): a weaker arm servo, as the real STS3215 (P 16): the executed arm target is moved
+# to q + s * (target - q), i.e. the position gain times s; 1 = off. Not used in training or data collection. Applied
+# after the robot dynamics stage (``RobotDyn``; the two compound; with the fitted servo ``RobotDynConfig.servo`` an
+# error: counted twice); per world and recorded: ``RobotDynConfig.s_*``.
+EVAL_KP_SCALE = float(os.environ.get("NEDM_SO101_EVAL_KP_SCALE", "1"))
+
+
+def lift_at(kin, u, lift):
+ """The floor raise (``JointEnvConfig.floor_raise``) of poses u [B, >= 5] (m): c0 + c1 x + c2 y at the pose's grasp
+ point (``kin.fk``; the arm joints only), ``lift`` = (c0, c1, c2). float64 [B]."""
+ p, _ = kin.fk(u[:, :5])
+ c0, c1, c2 = (float(c) for c in lift)
+ return c0 + c1 * p[:, 0] + c2 * p[:, 1]
+
+
+def _low(kin, u, q, plane=None, lift=None):
+ """Lowest gripper / moving-jaw collision point (m) of the arm pose u[:, :5] with the commanded and the measured jaw
+ angle (the smaller). ``plane``: height above that plane instead of world z (``table.py``). ``lift`` (c0, c1, c2):
+ minus the floor raise at the pose's grasp point (``lift_at``; None: the old code)."""
+ kw = {} if plane is None else dict(plane=plane)
+ a = kin.lowest_point(u, exact=False, **kw)
+ b = kin.lowest_point(torch.cat((u[:, :5], q[:, 5:6]), -1), exact=False, **kw)
+ if lift is None:
+ return torch.minimum(a, b)
+ return torch.minimum(a, b) - lift_at(kin, u, lift)
+
+
+def floor_guard(u, q, kin, floor=FLOOR, iters=8, plane=None, lift=None):
+ """Table floor of the action layer (the decoder's floor rule in joint space): a target whose lowest gripper /
+ moving-jaw point is below ``floor`` AND below that of the measured pose is pulled back toward the measured q along
+ the straight joint line, u' = q + lam (u - q) with the largest lam (bisection) that keeps it at or above
+ min(floor, the measured pose's lowest point). Stateless (robot kinematics + measured q). u, q [B, 6] -> [B, 6].
+ ``plane`` (c0, c1, c2): heights above the plane z = c0 + c1 x + c2 y instead of world z (a floor that follows a
+ tilted table; a flat floor at height h is ``floor`` = FLOOR + h, as the robot's ``--table-z``). ``lift`` (c0, c1,
+ c2): a tilted floor raise (``JointEnvConfig.floor_raise``): every pose's lowest point is measured from c0 + c1 x +
+ c2 y at ITS OWN grasp point (vertical), the image of the robot's flat arm-frame floor under the student's table
+ frame map (``table_bias``: the map moves the whole gripper by the plane height at the grasp point)."""
+ lu = _low(kin, u, q, plane, lift)
+ bad = lu < floor - 1e-9
+ if not bool(bad.any()):
+ return u
+ lq = _low(kin, q, q, plane, lift)
+ ref = torch.minimum(lq, torch.full_like(lq, floor))
+ bad = bad & (lu < ref - 1e-9)
+ if not bool(bad.any()):
+ return u
+ idx = bad.nonzero().flatten()
+ ub, qb, rb = u[idx], q[idx], ref[idx]
+ lo = torch.zeros(len(idx), dtype=u.dtype, device=u.device)
+ hi = torch.ones_like(lo)
+ d = torch.cat((ub[:, :5] - qb[:, :5], torch.zeros_like(ub[:, 5:])), -1)
+ base = torch.cat((qb[:, :5], ub[:, 5:]), -1)
+ for _ in range(iters):
+ mid = (lo + hi) / 2
+ ok = _low(kin, base + mid[:, None] * d, qb, plane, lift) >= rb - 1e-9
+ lo, hi = torch.where(ok, mid, lo), torch.where(ok, hi, mid)
+ out = u.clone()
+ out[idx] = base + lo[:, None] * d
+ return out
+
+
+def safety(u, q, tlo, thi, lead=None, kin=None, floor=None, floor_plane=None, floor_lift=None):
+ """The action layer of teacher AND student: arm targets within ``lead`` of the measured q, the table floor
+ (``floor_guard`` with ``kin``, if ``floor`` is given; ``floor_plane``: heights above that plane; ``floor_lift``: a
+ tilted floor raise measured at each pose's grasp point, ``floor_guard`` lift), all targets within the collector's
+ range. u, q [B, 6] -> [B, 6]."""
+ if lead is not None:
+ arm = torch.minimum(torch.maximum(u[:, :5], q[:, :5] - lead), q[:, :5] + lead)
+ u = torch.cat((arm, u[:, 5:]), -1)
+ u = torch.minimum(torch.maximum(u, tlo), thi)
+ if kin is not None and floor is not None:
+ if floor_lift is not None:
+ return floor_guard(u, q, kin, floor, plane=floor_plane, lift=floor_lift)
+ u = floor_guard(u, q, kin, floor) if floor_plane is None else floor_guard(u, q, kin, floor, plane=floor_plane)
+ return u
+
+
+# ---- robot dynamics emulation (real2sim) -------------------------------------------------------------------------
+DYN_ENV = "NEDM_SO101_DYN" # JSON ``RobotDynConfig`` of the evaluation envs (``joint_teacher.make_env``)
+SAG_JOINTS = (1, 2) # shoulder_lift, elbow: the joints that settle below their command on the robot
+_DYN_SHORT = dict(d=("d_lo", "d_hi"), s=("s_lo", "s_hi"), tau=("tau_lo", "tau_hi"),
+ sag_deg=("sag_lo_deg", "sag_max_deg"), noise=("noise_lo", "noise_max"))
+
+
+@dataclass
+class RobotDynConfig:
+ """The real SO101's timing and servo, emulated per world between the action layer and the world step (``RobotDyn``;
+ robot values: ~/so101_r2s_claude/sim_debug/scout/timing.md: q-read-to-first-target 46 ms = 2.3 steps, the robot
+ holds the previous decision's last target until the new ones are written, servo delay 80-132 ms, achieved /
+ commanded motion per decision 0.3-0.5, measured - commanded SENT +1.5 deg shoulder_lift / +1.9 deg elbow under
+ load, with the guard's 1-2.8 deg integral correction already in the sent command). Every value is drawn per world
+ at its episode reset; a world is perturbed with probability ``p`` (the others take the old path bit for bit).
+ Ranges are inclusive, lo == hi is a fixed value (evaluation). Short forms in ``from_dict`` set both ends of a
+ range: d, s, tau, sag_deg, noise. Stage order per 20 ms step: delay -> integral correction -> lag -> sag -> gain
+ -> noise -> actuator range (the lag filters the COMMAND; the gain acts on the error to the measured q of this
+ step). The sag is added before the gain, so the stage's own offset is the sag for any gain; a world with gravity
+ adds its own error at a low gain on top (MuJoCo, measured - command: s 0.1 alone +0.14 / +0.21 deg, s 0.1 with a
+ 1.7 deg sag +1.84 / +1.91 deg). The integral correction (``i_time_s`` > 0) is the robot guard's
+ (``hw_lib.GuardConfig.i_*``, robot runs: i_time_s 0.2, i_max_deg 3): without it a constant sag moves a policy
+ that commands relative to the measured q by the sag at every decision (jt_h110: 0.8 % lenient at 0.5 deg).
+ ``i_antiwindup`` (off by default; the robot guard has it on since 2026-10-24, ``hw_lib.Guard``): the integral does
+ not grow on a joint held at its actuator range (the robot: a wrist roll at its real stop wound up to +3 deg).
+ ``servo`` ({} = off): the real servo fitted on the robot logs (``RealServo``, ``servo_spec``; report
+ ~/so101_r2s_claude/sim_debug/scout/tr_servo.md), per joint fixed values or [lo, hi] ranges drawn per world and
+ episode. It REPLACES the lag / sag / gain (they must stay neutral: s 1, tau 0, sag 0, else counted twice); stage
+ order then: delay -> integral correction -> servo -> noise -> actuator range (its input is the command SENT)."""
+ p: float = 1.0 # share of perturbed worlds (per episode)
+ d_lo: int = 0 # command delay (20 ms steps), per episode U{d_lo .. d_hi}: the first d steps
+ d_hi: int = 0 # of a decision run the previous decision's last command, then u5[0 .. 4 - d]
+ jitter: float = 0.0 # per decision d + (-1, 0, +1) with probability j / 2, 1 - j, j / 2 (j = jitter)
+ delay_mode: str = "hold" # "hold": the first d steps run the previous decision's last command, then
+ # u5[0 .. 4 - d] (the last d targets are dropped); "queue": every target runs d
+ # steps late, none is dropped (the first d steps run the previous decision's
+ # targets 5 - d .. 4; VIRAL's action-delay rule; the robot loop runs all 5)
+ s_lo: float = 1.0 # arm servo gain scale, log-uniform: u_arm = q + s (u_arm - q) (jaw: unchanged)
+ s_hi: float = 1.0
+ tau_lo: float = 0.0 # first-order lag of the arm + jaw command (s), log-uniform, 0 = off:
+ tau_hi: float = 0.0 # f <- f + min(1, DT / tau) (u - f), f = the measured q at the reset
+ sag_lo_deg: float = 0.0 # static error (deg), uniform: + sag on the shoulder_lift and elbow commands
+ sag_max_deg: float = 0.0 # (measured q = command + sag, the robot's sign)
+ noise_lo: float = 0.0 # Gaussian noise on the arm commands, every step; sigma (rad) uniform per
+ noise_max: float = 0.0 # episode
+ i_time_s: float = 0.0 # integral correction of the robot guard (0 = off; arm joints, every step):
+ i_max_deg: float = 3.0 # integ += (command - q) DT / i_time_s, |integ| <= i_max_deg, only while
+ i_e_max_deg: float = 1.0 # |command - q| < i_e_max_deg and the joint does not move to its command
+ i_v_min: float = 0.02 # faster than i_v_min (rad/s); the sent command = command + integ
+ i_antiwindup: bool = False # the robot guard's anti-windup (hw_lib.Guard, 2026-10-24): no integration on
+ # a joint whose command is at its actuator range (tlo .. thi, the roll cap
+ # included) or whose corrected command would pass it; the correction is 0
+ # for a command at / beyond the range (either sign), else kept within
+ # [tlo - cmd, thi - cmd]; False = the old rule
+ servo: dict = field(default_factory=dict) # the fitted real servo (``servo_spec`` keys); {} = off
+
+ def __post_init__(self):
+ if not 0.0 <= self.p <= 1.0 or not 0.0 <= self.jitter <= 1.0:
+ raise ValueError(f"robot dyn: p {self.p}, jitter {self.jitter} must be in [0, 1]")
+ if self.delay_mode not in ("hold", "queue"):
+ raise ValueError(f"robot dyn: delay_mode {self.delay_mode!r} must be 'hold' or 'queue'")
+ if not 0 <= int(self.d_lo) <= int(self.d_hi) <= STEPS - 1:
+ raise ValueError(f"robot dyn: delay {self.d_lo} .. {self.d_hi} must be within 0 .. {STEPS - 1} steps")
+ if not 0.0 < self.s_lo <= self.s_hi:
+ raise ValueError(f"robot dyn: gain {self.s_lo} .. {self.s_hi} must be > 0, lo <= hi")
+ if not 0.0 <= self.tau_lo <= self.tau_hi or (self.tau_lo == 0.0 < self.tau_hi):
+ raise ValueError(f"robot dyn: tau {self.tau_lo} .. {self.tau_hi}: log-uniform, both > 0 (or both 0 = off)")
+ if not self.sag_lo_deg <= self.sag_max_deg or not 0.0 <= self.noise_lo <= self.noise_max:
+ raise ValueError("robot dyn: sag / noise ranges need lo <= hi (noise >= 0)")
+ if self.i_time_s < 0.0 or self.i_max_deg < 0.0 or self.i_e_max_deg < 0.0:
+ raise ValueError("robot dyn: integral correction i_time_s / i_max_deg / i_e_max_deg must be >= 0")
+ self.d_lo, self.d_hi = int(self.d_lo), int(self.d_hi)
+ if self.servo is None or self.servo is False:
+ self.servo = {}
+ if not isinstance(self.servo, dict):
+ raise ValueError(f"robot dyn: servo must be a dict ({{}} = off), got {self.servo!r}")
+ if self.servo:
+ self.servo = copy.deepcopy(self.servo)
+ servo_spec(self.servo) # raises on bad keys / values
+ if not (self.s_lo == self.s_hi == 1.0 and self.tau_hi == 0.0 and self.sag_lo_deg == self.sag_max_deg
+ == 0.0):
+ raise ValueError("robot dyn: the servo model replaces the gain s, lag tau and sag; keep them neutral "
+ "(s 1, tau 0, sag 0), else they are counted twice")
+
+ @staticmethod
+ def from_dict(d):
+ d = dict(d or {})
+ known = {f.name for f in fields(RobotDynConfig)}
+ bad = sorted(set(d) - known - set(_DYN_SHORT) - {"note"})
+ if bad:
+ raise ValueError(f"unknown robot dyn keys {bad}")
+ for k, (lo, hi) in _DYN_SHORT.items():
+ if k in d:
+ if lo in d or hi in d:
+ raise ValueError(f"robot dyn: {k!r} sets {lo} and {hi}; give one form")
+ d[lo] = d[hi] = d.pop(k)
+ return RobotDynConfig(**{k: v for k, v in d.items() if k in known})
+
+ def to_dict(self):
+ """The record (``asdict``) without the servo key while it is off and without ``i_antiwindup`` while it is
+ False: records of the old settings stay as they were (older code copies reject unknown keys in
+ ``from_dict``)."""
+ d = copy.deepcopy(asdict(self))
+ if not d["servo"]:
+ del d["servo"]
+ if not d["i_antiwindup"]:
+ del d["i_antiwindup"]
+ return d
+
+ @property
+ def neutral(self):
+ """True: every perturbed world equals the old path (no delay, gain 1, no lag, sag, noise or integral
+ correction, no servo model); ``RobotDyn`` then skips the stage (bit for bit the old step)."""
+ return (self.d_hi == 0 and self.s_lo == self.s_hi == 1.0 and self.tau_hi == 0.0 and self.sag_lo_deg ==
+ self.sag_max_deg == 0.0 and self.noise_max == 0.0 and self.i_time_s == 0.0 and not self.servo)
+
+
+def dyn_config(v) -> RobotDynConfig | None:
+ """None / False / {} / "" / "{}" / "null" -> None (off); a dict or a JSON string -> ``RobotDynConfig``."""
+ if isinstance(v, RobotDynConfig):
+ return v
+ if isinstance(v, str):
+ v = json.loads(v) if v.strip() else None
+ if v is None or v is False or (isinstance(v, dict) and not v):
+ return None
+ if not isinstance(v, dict):
+ raise ValueError(f"robot dyn: a dict / JSON object, got {v!r}")
+ return RobotDynConfig.from_dict(v)
+
+
+@dataclass
+class PauseConfig:
+ """The real robot's hold state (real2sim, 2026-10-22): on the robot the student carries the cube over the plate,
+ then the arm stands still 1-5 cm above it (qdot exactly 0) and the student never releases; in the sim the arm
+ never stands still there, so the student has no data of that state. A pause freezes the 5 arm joints at their
+ measured q for ``s_lo``-``s_hi`` s (the jaw follows its command), started at a decision where the cube is held,
+ lifted, within ``near_m`` (xy) of the goal and its bottom ``z_lo``-``z_hi`` above z = 0, with probability ``rate``
+ per decision, at most ``max_n`` times per episode, in a share ``p`` of the episodes. The JT labels the still
+ states ("descend"); after the pause the normal physics continue. Training only (``JointEnvConfig.pause``).
+ Round v9 (2026-10-25): ``near_m`` up to 0.30 and ``z_lo`` 0.002 put the pauses anywhere in the carry (the robot's
+ carry stops: 50-110 mm from the plate, cube bottom a few mm above the sim table); the defaults are unchanged."""
+ p: float = 0.5
+ s_lo: float = 0.5
+ s_hi: float = 3.0
+ near_m: float = 0.04
+ z_lo: float = 0.008
+ z_hi: float = 0.06
+ rate: float = 0.25
+ max_n: int = 2
+
+ def __post_init__(self):
+ if not (0.0 <= self.p <= 1.0 and 0.0 <= self.rate <= 1.0 and 0.0 < self.s_lo <= self.s_hi
+ and self.z_lo <= self.z_hi and self.near_m > 0 and int(self.max_n) >= 1):
+ raise ValueError(f"pause config out of range: {self}")
+ self.max_n = int(self.max_n)
+
+
+def pause_config(v) -> PauseConfig | None:
+ """None / False / {} / "" -> None (off); a dict or a JSON string -> ``PauseConfig``."""
+ if isinstance(v, PauseConfig):
+ return v
+ if isinstance(v, str):
+ v = json.loads(v) if v.strip() else None
+ if v is None or v is False or (isinstance(v, dict) and not v):
+ return None
+ d = {k: x for k, x in dict(v).items() if k != "note"}
+ bad = sorted(set(d) - {f.name for f in fields(PauseConfig)})
+ if bad:
+ raise ValueError(f"unknown pause keys {bad}")
+ return PauseConfig(**d)
+
+
+class Pause:
+ """Per-world state of ``PauseConfig`` (``JointVecEnv.step``), own generator."""
+
+ def __init__(self, cfg: PauseConfig, B, device, seed):
+ self.cfg, self.B, self.dev = cfg, int(B), torch.device(device)
+ self.gen = torch.Generator(self.dev).manual_seed(int(seed))
+ self.on = torch.zeros(B, dtype=torch.bool, device=self.dev)
+ self.n = torch.zeros(B, dtype=torch.long, device=self.dev) # pauses so far in this episode
+ self.left = torch.zeros(B, dtype=torch.long, device=self.dev) # steps left in the current pause
+ self.qh = torch.zeros(B, 6, dtype=torch.float64, device=self.dev) # the frozen arm q
+ self.started = 0 # pauses started (log)
+
+ def reset(self, idx):
+ u = torch.rand(len(idx), generator=self.gen, dtype=torch.float64, device=self.dev)
+ self.on[idx] = u < self.cfg.p
+ self.n[idx], self.left[idx] = 0, 0
+
+ def begin(self, task, q):
+ """Decision start: start a pause where the condition holds (task.F of the last step, q [B, 6] measured)."""
+ c, F = self.cfg, task.F
+ if F is None:
+ return
+ r = torch.rand(self.B, 2, generator=self.gen, dtype=torch.float64, device=self.dev)
+ dxy = (F["c"][:, :2] - task.goal_xy).norm(dim=-1)
+ zb = F["c"][:, 2] - T.CUBE_HALF
+ go = (self.on & (self.left == 0) & (self.n < c.max_n) & F["held"] & task.tr.lifted & (dxy < c.near_m)
+ & (zb >= c.z_lo) & (zb <= c.z_hi) & (r[:, 0] < c.rate))
+ if bool(go.any()):
+ steps = torch.round((c.s_lo + r[:, 1] * (c.s_hi - c.s_lo)) / CONTROL_DT).long().clamp(min=1)
+ self.left = torch.where(go, steps, self.left)
+ self.qh = torch.where(go[:, None], q.to(torch.float64), self.qh)
+ self.n = self.n + go.long()
+ self.started += int(go.sum())
+
+ def apply(self, u):
+ """One 20 ms step: the paused worlds' arm targets = the frozen q (the jaw keeps its command)."""
+ m = self.left > 0
+ if not bool(m.any()):
+ return u
+ out = torch.where(m[:, None], torch.cat((self.qh[:, :5], u[:, 5:]), -1), u)
+ self.left = (self.left - 1).clamp(min=0)
+ return out
+
+ def summary(self):
+ return dict(pause_on=round(float(self.on.double().mean()), 3),
+ pause_now=round(float((self.left > 0).double().mean()), 3), pause_started=int(self.started))
+
+
+# ---- held-cube rest starts (real2sim round v9, 2026-10-25; off by default) -----------------------------------------
+REST_STATE = ("q", "qd", "cube_pos", "cube_quat", "cube_v", "cube_w")
+REST_KEYS = ("rest_goal_xy", "rest_goal_yaw", "rest_lifted", "rest_air_s")
+
+
+@dataclass
+class RestConfig:
+ """Held-cube rest starts (real2sim round v9): on the robot of 2026-10-24 the student stopped with the cube in the
+ jaw, low (TCP 19-29 mm sim z) and 50-110 mm from the plate, and the teacher labels "stay" / "open the jaw" there:
+ with the lifted flag 1, a long held time and no arm speed a low held cube is a place state for it (step 0,
+ ~/so101_r2s_claude/v9/restart/STEP0.md: 86-91 % far drops from such starts). With this option every automatic
+ reset (``JointVecEnv._pool_reset``) is, with probability ``share``, a rest start: a row of the rest bank ``bank``
+ (.npz: the start-bank keys ``REST_STATE`` at rest + ``rest_goal_xy`` [N, 2], ``rest_goal_yaw`` [N],
+ ``rest_lifted`` [N], ``rest_air_s`` [N] (s held so far), optional ``rest_ctrl`` [N, 6]: the held targets, whose jaw
+ column becomes the robot dynamics stage's past jaw command), with the row's goal, the task's lifted flag =
+ ``rest_lifted`` and held time = ``rest_air_s`` (``JointVecEnv.set_rest``). The other resets draw their rows and goals
+ as before (the env's generator makes the same draws); the rest draws use their own generator. Rows above the
+ wrist-roll cap are dropped. Training only (start-bank worlds); fixed tasks with rest_* keys:
+ ``joint_teacher.run_tasks``."""
+ bank: str = ""
+ share: float = 0.25
+
+ def __post_init__(self):
+ if not self.bank or isinstance(self.share, bool) or not 0.0 <= float(self.share) <= 1.0:
+ raise ValueError(f"rest config: a bank path and a share in [0, 1], got {self}")
+ self.bank, self.share = str(self.bank), float(self.share)
+
+
+def rest_config(v) -> RestConfig | None:
+ """None / False / {} / "" -> None (off); a dict or a JSON string -> ``RestConfig``."""
+ if isinstance(v, RestConfig):
+ return v
+ if isinstance(v, str):
+ v = json.loads(v) if v.strip() else None
+ if v is None or v is False or (isinstance(v, dict) and not v):
+ return None
+ d = {k: x for k, x in dict(v).items() if k != "note"}
+ bad = sorted(set(d) - {f.name for f in fields(RestConfig)})
+ if bad:
+ raise ValueError(f"unknown rest keys {bad}")
+ return RestConfig(**d)
+
+
+@dataclass
+class FarOpenConfig:
+ """A dense cost on jaw-open commands while the held cube is far from the goal (real2sim round v9, 2026-10-25;
+ training reward only, off by default: ``JointEnvConfig.far_open`` None). Every 20 ms step, in live worlds whose cube
+ is held (``task.F["held"]`` of the previous step), lifted (``task.tr.lifted``) and more than ``far_m`` (xy) from the
+ goal: reward -= ``cost`` x max(0, jaw target - measured jaw) (rad; the action layer's executed jaw target ``u_exe``).
+ Why: from the held-cube rest starts (``RestConfig``) D's teacher opens the jaw far from the goal; the closed jaw is
+ 7-19 policy std away and a successful restart needs it closed for several decisions in a row, so the success reward
+ alone gave PPO no signal (tppo_restart_v9a_s31: rest dev set 10 -> 12 % in 140 iterations). The cost is a smooth
+ function of the action at every such step. It never acts at the place (within ``far_m``) or before the first lift."""
+ cost: float = 0.5
+ far_m: float = 0.04
+
+ def __post_init__(self):
+ if isinstance(self.cost, bool) or not (float(self.cost) >= 0.0 and float(self.far_m) > 0.0):
+ raise ValueError(f"far_open config: cost >= 0 and far_m > 0, got {self}")
+ self.cost, self.far_m = float(self.cost), float(self.far_m)
+
+
+def far_open_config(v) -> FarOpenConfig | None:
+ """None / False / {} / "" -> None (off); a dict or a JSON string -> ``FarOpenConfig``."""
+ if isinstance(v, FarOpenConfig):
+ return v
+ if isinstance(v, str):
+ v = json.loads(v) if v.strip() else None
+ if v is None or v is False or (isinstance(v, dict) and not v):
+ return None
+ d = {k: x for k, x in dict(v).items() if k != "note"}
+ bad = sorted(set(d) - {f.name for f in fields(FarOpenConfig)})
+ if bad:
+ raise ValueError(f"unknown far_open keys {bad}")
+ return FarOpenConfig(**d)
+
+
+@dataclass
+class ArmTableConfig:
+ """A kinematic arm-table end for worlds without an arm-table contact (the NRD; real2sim round v9c, 2026-10-25; off by
+ default: ``JointEnvConfig.arm_table`` None). After every 20 ms world step: the lowest collision point of the gripper
+ and the moving jaw (``kin.lowest_point``, the deploy guard's points; heights above the table plane if one is set) at
+ the pose extrapolated ``tau_s`` ahead with the measured joint rates, q + ``tau_s`` x qd, below ``margin_m`` -> the
+ world's ``arm_table`` flag -> the task's ``world_arm_table`` end (the failure cost of every rule), as MuJoCo's
+ contact end. ``tau_s`` 0: the pose itself. ``grasp_only``: only in worlds before their first firm lift
+ (``task.tr.lifted`` False before the step): the place descent and the held-cube rest starts are not touched.
+ Why: the restart teachers (s36_cont) lost 13-14 points of MuJoCo HOME roll 0 to arm-table ends at the grasp (22 of
+ 200 episodes, D's teacher 0): the jaw closes while the arm still descends at about 0.2 m/s, the targets sit on the
+ action layer's 1.5 mm floor and the MuJoCo arm overshoots it; the moving jaw's fingertip mesh touches the table
+ (all 22). The NRD has no arm-table pair (``nrd_sim``: arm_table all False), so PPO in the NRD never paid for it.
+ Fit on the gate rollouts (``~/so101_r2s_claude/v9/fix/teacher/``): all 22 MuJoCo ends were before the first lift.
+ margin 0, tau 0.02 s, grasp only fires on all 22 (MuJoCo states), in 87 of 200 of s36_cont's NRD HOME roll 0
+ episodes and in 3 of 200 of D's teacher's (6 of D's 193 MuJoCo successes)."""
+ margin_m: float = 0.0
+ tau_s: float = 0.02
+ grasp_only: bool = True
+
+ def __post_init__(self):
+ if not isinstance(self.grasp_only, bool):
+ raise ValueError(f"arm_table config: grasp_only must be a bool, got {self.grasp_only!r}")
+ for k in ("margin_m", "tau_s"):
+ v = getattr(self, k)
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(float(v)):
+ raise ValueError(f"arm_table config: {k} must be a finite number, got {v!r}")
+ if not (0.0 <= float(self.tau_s) <= 0.1 and -0.005 <= float(self.margin_m) <= 0.02):
+ raise ValueError(f"arm_table config: tau_s in [0, 0.1] s and margin_m in [-0.005, 0.02] m, got {self}")
+ self.margin_m, self.tau_s = float(self.margin_m), float(self.tau_s)
+
+
+def arm_table_config(v) -> ArmTableConfig | None:
+ """None / False / {} / "" -> None (off); a dict or a JSON string -> ``ArmTableConfig``."""
+ if isinstance(v, ArmTableConfig):
+ return v
+ if isinstance(v, str):
+ v = json.loads(v) if v.strip() else None
+ if v is None or v is False or (isinstance(v, dict) and not v):
+ return None
+ d = {k: x for k, x in dict(v).items() if k != "note"}
+ bad = sorted(set(d) - {f.name for f in fields(ArmTableConfig)})
+ if bad:
+ raise ValueError(f"unknown arm_table keys {bad}")
+ return ArmTableConfig(**d)
+
+
+def arm_table_rule(q, qd, kin, at: ArmTableConfig, plane=None):
+ """[B] bool: ``ArmTableConfig``'s kinematic arm-table end at the measured state (q, qd [B, 6])."""
+ q = q.to(torch.float64)
+ qx = q if at.tau_s == 0.0 else q + at.tau_s * qd.to(torch.float64)
+ low = kin.lowest_point(qx) if plane is None else kin.lowest_point(qx, plane=plane)
+ return low < at.margin_m
+
+
+@dataclass
+class GraspShiftConfig:
+ """A grasp target moved ``d_m`` along the jaw axis toward the FIXED jaw (real2sim round v11, 2026-10-25; training
+ reward only, off by default: ``JointEnvConfig.grasp_shift`` None). The cube then sits nearer the middle of the open
+ jaws: wanted offset of the cube centre from the grasp point (TCP) along the gripper's closing axis (gripper x,
+ fixed jaw -> moving jaw; ``task.features`` ``hx``: horizontal, in the gripper yaw frame) = +``d_m``.
+
+ The cost acts at two events of a live world before its first firm lift, with the cube free (not held, on the
+ table) and the TCP within ``r_m`` (xy) of the cube centre: (1) the TCP goes below ``h_m`` above the cube centre
+ (a downward crossing between two 20 ms steps; with a top-down gripper the fingertips are then at the cube-top level:
+ the moment the fixed jaw clears the cube or lands on it), (2) the measured jaw goes below ``jaw_rad`` (the close
+ start; the moving jaw has not reached the cube yet) with the TCP below ``h_m``. At each event: reward -= ``cost`` x
+ min(max(0, |hx - d_m| - ``tol_m``), ``cap_m``) (m). Event (1) does not depend on the jaw (a policy cannot avoid it by
+ a half-closed descent); event (2) measures the cube position in the open jaws at the close.
+
+ Why: on the robot the grasp fails when the fixed-jaw tip ends > 3 mm over the cube (0 / 38 held); a 30 mm cube on
+ the grasp point clears the fixed jaw by only 2.8 mm (arm model), the open moving jaw by 33 mm. In sim, a cube 3-5 mm
+ toward the moving jaw at the descent start gave +31 to +41 of 224 grasps for all 4 robot students
+ (~/so101_r2s_claude/grasp_why/). The teacher reward has no placement term: the reach potential (``task.potential``,
+ TCP xy to the cube xy) is cashed in at the first firm lift, so it does not set the grasp point, and the NRD lets
+ the fixed jaw pass through the cube top (the task's jaw_overlap rule ends it; ~/so101_r2s_claude/v11/teacher/).
+ Check before use (v11 step 2): with the cube 0-12 mm toward the moving jaw, a scripted close pushes it onto the
+ fixed jaw and holds it in MuJoCo and in the NRD (144 / 144 lifted in both; NRD in-hand x error about -2 mm)."""
+ d_m: float = 0.004
+ cost: float = 50.0
+ tol_m: float = 0.001
+ cap_m: float = 0.015
+ h_m: float = 0.028
+ r_m: float = 0.03
+ jaw_rad: float = 0.45
+
+ def __post_init__(self):
+ for k in ("d_m", "cost", "tol_m", "cap_m", "h_m", "r_m", "jaw_rad"):
+ v = getattr(self, k)
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(float(v)):
+ raise ValueError(f"grasp_shift config: {k} must be a finite number, got {v!r}")
+ setattr(self, k, float(v))
+ if not (0.0 <= self.d_m <= 0.015 and self.cost >= 0.0 and 0.0 <= self.tol_m <= 0.005
+ and 0.0 < self.cap_m <= 0.03 and 0.005 <= self.h_m <= 0.06 and 0.005 <= self.r_m <= 0.06
+ and 0.2 <= self.jaw_rad <= 0.7):
+ raise ValueError(f"grasp_shift config: d_m in [0, 0.015] m, cost >= 0, tol_m in [0, 0.005] m, cap_m in "
+ f"(0, 0.03] m, h_m and r_m in [0.005, 0.06] m, jaw_rad in [0.2, 0.7] rad, got {self}")
+
+
+def grasp_shift_config(v) -> GraspShiftConfig | None:
+ """None / False / {} / "" -> None (off); a dict or a JSON string -> ``GraspShiftConfig``."""
+ if isinstance(v, GraspShiftConfig):
+ return v
+ if isinstance(v, str):
+ v = json.loads(v) if v.strip() else None
+ if v is None or v is False or (isinstance(v, dict) and not v):
+ return None
+ d = {k: x for k, x in dict(v).items() if k != "note"}
+ bad = sorted(set(d) - {f.name for f in fields(GraspShiftConfig)})
+ if bad:
+ raise ValueError(f"unknown grasp_shift keys {bad}")
+ return GraspShiftConfig(**d)
+
+
+def grasp_height(F):
+ """[B] TCP height above the cube centre (m) of task features F."""
+ return F["tcp"][:, 2] - F["c"][:, 2]
+
+
+def grasp_shift_events(F, h_prev, jaw_prev, lifted, gs: GraspShiftConfig):
+ """``GraspShiftConfig``'s events at the state of features F (after a 20 ms step), with the previous step's TCP
+ height above the cube centre ``h_prev`` [B] and measured jaw ``jaw_prev`` [B] and the task's lifted flag before
+ the step [B] -> (descent event [B] bool, close event [B] bool, hx - d_m [B] m, TCP height now [B] m)."""
+ h = grasp_height(F)
+ free = ~F["held"] & F["on_table"] & ~lifted & (F["dxy"] < gs.r_m)
+ low = h < gs.h_m
+ e1 = free & low & (h_prev >= gs.h_m)
+ e2 = free & low & (jaw_prev >= gs.jaw_rad) & (F["jaw"] < gs.jaw_rad)
+ return e1, e2, F["hx"] - gs.d_m, h
+
+
+def grasp_shift_cost(err, gs: GraspShiftConfig):
+ """[B] cost of one event at the offset error err = hx - d_m [B] (m)."""
+ return gs.cost * (err.abs() - gs.tol_m).clamp(min=0.0, max=gs.cap_m)
+
+
+GS_STATS = ("n_descent", "hx_descent", "abs_err_descent", "n_close", "hx_close", "abs_err_close", "cost")
+
+
+def load_rest_bank(path, device) -> dict:
+ """Rest bank (``RestConfig``) -> dict of [N, ...] tensors: ``REST_STATE`` (float64), goal_xy, goal_yaw, lifted
+ (bool), air (held time in 20 ms steps, long), jaw_cmd (float64; only with ``rest_ctrl``). Refuses the sealed test
+ and a task file (``goal_xy`` key: development / fresh sets are not training starts)."""
+ p = Path(str(path)).expanduser()
+ if "test_sealed" in str(p):
+ raise ValueError("the sealed test data must not be used for starts")
+ z = np.load(p)
+ if "goal_xy" in z.files:
+ raise ValueError(f"{p}: a task file (goal_xy), not a rest bank")
+ miss = [k for k in REST_STATE + REST_KEYS if k not in z.files]
+ if miss:
+ raise ValueError(f"{p}: rest bank without {miss}")
+ f = lambda k: torch.as_tensor(np.asarray(z[k], np.float64), device=device) # noqa: E731
+ b = {k: f(k) for k in REST_STATE}
+ b.update(goal_xy=f("rest_goal_xy"), goal_yaw=f("rest_goal_yaw"),
+ lifted=torch.as_tensor(np.asarray(z["rest_lifted"], bool), device=device),
+ air=torch.round(f("rest_air_s") / CONTROL_DT).long())
+ if "rest_ctrl" in z.files:
+ b["jaw_cmd"] = f("rest_ctrl")[:, 5]
+ return b
+
+
+# ---- goal jumps (studentlab trials A2-A4, 2026-10-22; off by default) ---------------------------------------------
+@dataclass
+class GoalJumpConfig:
+ """Goal-jump coverage: states with the cube held PAST (or before) the goal, which the carry never makes on its own
+ (the real robot hovers ~19 mm past the mat centre). In a share ``p`` of the episodes, at most ``max_n`` times per
+ episode, at a decision where the cube is held, lifted (``task.tr.lifted``), its bottom ``z_lo``-``z_hi`` above the
+ table and its centre within ``near_m`` (xy) of the goal, with probability ``rate`` per such decision and at least
+ ``gap_s`` after the previous jump, the goal moves so that the cube is PAST it along the carry direction by
+ d ~ U(d_lo, d_hi) (share 1 - ``before_p``) or BEFORE it by d (share ``before_p``), plus a lateral offset
+ U(-lat_m, lat_m). Carry direction = unit vector from the cube's start xy to the goal at the episode start (radial
+ from the pan axis if they are within 1 mm). The goal yaw stays. A new goal outside the workspace annulus
+ (``task.ANNULUS_R`` / ``ANNULUS_DEG`` widened by ``margin_m``) is tried with the lateral offset mirrored, else that
+ world does not jump at this decision. ``JointVecEnv.step`` applies the jump at the END of a step (after the task
+ rules and the outcome record of that step), so from the next decision on the teacher observation, the task rules
+ (success, errors), the renderer's goal and the student's aux targets all read the moved goal (``JointVecEnv``
+ recomputes the observation rows of the worlds that jumped). Own generator: the env's other draws never change."""
+ p: float = 0.4
+ max_n: int = 2
+ rate: float = 0.35
+ gap_s: float = 1.0
+ near_m: float = 0.03
+ z_lo: float = 0.005
+ z_hi: float = 0.045
+ d_lo: float = 0.008
+ d_hi: float = 0.028
+ before_p: float = 0.2
+ lat_m: float = 0.008
+ margin_m: float = 0.01
+
+ def __post_init__(self):
+ self.max_n = int(self.max_n)
+ if not (0.0 <= self.p <= 1.0 and 0.0 <= self.rate <= 1.0 and 0.0 <= self.before_p <= 1.0 and self.max_n >= 1
+ and 0.0 <= self.d_lo <= self.d_hi and self.lat_m >= 0.0 and self.near_m > 0.0
+ and self.z_lo <= self.z_hi and self.gap_s >= 0.0 and self.margin_m >= 0.0):
+ raise ValueError(f"goal jump config out of range: {self}")
+
+ @staticmethod
+ def from_spec(spec: str, **base) -> "GoalJumpConfig":
+ """Short text form (evaluation CLI), lengths in mm: "p=1,d=10:25,lat=8[,n=1,before=0,rate=0.35,near=30,
+ z=5:45,gap=1.0,margin=10]". ``base``: defaults under the text (e.g. max_n=1, before_p=0)."""
+ kw = dict(base)
+ for part in [s.strip() for s in str(spec).split(",") if s.strip()]:
+ k, v = part.split("=", 1)
+ k = k.strip()
+ lo_hi = [float(x) for x in v.split(":")]
+ if k in ("d", "z"):
+ if len(lo_hi) != 2:
+ raise ValueError(f"goal jump spec {k}={v}: lo:hi (mm)")
+ kw[f"{k}_lo"], kw[f"{k}_hi"] = lo_hi[0] * 1e-3, lo_hi[1] * 1e-3
+ elif k in ("lat", "near", "margin"):
+ kw[f"{k}_m"] = lo_hi[0] * 1e-3
+ elif k == "n":
+ kw["max_n"] = int(lo_hi[0])
+ elif k == "before":
+ kw["before_p"] = lo_hi[0]
+ elif k in ("p", "rate", "gap"):
+ kw[{"gap": "gap_s"}.get(k, k)] = lo_hi[0]
+ else:
+ raise ValueError(f"goal jump spec: unknown key {k!r} (p, d, lat, n, before, rate, near, z, gap, margin)")
+ return GoalJumpConfig(**kw)
+
+
+def goal_jump_config(v) -> GoalJumpConfig | None:
+ """None / False / {} / "" -> None (off); a dict / JSON string -> ``GoalJumpConfig``."""
+ if isinstance(v, GoalJumpConfig):
+ return v
+ if isinstance(v, str):
+ v = json.loads(v) if v.strip() else None
+ if v is None or v is False or (isinstance(v, dict) and not v):
+ return None
+ d = {k: x for k, x in dict(v).items() if k not in ("note", "notes")}
+ bad = sorted(set(d) - {f.name for f in fields(GoalJumpConfig)})
+ if bad:
+ raise ValueError(f"unknown goal jump keys {bad}")
+ return GoalJumpConfig(**d)
+
+
+# ---- the wrist-roll cap (real2sim; off by default) -----------------------------------------------------------------
+ROLL = 4 # wrist_roll joint index
+ROLL_NEAR_DEG = 0.5 # summaries: a measured roll this close to the cap counts as "at the cap"
+
+
+def roll_hi_config(v) -> float | None:
+ """None -> None (off); a number (sim deg) -> float. Raises ValueError if not finite or at / below the target
+ range's lower end (``kin.TLO[4]``)."""
+ import numbers
+ from nedm.so101_policy.kin import TLO
+ if v is None:
+ return None
+ if not isinstance(v, numbers.Real) or isinstance(v, bool) or not math.isfinite(float(v)):
+ raise ValueError(f"roll_hi_deg {v!r}: a finite number (sim deg) or None")
+ if math.radians(float(v)) <= TLO[ROLL]:
+ raise ValueError(f"roll_hi_deg {v}: must be above the wrist roll's lower target limit "
+ f"{math.degrees(TLO[ROLL]):.1f} deg")
+ return float(v)
+
+
+FLOOR_RAISE_MAX = (0.03, 0.2, 0.2) # floor_raise limits: |c0| m, |c1|, |c2| m per m (a units guard)
+
+
+def floor_raise_config(v) -> tuple | None:
+ """``JointEnvConfig.floor_raise`` (module docstring "Floor raise"): None / False / 0 / [] / "" / all zeros -> None
+ (off); a number (m) or the string "h" -> the flat raise (h, 0, 0); a sequence (c0, c1, c2) (m, m per m) or the
+ string "c0,c1,c2" -> a tuple of floats. Raises ValueError for another length, a bool / non-finite value, or values
+ beyond ``FLOOR_RAISE_MAX`` (mm given as m)."""
+ import numbers
+ if isinstance(v, str):
+ v = v.strip()
+ v = [float(x) for x in v.split(",")] if v else None
+ v = v[0] if v is not None and len(v) == 1 else v
+ if v is None or v is False:
+ return None
+ if isinstance(v, numbers.Real) and not isinstance(v, bool):
+ v = (v, 0.0, 0.0)
+ try:
+ c = tuple(v)
+ except TypeError:
+ raise ValueError(f"floor_raise {v!r}: a height (m) or (c0, c1, c2)") from None
+ if len(c) == 0:
+ return None
+ if len(c) != 3 or any(isinstance(x, bool) or not isinstance(x, numbers.Real) or not math.isfinite(float(x))
+ for x in c):
+ raise ValueError(f"floor_raise {v!r}: a height (m) or 3 finite numbers (c0 m, c1, c2 m per m)")
+ c = tuple(float(x) + 0.0 for x in c) # (+ 0.0: no -0.0 in the record)
+ if any(abs(x) > m for x, m in zip(c, FLOOR_RAISE_MAX)):
+ raise ValueError(f"floor_raise {list(c)}: beyond |c0| {FLOOR_RAISE_MAX[0]} m, |c1|, |c2| {FLOOR_RAISE_MAX[1]} "
+ "(units: m, m per m)")
+ return None if not any(c) else c
+
+
+def raise_of_table(plane) -> tuple | None:
+ """The floor raise that puts the action-layer floor flat in the frame of a world whose table lies on ``plane``
+ (c0, c1, c2; ``table.py``, c0 < 0 = lower than the sim table): -plane (``table_bias`` frame map: the reading is
+ the true pose moved by plane(xy) at the grasp point, so the robot's flat floor z = 0 of the reading is z =
+ -plane(xy) in the true frame). None / zeros -> None."""
+ if plane is None:
+ return None
+ return floor_raise_config([-float(c) for c in plane])
+
+
+def drop_high_roll(bank: dict, hi: float):
+ """Start bank (dict of [N, ...] tensors with "q") -> (the rows whose wrist roll q[:, 4] <= hi, rows dropped). No row
+ above: the same dict (its draws do not change)."""
+ keep = ~(bank["q"][:, ROLL] > hi)
+ n = int((~keep).sum())
+ if n == 0:
+ return bank, 0
+ idx = keep.nonzero().flatten()
+ return {k: v[idx] for k, v in bank.items()}, n
+
+
+def in_workspace(xy, margin=0.0):
+ """[n, 2] goal xy -> [n] bool: on the workspace annulus of ``task.sample_annulus`` widened by ``margin`` (m)."""
+ from nedm.so101_policy.kin import PAN_AXIS_XY
+ dx, dy = xy[:, 0] - PAN_AXIS_XY[0], xy[:, 1] - PAN_AXIS_XY[1]
+ r = torch.sqrt(dx ** 2 + dy ** 2)
+ a = torch.atan2(dy, dx).abs()
+ amax = math.radians(max(abs(T.ANNULUS_DEG[0]), abs(T.ANNULUS_DEG[1]))) + margin / r.clamp_min(1e-3)
+ return (r >= T.ANNULUS_R[0] - margin) & (r <= T.ANNULUS_R[1] + margin) & (a <= amax)
+
+
+class GoalJump:
+ """Per-world state of ``GoalJumpConfig`` (``JointVecEnv``); own generator. ``just`` [B]: jumped at the end of the
+ last step; ``n`` [B]: jumps in the current episode; ``goal0`` [B, 2]: the episode's first goal; ``d_last`` /
+ ``lat_last`` [B] (m): the last jump's offset of the cube from the new goal along the carry (+ = past) / across;
+ ``z_last`` [B] (m): the cube bottom at the last jump."""
+
+ def __init__(self, cfg: GoalJumpConfig, B, device, seed):
+ self.cfg, self.B, self.dev = cfg, int(B), torch.device(device)
+ self.gen = torch.Generator(self.dev).manual_seed(int(seed))
+ f = dict(dtype=torch.float64, device=self.dev)
+ self.on = torch.zeros(B, dtype=torch.bool, device=self.dev)
+ self.n = torch.zeros(B, dtype=torch.long, device=self.dev)
+ self.last_t = torch.full((B,), -10 ** 9, dtype=torch.long, device=self.dev)
+ self.just = torch.zeros(B, dtype=torch.bool, device=self.dev)
+ self.dir = torch.zeros(B, 2, **f)
+ self.goal0 = torch.zeros(B, 2, **f)
+ self.d_last = torch.full((B,), math.nan, **f)
+ self.lat_last = torch.full((B,), math.nan, **f)
+ self.z_last = torch.full((B,), math.nan, **f) # cube bottom (m) at the last jump
+ self.jumps = 0 # jumps so far (log)
+
+ def reseed(self, seed):
+ self.gen.manual_seed(int(seed) & 0x7FFFFFFFFFFFFFFF)
+
+ def reset(self, idx, cube_xy, goal_xy):
+ """Episode start of worlds ``idx``: cube_xy, goal_xy [n, 2] of the start."""
+ from nedm.so101_policy.kin import PAN_AXIS_XY
+ u = torch.rand(len(idx), generator=self.gen, dtype=torch.float64, device=self.dev)
+ self.on[idx] = u < self.cfg.p
+ self.n[idx] = 0
+ self.last_t[idx] = -10 ** 9
+ self.just[idx] = False
+ g = torch.as_tensor(goal_xy, dtype=torch.float64, device=self.dev).reshape(-1, 2)
+ c = torch.as_tensor(cube_xy, dtype=torch.float64, device=self.dev).reshape(-1, 2)
+ v = g - c
+ nv = v.norm(dim=-1, keepdim=True)
+ rad = g - torch.tensor(PAN_AXIS_XY, dtype=torch.float64, device=self.dev)
+ rad = rad / rad.norm(dim=-1, keepdim=True).clamp_min(1e-9)
+ self.dir[idx] = torch.where(nv > 1e-3, v / nv.clamp_min(1e-9), rad)
+ self.goal0[idx] = g
+ self.d_last[idx], self.lat_last[idx], self.z_last[idx] = math.nan, math.nan, math.nan
+
+ def apply(self, task, live):
+ """End of a step (``task.F`` = this step's features): move the goal of the eligible worlds (``task.set_goal``)
+ -> long [k] indices of the worlds that jumped (empty: none). Draws B x 4 uniforms at every call."""
+ c = self.cfg
+ F, tr = task.F, task.tr
+ self.just = torch.zeros_like(self.just)
+ r = torch.rand(self.B, 4, generator=self.gen, dtype=torch.float64, device=self.dev)
+ cxy = F["c"][:, :2].to(torch.float64)
+ dxy = (cxy - task.goal_xy).norm(dim=-1)
+ zb = F["bottom"]
+ gap_ok = (tr.t - self.last_t).to(torch.float64) * CONTROL_DT >= c.gap_s - 1e-9
+ go = (self.on & live & (self.n < c.max_n) & F["held"] & tr.lifted & (dxy < c.near_m) & (zb >= c.z_lo)
+ & (zb <= c.z_hi) & gap_ok & (r[:, 0] < c.rate))
+ if not bool(go.any()):
+ return go.nonzero().flatten()
+ d = c.d_lo + r[:, 1] * (c.d_hi - c.d_lo)
+ sgn = torch.where(r[:, 2] < c.before_p, -1.0, 1.0).to(d) # +1: the cube is PAST the new goal
+ lat = (2.0 * r[:, 3] - 1.0) * c.lat_m
+ u = self.dir
+ perp = torch.stack((-u[:, 1], u[:, 0]), -1)
+ base = cxy - (sgn * d)[:, None] * u # cube - goal = sgn d u + lat perp
+ g1, g2 = base - lat[:, None] * perp, base + lat[:, None] * perp
+ ok1, ok2 = in_workspace(g1, c.margin_m), in_workspace(g2, c.margin_m)
+ go = go & (ok1 | ok2)
+ idx = go.nonzero().flatten()
+ if len(idx):
+ new = torch.where(ok1[:, None], g1, g2)[idx]
+ task.set_goal(idx, new, task.goal_yaw[idx])
+ self.n[idx] += 1
+ self.last_t[idx] = tr.t[idx]
+ self.just[idx] = True
+ self.d_last[idx] = (sgn * d)[idx]
+ self.lat_last[idx] = torch.where(ok1, lat, -lat)[idx]
+ self.z_last[idx] = zb.to(torch.float64)[idx]
+ self.jumps += len(idx)
+ return idx
+
+ def summary(self):
+ return dict(gj_on=round(float(self.on.double().mean()), 3), gj_jumps=int(self.jumps))
+
+
+def dyn_from_env() -> RobotDynConfig | None:
+ """The evaluation setting of ``$NEDM_SO101_DYN`` (JSON ``RobotDynConfig``, e.g. '{"d": 2, "s": 0.1, "tau": 0.1,
+ "sag_deg": 1.7}'); unset / empty = off."""
+ return dyn_config(os.environ.get(DYN_ENV, "").strip())
+
+
+def _log_uniform(lo, hi, u):
+ if lo == hi:
+ return torch.full_like(u, float(lo))
+ return torch.exp(math.log(lo) + u * (math.log(hi) - math.log(lo)))
+
+
+# ---- the fitted real servo (``RobotDynConfig.servo``) ----------------------------------------------------------------
+# Per joint, continuous time, exact per sub-step for the piecewise-constant command c = the command SENT (after the
+# stage's delay d and the integral correction); fitted on 12 robot + 15 teleop episodes (report
+# ~/so101_r2s_claude/sim_debug/scout/tr_servo.md; reference /tmp/claude_servo_fit/servo_emu.py plus the load-dependent
+# dead band of its sim.py):
+# r = c(t - delay) + o, o = bias - compliance (G(q) + m_cube Gc(q) held) (where the servo settles)
+# e = r - y, db = deadband + deadband_per_Nm |G(q)|
+# a still joint starts only if |e| > db + breakaway_extra, a moving joint stops once |e| <= db (+ SERVO_EPS)
+# while moving: dy/dt = clip((e - db sign e) / tau, +-vmax)
+# G, Gc: closed-form gravity torque (N m) of shoulder_lift / elbow / wrist_flex and the held-cube torque per kg at the
+# grasp point (least squares on the Menagerie MuJoCo model, residual 0.004 N m) at the MEASURED q; ``held`` = the
+# task's held flag. The output y (the emulated real joint position at the end of the step) is the target sent to the
+# world: the sim servo is stiff (MuJoCo kp 998: lag 3 ms, sag < 0.03 deg), so the world follows y within a few ms.
+# y is re-anchored per joint to the world q where they differ by more than ``reanchor_deg`` (contact, blocked jaw).
+# Held cube (``held_jaw``, default on; off = the reference): while the task's held flag is set the cube blocks the
+# jaw, so the emulated jaw cannot close past the world's jaw angle (y = max(y, q)), and while the servo squeezes
+# (its settle point below q - the dead band) the world's jaw target is that settle point (the delayed command), not y:
+# with the reference's y the jaw target is only 2.5 / 4.9 deg (alternating) past the held jaw instead of the commanded
+# ~9.6 deg; MuJoCo's grip does not change (force-saturated beyond 0.2 deg), the NRD world's does (jt_h110 on dev100:
+# 99 % lenient nominal, 97 % at a 4.9 deg gap, 35 % alternating, 0 % at 2.5 deg; the fitted jaw servo alone: 10 %
+# with the reference rule, 97 % with this one, MuJoCo 78 / 81 %; ~/so101_r2s_claude/sim_debug/servo/diag), and on
+# release the jaw opens from the held angle (the reference first runs back up from up to 4.9 deg: 0-1 step later).
+SERVO_KEYS = ("delay_ms", "tau_ms", "deadband_deg", "deadband_per_Nm_deg", "breakaway_extra_deg",
+ "compliance_rad_per_Nm", "cube_mass_kg", "bias_deg", "vmax_rad_s") # = servo_fit_params.json "proposed"
+SERVO_NEED = ("delay_ms", "tau_ms", "deadband_deg") # required keys; the others default to:
+SERVO_DEFAULT = dict(deadband_per_Nm_deg=0.0, breakaway_extra_deg=0.0, compliance_rad_per_Nm=0.0, cube_mass_kg=0.0,
+ bias_deg=0.0, vmax_rad_s=1e3) # 1e3 rad/s = no speed limit
+SERVO_LOG = ("tau_ms", "vmax_rad_s") # [lo, hi] log-uniform (the fit's randomisation)
+SERVO_OPTS = dict(n_sub=10, reanchor_deg=3.0, held_jaw=True) # sub-steps per 20 ms step, re-anchor threshold,
+ # the held-cube jaw rule (False = the reference)
+SERVO_SI = dict(delay_ms=1e-3, tau_ms=1e-3, deadband_deg=math.pi / 180, deadband_per_Nm_deg=math.pi / 180,
+ breakaway_extra_deg=math.pi / 180, compliance_rad_per_Nm=1.0, cube_mass_kg=1.0,
+ bias_deg=math.pi / 180, vmax_rad_s=1.0) # config units -> s, rad, rad / N m, kg, rad / s
+SERVO_MAX_DELAY_S = 0.25
+SERVO_EPS = 1.7e-4 # rad: a moving joint stops this far past the edge
+SERVO_SUMMARY = ("dyn_servo_still", "dyn_servo_db_deg") # ``RobotDyn.summary`` keys with the servo on
+# gravity torque (N m) of joints 1..3 and the held-cube torque (N m per kg): w . [c1 s1 c12 s12 c123 s123]
+SERVO_W_BIAS = ((-0.08956, -0.41704, -0.35361, -0.01302, -0.12852, -0.00093),
+ (0.0, 0.0, -0.35361, -0.01302, -0.12852, -0.00093),
+ (0.0, 0.0, 0.0, 0.0, -0.12852, -0.00093))
+SERVO_W_CUBE = ((-0.27491, -1.10161, -1.32276, -0.05156, -1.50263, -0.01843),
+ (0.0, 0.0, -1.32276, -0.05156, -1.50263, -0.01843),
+ (0.0, 0.0, 0.0, 0.0, -1.50263, -0.01843))
+
+
+def servo_spec(d):
+ """``RobotDynConfig.servo`` dict -> (lo, hi) float64 [len(SERVO_KEYS), 6] in SI units (``SERVO_SI``) and the options
+ (``SERVO_OPTS``). Per key: a number (every joint) or 6 entries (shoulder_pan .. gripper), each a number (fixed) or
+ [lo, hi] (drawn per world and episode: log-uniform for ``SERVO_LOG``, else uniform); cube_mass_kg: a number or
+ [lo, hi] (one draw per world). Missing keys: ``SERVO_DEFAULT`` (``SERVO_NEED`` must be given); "note" ignored.
+ Raises ValueError on unknown keys, bad shapes or ranges."""
+ import numbers
+ d = {k: v for k, v in dict(d).items() if k != "note"}
+ bad = sorted(set(d) - set(SERVO_KEYS) - set(SERVO_OPTS))
+ if bad:
+ raise ValueError(f"robot dyn servo: unknown keys {bad} (known: {list(SERVO_KEYS) + list(SERVO_OPTS)})")
+ miss = [k for k in SERVO_NEED if k not in d]
+ if miss:
+ raise ValueError(f"robot dyn servo: missing keys {miss}")
+ num = lambda x: isinstance(x, numbers.Real) and not isinstance(x, bool) # noqa: E731
+ seq = lambda x, n: isinstance(x, (list, tuple)) and len(x) == n # noqa: E731
+ lo, hi = np.zeros((len(SERVO_KEYS), 6)), np.zeros((len(SERVO_KEYS), 6))
+ for i, k in enumerate(SERVO_KEYS):
+ v = d.get(k, SERVO_DEFAULT.get(k))
+ if num(v) or (k == "cube_mass_kg" and seq(v, 2)):
+ ent = [v] * 6
+ elif seq(v, 6) and k != "cube_mass_kg":
+ ent = list(v)
+ else:
+ raise ValueError(f"robot dyn servo: {k} = {v!r}: a number, " +
+ ("or [lo, hi]" if k == "cube_mass_kg" else "or 6 entries (numbers or [lo, hi])"))
+ for j, e in enumerate(ent):
+ if num(e):
+ a = b = float(e)
+ elif seq(e, 2) and num(e[0]) and num(e[1]):
+ a, b = float(e[0]), float(e[1])
+ else:
+ raise ValueError(f"robot dyn servo: {k}[{j}] = {e!r}: a number or [lo, hi]")
+ if not (math.isfinite(a) and math.isfinite(b) and a <= b):
+ raise ValueError(f"robot dyn servo: {k}[{j}] = {e!r}: finite, lo <= hi")
+ lo[i, j], hi[i, j] = a * SERVO_SI[k], b * SERVO_SI[k]
+ K = {k: i for i, k in enumerate(SERVO_KEYS)}
+ if lo[K["delay_ms"]].min() < 0.0 or hi[K["delay_ms"]].max() > SERVO_MAX_DELAY_S:
+ raise ValueError(f"robot dyn servo: delay_ms must be within 0 .. {SERVO_MAX_DELAY_S * 1e3:g}")
+ if min(lo[K["tau_ms"]].min(), lo[K["vmax_rad_s"]].min()) <= 0.0:
+ raise ValueError("robot dyn servo: tau_ms and vmax_rad_s must be > 0")
+ for k in ("deadband_deg", "deadband_per_Nm_deg", "breakaway_extra_deg", "compliance_rad_per_Nm", "cube_mass_kg"):
+ if lo[K[k]].min() < 0.0:
+ raise ValueError(f"robot dyn servo: {k} must be >= 0")
+ opts = dict(SERVO_OPTS, **{k: d[k] for k in SERVO_OPTS if k in d})
+ if not (num(opts["n_sub"]) and int(opts["n_sub"]) == opts["n_sub"] and int(opts["n_sub"]) >= 1
+ and num(opts["reanchor_deg"]) and opts["reanchor_deg"] > 0 and isinstance(opts["held_jaw"], bool)):
+ raise ValueError(f"robot dyn servo: n_sub (int >= 1) / reanchor_deg (> 0) / held_jaw (bool): {opts}")
+ return lo, hi, dict(n_sub=int(opts["n_sub"]), reanchor_deg=float(opts["reanchor_deg"]),
+ held_jaw=bool(opts["held_jaw"]))
+
+
+def servo_gravity(q, w):
+ """q [B, 6] (sim rad) -> (G, Gc) [B, 6] float64: the gravity torque (N m) and the held-cube torque per kg (N m / kg)
+ of shoulder_lift / elbow / wrist_flex (zero for pan, wrist_roll, jaw); w = (``SERVO_W_BIAS``, ``SERVO_W_CUBE``) as
+ [3, 6] float64 tensors on q's device."""
+ a1 = q[:, 1]
+ a2 = a1 + q[:, 2]
+ a3 = a2 + q[:, 3]
+ X = torch.stack((a1.cos(), a1.sin(), a2.cos(), a2.sin(), a3.cos(), a3.sin()), -1).to(torch.float64)
+ G = torch.zeros(q.shape[0], 6, dtype=torch.float64, device=q.device)
+ Gc = torch.zeros_like(G)
+ G[:, 1:4] = X @ w[0].T
+ Gc[:, 1:4] = X @ w[1].T
+ return G, Gc
+
+
+def _servo_seed(seed):
+ return (int(seed) * 0x5851F42D + 0x5E7) & 0x7FFFFFFFFFFF
+
+
+class RealServo:
+ """Per-world state of the fitted real servo (``RobotDynConfig.servo``; the model above) for B worlds x 6 joints,
+ float64, vectorised over worlds and joints, own generator (``RobotDyn`` seeds it from its own seed, so the stage's
+ other draws do not change with the servo on). State: the emulated position y, the moving / still flag, the last
+ ``nh`` sent commands. At every reset one uniform per world, key and joint (``SERVO_KEYS`` x 6, fixed keys too), so
+ paired settings share their draws. ``step``: one 20 ms step in ``n_sub`` sub-steps, each in closed form (lag +
+ speed limit) for the command acting in that sub-step (the command of m steps ago, m = ceil((delay / h - i) / n))."""
+
+ def __init__(self, spec: dict, B, device, seed):
+ lo, hi, opts = servo_spec(spec)
+ self.B, self.dev = int(B), torch.device(device)
+ f = dict(dtype=torch.float64, device=self.dev)
+ self.lo, self.hi = torch.as_tensor(lo, **f), torch.as_tensor(hi, **f)
+ self.log = torch.tensor([k in SERVO_LOG for k in SERVO_KEYS], dtype=torch.bool, device=self.dev)[:, None]
+ self.n = int(opts["n_sub"])
+ self.h = CONTROL_DT / self.n
+ self.reanchor = math.radians(opts["reanchor_deg"])
+ self.held_jaw = bool(opts["held_jaw"])
+ self.nh = int(math.ceil(float(hi[SERVO_KEYS.index("delay_ms")].max()) / CONTROL_DT)) + 2 # history (steps)
+ self.gen = torch.Generator(self.dev).manual_seed(int(seed))
+ self.w = (torch.tensor(SERVO_W_BIAS, **f), torch.tensor(SERVO_W_CUBE, **f))
+ self.draw = torch.zeros(B, len(SERVO_KEYS), 6, **f) # per-world values (SI units, ``SERVO_KEYS``)
+ self.p = {k: torch.zeros(B, 6, **f) for k in ("delay", "tau", "db", "db1", "dbs", "kg", "kh", "b", "vmax")}
+ self.p["tau"][:], self.p["vmax"][:] = 0.04, 1e3
+ self.m = torch.zeros(B, self.n, 6, dtype=torch.long, device=self.dev) # command age per sub-step (steps)
+ self.y = torch.zeros(B, 6, **f) # the emulated real joint position
+ self.moving = torch.zeros(B, 6, dtype=torch.bool, device=self.dev)
+ self.hist = torch.zeros(B, self.nh, 6, **f) # hist[:, m] = the command sent m steps ago
+ self.fresh = torch.ones(B, dtype=torch.bool, device=self.dev) # reset since the last step: held flag stale
+
+ def reseed(self, seed):
+ self.gen.manual_seed(int(seed))
+
+ def reset(self, idx, q):
+ """Episode start of worlds ``idx`` (q [n, 6] measured): new draws; y = q, still, command history = q."""
+ n = len(idx)
+ u = torch.rand(n, len(SERVO_KEYS), 6, generator=self.gen, dtype=torch.float64, device=self.dev)
+ lo, hi = self.lo, self.hi
+ lin = lo + u * (hi - lo) # lo == hi: exactly lo
+ llo, lhi = torch.log(lo.clamp_min(1e-300)), torch.log(hi.clamp_min(1e-300))
+ v = torch.where(self.log & (hi > lo), torch.exp(llo + u * (lhi - llo)), lin)
+ km = SERVO_KEYS.index("cube_mass_kg")
+ v[:, km] = v[:, km, :1].expand(n, 6) # one cube mass per world
+ self.draw[idx] = v
+ K = {k: v[:, i] for i, k in enumerate(SERVO_KEYS)}
+ p = self.p
+ for a, k in (("delay", "delay_ms"), ("tau", "tau_ms"), ("db", "deadband_deg"), ("db1", "deadband_per_Nm_deg"),
+ ("dbs", "breakaway_extra_deg"), ("kg", "compliance_rad_per_Nm"), ("b", "bias_deg"),
+ ("vmax", "vmax_rad_s")):
+ p[a][idx] = K[k]
+ p["kh"][idx] = K["compliance_rad_per_Nm"] * K["cube_mass_kg"]
+ dsub = torch.round(K["delay_ms"] / self.h).long() # delay in sub-steps
+ i = torch.arange(self.n, device=self.dev)[None, :, None]
+ self.m[idx] = torch.div(dsub[:, None, :] - i + self.n - 1, self.n, rounding_mode="floor").clamp(0, self.nh - 1)
+ q = q.to(torch.float64)
+ self.y[idx] = q
+ self.moving[idx] = False
+ self.hist[idx] = q[:, None, :]
+ self.fresh[idx] = True
+
+ def step(self, cmd, q, held=None):
+ """One 20 ms step: cmd [B, 6] the command sent (after delay + integral correction), q [B, 6] the measured q
+ (world), held [B] bool the task's held flag (None: not held) -> the target for the world [B, 6] (y at the end
+ of the step; ``held_jaw``: a held jaw that squeezes gets the settle point instead)."""
+ p, h = self.p, self.h
+ cmd, qw = cmd.to(torch.float64), q.to(torch.float64)
+ hb = torch.zeros(self.B, dtype=torch.bool, device=self.dev) if held is None else \
+ held.to(self.dev).bool() & ~self.fresh # a reset world's flag is the old episode's
+ hf = hb.to(torch.float64)
+ self.fresh = torch.zeros_like(self.fresh)
+ self.hist = torch.cat((cmd[:, None], self.hist[:, :-1]), 1)
+ y = torch.where((self.y - qw).abs() > self.reanchor, qw, self.y)
+ if self.held_jaw: # the held cube blocks the jaw: it cannot close past the world's jaw angle
+ y = torch.cat((y[:, :5], torch.where(hb, torch.maximum(y[:, 5], qw[:, 5]), y[:, 5])[:, None]), -1)
+ G, Gc = servo_gravity(qw, self.w)
+ o = p["b"] - p["kg"] * G - p["kh"] * Gc * hf[:, None]
+ tau, vmax, dbs = p["tau"].clamp_min(1e-4), p["vmax"], p["dbs"]
+ db = p["db"] + p["db1"] * G.abs() # the dead band grows with the load
+ vt = vmax * tau
+ th_mov, th_still = db + SERVO_EPS, db + dbs # stiction: a still joint needs db + dbs
+ R = torch.gather(self.hist, 1, self.m) + o[:, None] # [B, n_sub, 6] the settle point per sub-step
+ mov = self.moving
+ for i in range(self.n):
+ r = R[:, i]
+ e = r - y
+ ae, sg = e.abs(), torch.sign(e)
+ mv = torch.where(mov, ae > th_mov, ae > th_still)
+ rp = r - db * sg # it settles at the dead band's edge
+ ep = (rp - y).abs()
+ t1 = (ep - vt) / vmax # length of the speed-limited phase
+ q_lin = y + sg * vmax * h
+ tb = t1.clamp(0.0, h)
+ qb = torch.where(ep > vt, rp - sg * vt, y) # the state after the speed-limited phase
+ q_exp = rp - (rp - qb) * torch.exp(-(h - tb) / tau)
+ y = torch.where(mv, torch.where(t1 >= h, q_lin, q_exp), y)
+ mov = mv
+ self.y, self.moving = y, mov
+ if not self.held_jaw:
+ return y
+ rj = R[:, -1, 5] # held and squeezing (settle point below the jaw angle - the dead band): the
+ sq = hb & (rj < qw[:, 5] - db[:, 5]) # world's jaw target is the settle point
+ return torch.cat((y[:, :5], torch.where(sq, rj, y[:, 5])[:, None]), -1)
+
+ def summary(self, on):
+ """``SERVO_SUMMARY`` over the worlds ``on`` [B] bool: share of still arm joints in the last step, mean arm dead
+ band (deg, without the load term)."""
+ if not bool(on.any()):
+ return dict.fromkeys(SERVO_SUMMARY, float("nan"))
+ return dict(dyn_servo_still=round(float((~self.moving[on, :5]).double().mean()), 3),
+ dyn_servo_db_deg=round(float(torch.rad2deg(self.p["db"][on, :5]).mean()), 3))
+
+
+class RobotDyn:
+ """Per-world state of ``RobotDynConfig`` for B worlds on one device (``JointVecEnv.step``). Own generator (seeded
+ from the env seed; ``reseed`` at ``reset_tasks``), so the env's other draws never change. Six uniforms per world
+ and reset (perturbed, delay, gain, tau, sag, sigma), B uniforms per decision (jitter) and B x 5 normals per step
+ (noise), all drawn whatever the ranges are, so paired settings share their draws. A neutral config
+ (``RobotDynConfig.neutral``) never activates the stage. ``servo`` (``RealServo``, None = off) has its own
+ generator: the draws above are the same with and without it."""
+ COLS = ("on", "d0", "s", "tau", "sag_deg", "sigma")
+ SUMMARY = ("dyn_on", "dyn_d0", "dyn_d", "dyn_s_p50", "dyn_tau_p50", "dyn_sag_deg", "dyn_sigma", "dyn_i_deg")
+
+ def __init__(self, cfg: RobotDynConfig, B, device, seed):
+ self.cfg, self.B, self.dev = cfg, int(B), torch.device(device)
+ self.gen = torch.Generator(self.dev).manual_seed(int(seed))
+ f, li = dict(dtype=torch.float64, device=self.dev), dict(dtype=torch.long, device=self.dev)
+ self.on = torch.zeros(B, dtype=torch.bool, device=self.dev)
+ self.d0, self.d = torch.zeros(B, **li), torch.zeros(B, **li)
+ self.s, self.tau, self.a = torch.ones(B, **f), torch.zeros(B, **f), torch.ones(B, **f)
+ self.sag, self.sigma = torch.zeros(B, **f), torch.zeros(B, **f)
+ self.hold = torch.zeros(B, 6, **f) # the previous decision's last command (held during the delay)
+ self.prev5 = torch.zeros(B, STEPS, 6, **f) # the previous decision's action-layer targets (delay_mode queue)
+ self.f = torch.zeros(B, 6, **f) # the lag filter's state
+ self.integ = torch.zeros(B, 5, **f) # the integral correction (rad, arm joints; i_time_s > 0)
+ self.active = False # any world perturbed (else ``JointVecEnv.step`` skips the stage)
+ self.eligible = None # [B] bool: worlds that may be perturbed (None = all; ``set_eligible``)
+ self.sag_idx = torch.tensor(SAG_JOINTS, dtype=torch.long, device=self.dev)
+ self.servo = RealServo(cfg.servo, B, self.dev, _servo_seed(seed)) if cfg.servo else None
+
+ def reseed(self, seed):
+ self.gen.manual_seed(int(seed) & 0x7FFFFFFFFFFFFFFF)
+ if self.servo is not None:
+ self.servo.reseed(_servo_seed(int(seed) & 0x7FFFFFFFFFFFFFFF))
+
+ def set_eligible(self, mask):
+ """Only these worlds may be perturbed (e.g. the online loop's student slots); the draws stay the same."""
+ self.eligible = None if mask is None else torch.as_tensor(mask, dtype=torch.bool, device=self.dev).clone()
+ if self.eligible is not None:
+ self.on &= self.eligible
+ self.active = bool(self.on.any()) and not self.cfg.neutral
+
+ def reset(self, idx, q):
+ """Episode start of worlds ``idx`` (q [n, 6]: their measured start q): new draws; hold and lag state = q,
+ integral correction = 0 (``Guard.reset``)."""
+ c, n = self.cfg, len(idx)
+ u = torch.rand(n, 6, generator=self.gen, dtype=torch.float64, device=self.dev)
+ self.on[idx] = (u[:, 0] < c.p) if self.eligible is None else (u[:, 0] < c.p) & self.eligible[idx]
+ self.d0[idx] = (c.d_lo + (u[:, 1] * (c.d_hi - c.d_lo + 1)).long()).clamp(max=c.d_hi)
+ self.s[idx] = _log_uniform(c.s_lo, c.s_hi, u[:, 2])
+ tau = _log_uniform(c.tau_lo, c.tau_hi, u[:, 3]) if c.tau_hi > 0 else torch.zeros_like(u[:, 3])
+ self.tau[idx] = tau
+ self.a[idx] = torch.where(tau > 0, (CONTROL_DT / tau.clamp_min(1e-12)).clamp(max=1.0), torch.ones_like(tau))
+ self.sag[idx] = torch.deg2rad(c.sag_lo_deg + u[:, 4] * (c.sag_max_deg - c.sag_lo_deg))
+ self.sigma[idx] = c.noise_lo + u[:, 5] * (c.noise_max - c.noise_lo)
+ q = q.to(torch.float64)
+ self.hold[idx], self.f[idx] = q, q
+ self.prev5[idx] = q[:, None, :].expand(-1, STEPS, -1)
+ self.integ[idx] = 0.0
+ if self.servo is not None: # the fitted servo: its own draws, emulated position = q
+ self.servo.reset(idx, q)
+ self.active = bool(self.on.any()) and not c.neutral
+
+ def begin(self):
+ """Decision start: this decision's delay d = clip(d0 + jitter, 0, STEPS - 1)."""
+ r = torch.rand(self.B, generator=self.gen, dtype=torch.float64, device=self.dev)
+ j = self.cfg.jitter
+ self.d = (self.d0 + (r >= 1.0 - j / 2).long() - (r < j / 2).long()).clamp(0, STEPS - 1)
+
+ def apply(self, j, ex, u, q, tlo, thi, qd=None, held=None):
+ """Step j of the decision: ``ex`` = the action layer's targets of steps 0 .. j (list of [B, 6]), ``u`` = ex[j],
+ q [B, 6] the measured q now, ``qd`` [B, 6] its speed (integral correction; None = not moving), ``held`` [B]
+ the task's held flag (the servo's cube term and held-cube jaw rule; None = not held; unused without the servo)
+ -> the target sent to the world [B, 6] (unperturbed rows: ``u`` itself)."""
+ B, d, c = self.B, self.d, self.cfg
+ ar = torch.arange(B, device=self.dev)
+ new = torch.stack(ex, 1)[ar, (j - d).clamp(min=0)] # u5[j - d] after the action layer
+ if c.delay_mode == "queue": # every target d steps late: the first d steps run prev5[5 - d + j]
+ old = self.prev5[ar, (STEPS - d + j).clamp(max=STEPS - 1)]
+ cmd = torch.where((d > j)[:, None], old, new)
+ if j == STEPS - 1:
+ self.prev5 = torch.stack(ex, 1).to(torch.float64)
+ else:
+ cmd = torch.where((d > j)[:, None], self.hold, new) # the first d steps: the held command
+ if j == STEPS - 1:
+ self.hold = cmd # held until the next decision's d
+ q = q.to(torch.float64)
+ if c.i_time_s > 0: # the robot guard's integral correction (hw_lib.Guard.apply, every step)
+ e = cmd[:, :5] - q[:, :5]
+ if qd is not None: # a joint that follows its command needs no correction
+ v_ = torch.nan_to_num(qd.to(torch.float64)[:, :5], 0.0, 0.0, 0.0)
+ e = torch.where(v_ * torch.sign(e) > c.i_v_min, torch.zeros_like(e), e)
+ e = torch.where(e.abs() < math.radians(c.i_e_max_deg), e, torch.zeros_like(e)) # blocked / new target
+ im = math.radians(c.i_max_deg)
+ if c.i_antiwindup: # the robot guard's anti-windup at the actuator range (RobotDynConfig)
+ lo5 = tlo[..., :5].to(torch.float64).expand(B, 5)
+ hi5 = thi[..., :5].to(torch.float64).expand(B, 5)
+ c5, w5 = cmd[:, :5], cmd[:, :5] + self.integ
+ tol = 1e-9
+ sat = (c5 >= hi5 - tol) | (c5 <= lo5 + tol) | (w5 >= hi5 - tol) | (w5 <= lo5 + tol)
+ e = torch.where(sat, torch.zeros_like(e), e)
+ new = (self.integ + e * (CONTROL_DT / c.i_time_s)).clamp(-im, im)
+ at = (c5 >= hi5 - tol) | (c5 <= lo5 + tol) # a command at / beyond the range: no correction
+ new = torch.where(at, torch.zeros_like(new), torch.minimum(torch.maximum(new, lo5 - c5), hi5 - c5))
+ self.integ = torch.where(self.on[:, None], new, self.integ)
+ else:
+ self.integ = torch.where(self.on[:, None], (self.integ + e * (CONTROL_DT / c.i_time_s)).clamp(-im, im),
+ self.integ)
+ cmd = torch.cat((cmd[:, :5] + self.integ, cmd[:, 5:]), -1)
+ if self.servo is not None: # the fitted real servo (arm + jaw) replaces the lag / sag / gain (neutral)
+ v = self.servo.step(cmd, q, held)
+ arm = v[:, :5]
+ else:
+ a = self.a[:, None]
+ self.f = torch.where(a >= 1.0, cmd, self.f + a * (cmd - self.f)) # first-order lag of the command
+ v = self.f.clone()
+ v[:, self.sag_idx] += self.sag[:, None] # static error (before the gain)
+ s = self.s[:, None]
+ arm = torch.where(s == 1.0, v[:, :5], q[:, :5] + s * (v[:, :5] - q[:, :5]))
+ arm = arm + self.sigma[:, None] * torch.randn(B, 5, generator=self.gen, dtype=torch.float64, device=self.dev)
+ out = torch.minimum(torch.maximum(torch.cat((arm, v[:, 5:]), -1), tlo), thi) # actuator range
+ return torch.where(self.on[:, None], out, u)
+
+ def params(self):
+ """[B, 6] float64 per-world draws (``COLS``; sag in deg)."""
+ return torch.stack((self.on.double(), self.d0.double(), self.s, self.tau, torch.rad2deg(self.sag), self.sigma),
+ -1)
+
+ def servo_params(self):
+ """[B, len(SERVO_KEYS), 6] float64 per-world servo draws in SI units (``SERVO_SI``); None without the servo."""
+ return None if self.servo is None else self.servo.draw
+
+ def summary(self):
+ """Compact draw statistics (perturbed share; means / medians over the perturbed worlds; the mean |integral
+ correction| in deg) for logs. Always the keys ``SUMMARY`` (NaN while no world is perturbed), so the log's
+ csv header (taken from its first row) has every column; with the servo also ``SERVO_SUMMARY``."""
+ on = self.on
+ out = dict.fromkeys(self.SUMMARY, float("nan"))
+ out["dyn_on"] = round(float(on.double().mean()), 3)
+ if bool(on.any()):
+ r = lambda x, k=3: round(float(x), k) # noqa: E731
+ out.update(dyn_d0=r(self.d0[on].double().mean()), dyn_d=r(self.d[on].double().mean()),
+ dyn_s_p50=r(self.s[on].median(), 4), dyn_tau_p50=r(self.tau[on].median(), 4),
+ dyn_sag_deg=r(torch.rad2deg(self.sag[on]).mean()), dyn_sigma=r(self.sigma[on].mean(), 5),
+ dyn_i_deg=r(torch.rad2deg(self.integ[on].abs()).mean()))
+ if self.servo is not None:
+ out.update(self.servo.summary(on))
+ return out
+
+
+# ---- lenient success ---------------------------------------------------------------------------------------------
+def lenient_now(F, cfg: T.TaskConfig, goal_xy, goal_yaw, lifted, half=BLOCK_HALF):
+ """[B] bool: the strict success conditions with the position test replaced by 'cube centre inside the goal block's
+ square of half side ``half``' and no yaw test."""
+ d = F["c"][:, :2] - goal_xy
+ c, s = torch.cos(goal_yaw), torch.sin(goal_yaw)
+ x, y = c * d[:, 0] + s * d[:, 1], -s * d[:, 0] + c * d[:, 1]
+ return (lifted & ~F["held"] & F["on_table"] & (F["tilt"] <= cfg.flat_tilt) & (F["speed"] < cfg.rest_speed)
+ & (x.abs() <= half) & (y.abs() <= half) & (F["jaw"] >= cfg.open_jaw)
+ & (F["tcp"][:, 2] >= F["c"][:, 2] + T.CUBE_HALF + cfg.tcp_clear))
+
+
+def attach_lenient(task: T.PickPlaceTask, half=BLOCK_HALF):
+ """Wrap ``task.step`` / ``task.reset`` so that ``task.lenient`` [B] bool latches the lenient success of each episode
+ (module docstring) and ``task.lenient_t`` [B] holds the step it first held (-1 never). Idempotent."""
+ if getattr(task, "_lenient_attached", False):
+ return task
+ B, dev = task.B, task.dev
+ task.lenient = torch.zeros(B, dtype=torch.bool, device=dev)
+ task.lenient_t = torch.full((B,), -1, dtype=torch.long, device=dev)
+ step0, reset0 = task.step, task.reset
+
+ def step(state, macro=None, macro_goal=None):
+ live = task.tr.end == 0
+ out = step0(state, macro, macro_goal)
+ info = out[3]
+ ok = lenient_now(task.F, task.cfg, task.goal_xy, task.goal_yaw, task.tr.lifted, half) & live & ~info["fail"]
+ new = ok & ~task.lenient
+ task.lenient_t = torch.where(new, task.tr.t, task.lenient_t)
+ task.lenient = task.lenient | ok
+ return out
+
+ def reset(idx, state, goal_xy, goal_yaw):
+ reset0(idx, state, goal_xy, goal_yaw)
+ task.lenient[idx] = False
+ task.lenient_t[idx] = -1
+
+ task.step, task.reset = step, reset
+ task._lenient_attached = True
+ return task
+
+
+# ---- observation ----------------------------------------------------------------------------------------------------
+def markov_obs(F, task: T.PickPlaceTask, idx=None, cfg: T.TaskConfig | None = None):
+ """[B, 47] float32 (module docstring) from task features F of the current state. ``cfg``: the task config of the
+ observation (default the task's; ``JointEnvConfig.hold_obs_s``)."""
+ sel = (lambda x: x) if idx is None else (lambda x: x[idx])
+ o = T.observation(F, sel(task.goal_xy), sel(task.goal_yaw), sel(task.tr.lifted), sel(task.tr.air_run),
+ task.cfg if cfg is None else cfg, None, None)
+ return o[:, :OBS_DIM]
+
+
+def hold_cap_kw(hold_cap_s=None, hold_obs_s=0.0) -> dict:
+ """``JointEnvConfig`` keywords of another hold_cap rule (``TaskConfig.hold_cap_s``: held in the air for longer
+ than this ends the episode; slow robot worlds need more time) and of the JT observation's held-time scale
+ (``hold_obs_s``; 0 with a new cap = keep the old envs' scale, the task default 3.5 s, which every evaluation and
+ online run so far gave the JT; jt_h110 itself was trained with hold_cap_s 2.5 (its env record). With the scale
+ moved to a 20 s cap jt_h110 drops from 98 to 36 % lenient in nominal NRD worlds, mostly mid-air releases).
+ None / the default and 0 -> {} (the old env)."""
+ out = {}
+ if hold_cap_s is not None and float(hold_cap_s) != T.TaskConfig.hold_cap_s:
+ out["task"] = dict(hold_cap_s=float(hold_cap_s))
+ out["hold_obs_s"] = float(hold_obs_s or T.TaskConfig.hold_cap_s)
+ elif hold_obs_s:
+ out["hold_obs_s"] = float(hold_obs_s)
+ return out
+
+
+# ---- env ------------------------------------------------------------------------------------------------------------
+@dataclass
+class JointEnvConfig:
+ world: str = "nrd"
+ num_envs: int = 4096
+ device: str = "cuda"
+ seed: int = 0
+ ckpts: list = field(default_factory=list)
+ members: object = "split"
+ nrd_cuda_graph: bool = True
+ starts: str = str(PP_DATA)
+ start_split: int = 0
+ pool_size: int = 65536
+ gamma: float = 0.99
+ horizon: int = 400
+ task: dict = field(default_factory=dict) # TaskConfig overrides
+ log_only: tuple = LOG_ONLY
+ lead_clamp: bool = True
+ floor_guard: bool = True # the table floor of the action layer (``floor_guard``)
+ codec: str = "" # .npz with mean / std (Codec)
+ auto_reset: bool = True
+ stagger: bool = True
+ block_half: float = BLOCK_HALF
+ geom_path: str = str(DATA / "rl_inputs" / "geometry" / "task_geom_v2.npz")
+ kin_points: str = str(DATA / "rl_inputs" / "geometry" / "kin_points_v1.npz")
+ mj_workers: int = 0
+ mj_python: object = None
+ mjwarp: dict = field(default_factory=dict)
+ dyn: object = None # RobotDynConfig (or its dict): robot dynamics stage; None = off
+ pause: object = None # PauseConfig (or its dict): the robot's hold state; None = off
+ hold_obs_s: float = 0.0 # held-time scale (s) of the JT observation; 0 = task hold_cap_s
+ # (``hold_cap_kw`` keeps the old envs' 3.5 s with a new cap)
+ goal_jump: object = None # GoalJumpConfig (or its dict): goal jumps; None = off
+ roll_hi_deg: object = None # wrist-roll target cap (sim deg; module docstring); None = off
+ rest: object = None # RestConfig (or its dict): held-cube rest starts; None = off
+ far_open: object = None # FarOpenConfig (or its dict): jaw-open cost far from the goal
+ arm_table: object = None # ArmTableConfig (or its dict): kinematic arm-table end
+ grasp_shift: object = None # GraspShiftConfig (or its dict): grasp target toward the
+ # fixed jaw (placement cost at the descent and the close)
+ floor_raise: object = None # (c0, c1, c2) m or a flat height: the action-layer floor
+ # 1.5 mm above z = raise(xy) (module docstring); None = off
+
+ def __post_init__(self):
+ self.dyn = dyn_config(self.dyn)
+ self.pause = pause_config(self.pause)
+ self.goal_jump = goal_jump_config(self.goal_jump)
+ self.roll_hi_deg = roll_hi_config(self.roll_hi_deg)
+ self.rest = rest_config(self.rest)
+ self.far_open = far_open_config(self.far_open)
+ self.arm_table = arm_table_config(self.arm_table)
+ self.grasp_shift = grasp_shift_config(self.grasp_shift)
+ self.floor_raise = floor_raise_config(self.floor_raise)
+
+ @staticmethod
+ def from_dict(d):
+ d = dict(d or {})
+ known = {f.name for f in fields(JointEnvConfig)}
+ bad = sorted(set(d) - known - {"note", "notes"})
+ if bad:
+ raise ValueError(f"unknown joint env config keys {bad}")
+ if "log_only" in d:
+ d["log_only"] = tuple(d["log_only"])
+ return JointEnvConfig(**{k: v for k, v in d.items() if k in known})
+
+ def to_dict(self):
+ d = copy.deepcopy(asdict(self))
+ if isinstance(self.dyn, RobotDynConfig):
+ d["dyn"] = self.dyn.to_dict() # no "servo" key while it is off (``RobotDynConfig.to_dict``)
+ if d.get("goal_jump") is None: # off: the old record (readable by code without goal jumps)
+ d.pop("goal_jump", None)
+ if d.get("roll_hi_deg") is None: # off: the old record (readable by code without the roll cap)
+ d.pop("roll_hi_deg", None)
+ if d.get("rest") is None: # off: the old record (readable by code without rest starts)
+ d.pop("rest", None)
+ if d.get("far_open") is None: # off: the old record
+ d.pop("far_open", None)
+ if d.get("arm_table") is None: # off: the old record
+ d.pop("arm_table", None)
+ if d.get("grasp_shift") is None: # off: the old record
+ d.pop("grasp_shift", None)
+ if d.get("floor_raise") is None: # off: the old record
+ d.pop("floor_raise", None)
+ else:
+ d["floor_raise"] = list(d["floor_raise"])
+ return d
+
+
+def load_codec(path, device="cpu"):
+ z = np.load(Path(path).expanduser())
+ return Codec(z["mean"], z["std"], device)
+
+
+class JointVecEnv:
+ """B task worlds with joint-target actions (module docstring)."""
+
+ def __init__(self, cfg: JointEnvConfig | dict, codec: Codec | None = None, share=None):
+ from nedm.so101_policy import vec_env as VE
+ self.cfg = cfg = JointEnvConfig.from_dict(cfg) if isinstance(cfg, dict) else cfg
+ self.dev = dev = torch.device("cpu" if cfg.world == "mujoco" else cfg.device)
+ self.B = B = int(cfg.num_envs)
+ self.num_envs, self.num_actions, self.num_obs = B, ACT_DIM, OBS_DIM
+ self.action_groups = [n for _, n in ACTION_GROUPS]
+ self.action_group_names = [g for g, _ in ACTION_GROUPS]
+ self.steps_per_decision = STEPS
+ self.kin = share.kin if share is not None else VE.kinematics(cfg.kin_points, dev)
+ self.geom = share.geom if share is not None else VE.task_geometry(cfg.geom_path, dev)
+ self.tcfg = T.TaskConfig(**{"horizon": int(cfg.horizon), "obs_rates": True, "log_only": tuple(cfg.log_only),
+ "gamma": float(cfg.gamma) ** (1.0 / STEPS), **dict(cfg.task)})
+ self.max_episode_length = math.ceil(self.tcfg.horizon / STEPS)
+ wcfg = VE.EnvConfig(world=cfg.world, num_envs=B, device=cfg.device, ckpts=list(cfg.ckpts), members=cfg.members,
+ nrd_cuda_graph=cfg.nrd_cuda_graph, starts="", mj_workers=cfg.mj_workers,
+ mj_python=cfg.mj_python, mjwarp=dict(cfg.mjwarp))
+ self.world = VE.make_world(wcfg, B, dev, self.kin, self.geom, share)
+ self.task = attach_lenient(T.PickPlaceTask(B, dev, kin=self.kin, geom=self.geom, cfg=self.tcfg,
+ overlap_rules=cfg.world != "mujoco"), cfg.block_half)
+ if codec is None:
+ if not cfg.codec:
+ raise ValueError("JointVecEnv needs a codec (cfg.codec or the argument)")
+ codec = load_codec(cfg.codec)
+ self.codec = codec.to(dev)
+ self.tlo, self.thi = self.kin.tlo.to(dev), self.kin.thi.to(dev)
+ # wrist-roll cap (module docstring; None = off): the action layer's range min(THI, cap) for the wrist roll
+ self.roll_hi = None if cfg.roll_hi_deg is None else math.radians(float(cfg.roll_hi_deg))
+ if self.roll_hi is not None:
+ self.thi = self.thi.clone() # kin.thi may be shared: never in place
+ self.thi[ROLL] = min(float(self.thi[ROLL]), self.roll_hi)
+ self.lead = torch.tensor(LEAD, dtype=torch.float64, device=dev) if cfg.lead_clamp else None
+ self.gen = torch.Generator(dev).manual_seed(int(cfg.seed))
+ if share is not None:
+ self.bank = share.bank
+ else:
+ self.bank = VE.load_starts(cfg.starts, cfg.start_split, dev) if cfg.starts and cfg.world != "mujoco" else None
+ self.roll_dropped = 0 # roll cap: start-bank rows dropped (wrist roll above the cap)
+ if self.roll_hi is not None and self.bank is not None:
+ self.bank, self.roll_dropped = drop_high_roll(self.bank, float(self.thi[ROLL]))
+ self.far_open_sum = torch.zeros((), dtype=torch.float64, device=dev) # FarOpenConfig: summed cost (log)
+ self.arm_table_n = torch.zeros((), dtype=torch.long, device=dev) # ArmTableConfig: ends by the rule (log)
+ # GraspShiftConfig (None = off): the previous step's TCP height above the cube centre and measured jaw (set at
+ # every reset), and the summed event statistics (log; GS_STATS order)
+ self.gs_h = self.gs_jaw = None
+ self.gs_stats = torch.zeros(len(GS_STATS), dtype=torch.float64, device=dev)
+ if cfg.grasp_shift is not None:
+ self.gs_h = torch.zeros(B, dtype=torch.float64, device=dev)
+ self.gs_jaw = torch.zeros(B, dtype=torch.float64, device=dev)
+ self.rest = None # held-cube rest starts (RestConfig; None = off): the bank, own generator
+ if cfg.rest is not None:
+ if self.bank is None:
+ raise ValueError("rest starts: automatic resets from a start bank only (cfg.starts, world not mujoco)")
+ self.rest, self.rest_dropped = load_rest_bank(cfg.rest.bank, dev), 0
+ if self.roll_hi is not None:
+ self.rest, self.rest_dropped = drop_high_roll(self.rest, float(self.thi[ROLL]))
+ self.rest_gen = torch.Generator(dev).manual_seed((int(cfg.seed) * 0x27D4EB2F + 0x7E5) & 0x7FFFFFFFFFFF)
+ self.rest_n, self.rest_resets = 0, 0 # rest starts / all automatic resets so far (log)
+ self.pool = None
+ f, li = dict(dtype=torch.float64, device=dev), dict(dtype=torch.long, device=dev)
+ self.ep_count = torch.zeros(B, **li)
+ self.ep_ret = torch.zeros(B, **f)
+ self.ep_len = torch.zeros(B, **li)
+ self.task_seed = torch.zeros(B, **li)
+ self.ws = None
+ self.obs = None
+ self.world_steps = 0
+ self.decisions = 0
+ self.u_exe = None # [B, 5, 6] targets executed in the last decision (after the action layer)
+ self.table_plane = None # ``set_table`` (evaluation only): the table top plane, None = z = 0
+ self.floor_plane = None # the action layer's floor plane (tilted); None = flat floor at floor_z
+ self.floor_z = 0.0 # flat floor height (m): FLOOR + floor_z (the robot script's --table-z)
+ self.q_offset = None # [6] joint offset of the policy frame (sim emulation of a joint-map offset)
+ # floor raise (JointEnvConfig.floor_raise; None = off): flat -> raise_z (added to floor_z), tilted -> raise_lift
+ # (floor_guard lift: measured at each pose's grasp point)
+ fr = cfg.floor_raise
+ self.raise_z = None if fr is None or fr[1] != 0.0 or fr[2] != 0.0 else fr[0]
+ self.raise_lift = None if fr is None or self.raise_z is not None else fr
+ # robot dynamics stage (real2sim; None = off) with its own generator, and the JT observation's held-time scale
+ self.dyn = None if cfg.dyn is None else RobotDyn(cfg.dyn, B, dev, (int(cfg.seed) * 0x9E3779B1 + 0xD1A) &
+ 0x7FFFFFFFFFFF)
+ if self.dyn is not None and self.dyn.servo is not None and EVAL_KP_SCALE != 1.0:
+ raise ValueError(f"robot dyn servo with $NEDM_SO101_EVAL_KP_SCALE = {EVAL_KP_SCALE:g}: the fitted servo "
+ "already has the real servo's softness (counted twice); unset it (1)")
+ self.pause = None if cfg.pause is None else Pause(cfg.pause, B, dev, (int(cfg.seed) * 0x2545F491 + 0x9A5) &
+ 0x7FFFFFFFFFFF)
+ self.goal_jump = None if cfg.goal_jump is None else GoalJump(cfg.goal_jump, B, dev, (int(cfg.seed) * 0x5851F42D
+ + 0x6A1) & 0x7FFFFFFFFFFF)
+ self.obs_tcfg = None
+ if cfg.hold_obs_s and float(cfg.hold_obs_s) != self.tcfg.hold_cap_s:
+ from dataclasses import replace
+ self.obs_tcfg = replace(self.tcfg, hold_cap_s=float(cfg.hold_obs_s))
+ if self.roll_hi is not None: # per episode: the largest commanded / measured wrist roll (policy frame)
+ self.roll_cmd_max = torch.full((B,), -math.inf, **f)
+ self.roll_q_max = torch.full((B,), -math.inf, **f)
+
+ # ---- the wrist-roll cap (module docstring) ------------------------------------------------------------------
+ def roll_cap(self) -> float | None:
+ """The wrist-roll cap of the target sent to the world (rad, world frame: the action layer's cap minus the joint
+ offset of ``set_table``), None = off."""
+ if self.roll_hi is None:
+ return None
+ hi = float(self.thi[ROLL])
+ return hi if self.q_offset is None else hi - float(self.q_offset[ROLL])
+
+ def cap_roll(self, u):
+ """Targets [..., 6] (world frame) -> a new tensor with the wrist roll <= ``roll_cap()``; off: ``u`` itself."""
+ c = self.roll_cap()
+ if c is None:
+ return u
+ return torch.cat((u[..., :ROLL], u[..., ROLL:ROLL + 1].clamp(max=c), u[..., ROLL + 1:]), -1)
+
+ def roll_info(self) -> dict | None:
+ """The cap for output files (None = off): sim deg, the action layer's cap (rad), start-bank rows dropped."""
+ if self.roll_hi is None:
+ return None
+ return dict(roll_hi_deg=float(self.cfg.roll_hi_deg), cap_rad=float(self.thi[ROLL]),
+ bank_dropped=int(self.roll_dropped))
+
+ def resolved(self) -> dict:
+ return dict(env=self.cfg.to_dict(), task=asdict(self.tcfg), codec={k: v.tolist() for k, v in
+ self.codec.state().items()},
+ num_obs=self.num_obs, num_actions=self.num_actions,
+ action_groups=list(zip(self.action_group_names, self.action_groups)), kind="joint_env")
+
+ # ---- a table that is not at z = 0 (evaluation only; ``table.py``) --------------------------------------------
+ def set_table(self, plane=None, floor="zero", q_offset=None):
+ """The table top on the plane z = c0 + c1 x + c2 y (None: z = 0, the old env): the CPU MuJoCo table geom, the
+ task starts (``reset_tasks``: the cube moved onto the plane before the warm-up, ``table.map_cube``), and the
+ task rules (heights above the plane: on the table, lift, release, lowest arm point; ``task.features``).
+ ``floor``: the action layer's table floor (lowest gripper / moving-jaw point >= FLOOR above it): "zero" (z = 0,
+ the default and the robot script's default --table-z 0), "table" (follows the table: a flat table -> FLOOR +
+ dz, as --table-z dz; a tilted plane -> heights above the plane, sim only), or a float = a flat floor at that
+ z (--table-z). ``q_offset`` [6] (rad): the policy and the action layer work in a joint frame q + q_offset
+ (the targets are mapped back by - q_offset; the world and the task stay true): a sim emulation of an extra
+ joint-map offset on the robot. World mujoco only."""
+ from nedm.so101_policy import table as TB
+ if self.cfg.world != "mujoco":
+ raise ValueError("set_table: CPU MuJoCo worlds only")
+ if self.cfg.floor_raise is not None and floor != "zero":
+ raise ValueError(f"set_table floor {floor!r} with floor_raise {list(self.cfg.floor_raise)}: one floor "
+ "rule at a time (floor 'zero' + the raise, or no raise)")
+ plane = None if plane is None or not any(plane) else tuple(float(c) for c in plane)
+ self.table_plane = plane
+ self.task.table_plane = plane
+ self.world.set_table(plane)
+ self.floor_plane, self.floor_z = None, 0.0
+ if isinstance(floor, (int, float)) and not isinstance(floor, bool):
+ self.floor_z = float(floor)
+ elif floor == "table":
+ if TB.is_flat(plane):
+ self.floor_z = 0.0 if plane is None else plane[0]
+ else:
+ self.floor_plane = plane
+ elif floor != "zero":
+ raise ValueError(f"floor {floor!r}: 'zero', 'table' or a height (m)")
+ self.q_offset = None if q_offset is None or not any(q_offset) else \
+ torch.as_tensor(q_offset, dtype=torch.float64, device=self.dev)
+ return dict(plane=plane, floor_plane=self.floor_plane, floor_z=self.floor_z,
+ q_offset=None if self.q_offset is None else self.q_offset.tolist(), table=self.world.table)
+
+ def floor_gap(self, q=None):
+ """Height (m) of the measured pose's lowest gripper / moving-jaw point above the action layer's floor, the
+ quantity ``floor_guard`` compares (``_low`` with the floor plane / the tilted floor raise, in the policy's
+ joint frame) minus the floor (FLOOR + floor_z + the flat floor raise); negative = below the floor (the guard
+ lets a target go as low as a measured pose that sags: the "floor creep", v12 review finding 2). q [B, 6]
+ (default the world's measured q) -> float64 [B]."""
+ q = (self.ws.q if q is None else q).to(device=self.dev, dtype=torch.float64)
+ if self.q_offset is not None:
+ q = q + self.q_offset
+ fz = self.floor_z if self.raise_z is None else self.floor_z + self.raise_z
+ return _low(self.kin, q, q, self.floor_plane, self.raise_lift) - (FLOOR + fz)
+
+ def table_info(self) -> dict:
+ out = dict(plane=self.table_plane, floor_plane=self.floor_plane, floor_z=self.floor_z,
+ q_offset=None if self.q_offset is None else self.q_offset.tolist())
+ if self.cfg.floor_raise is not None: # (off: the old keys)
+ out["floor_raise"] = list(self.cfg.floor_raise)
+ return out
+
+ def dyn_info(self) -> dict | None:
+ """The robot dynamics setting (``RobotDynConfig`` as a dict) + the per-world draws of the current episodes
+ (``RobotDyn.COLS``) + the hold cap / observation scale; None = off (evaluation files: the "dyn" key). With the
+ fitted servo also its per-world draws ``servo_params`` [B, len(SERVO_KEYS), 6] (SI units, ``servo_keys``)."""
+ if self.dyn is None:
+ return None
+ out = dict(cfg=self.dyn.cfg.to_dict(), cols=list(RobotDyn.COLS), params=self.dyn.params().cpu().tolist(),
+ hold_cap_s=self.tcfg.hold_cap_s, hold_obs_s=float(self.cfg.hold_obs_s), kp_scale=EVAL_KP_SCALE)
+ if self.dyn.servo is not None:
+ out.update(servo_keys=list(SERVO_KEYS), servo_params=self.dyn.servo_params().cpu().tolist())
+ return out
+
+ # ---- tasks -------------------------------------------------------------------------------------------------
+ def refresh_pool(self, n=None):
+ if self.bank is None:
+ raise RuntimeError("no start bank (world mujoco: use reset_tasks)")
+ n = int(n or self.cfg.pool_size)
+ N = self.bank["q"].shape[0]
+ i = torch.randint(N, (n,), generator=self.gen, device=self.dev)
+ yaw, _ = T.cube_yaw_tilt(self.bank["cube_quat"][i])
+ gxy, gyaw = T.sample_goals(self.bank["cube_pos"][i, :2], yaw, self.gen)
+ self.pool = dict(i=i, goal_xy=gxy, goal_yaw=gyaw)
+
+ def _reset_rows(self, idx, start: WorldState, goal_xy, goal_yaw, seeds, mj_start=None):
+ if self.cfg.world == "mujoco":
+ ws = self.world.reset(idx.cpu(), mj_start, warmup=True)
+ elif self.cfg.world == "mjwarp":
+ ws = self.world.reset(idx, start, warmup=False)
+ else:
+ ws = self.world.reset(idx, start)
+ self.ws = ws.to(self.dev)
+ self.task.reset(idx, self.ws.index(idx), goal_xy, goal_yaw)
+ if self.gs_h is not None: # GraspShiftConfig: the start state is the first "previous step"
+ F0 = T.features(self.ws.index(idx), self.kin, None, self.tcfg)
+ self.gs_h[idx], self.gs_jaw[idx] = grasp_height(F0), F0["jaw"]
+ self.task_seed[idx] = seeds
+ self.ep_ret[idx], self.ep_len[idx] = 0.0, 0
+ if self.dyn is not None: # robot dynamics: new draws, hold / lag state = the measured start q
+ self.dyn.reset(idx, self.ws.q[idx])
+ if self.pause is not None:
+ self.pause.reset(idx)
+ if self.goal_jump is not None: # goal jumps: per-episode draw, carry direction start cube -> goal
+ self.goal_jump.reset(idx, self.ws.cube_pos[idx, :2], goal_xy)
+ if self.roll_hi is not None: # roll cap records: the measured start roll (policy frame), no command yet
+ r0 = self.ws.q[idx, ROLL].to(torch.float64) + (0.0 if self.q_offset is None else self.q_offset[ROLL])
+ self.roll_q_max[idx] = r0.nan_to_num(-math.inf)
+ self.roll_cmd_max[idx] = -math.inf
+
+ def _pool_reset(self, idx):
+ from nedm.so101_policy.vec_env import start_rows
+ if self.pool is None:
+ self.refresh_pool()
+ k = torch.randint(len(self.pool["i"]), (len(idx),), generator=self.gen, device=self.dev)
+ i = self.pool["i"][k]
+ s = (int(self.cfg.seed) * 0x9E3779B1 + self.ep_count[idx] * self.B + idx) & 0xFFFFFFFF
+ self.ep_count[idx] += 1
+ if self.rest is None:
+ self._reset_rows(idx, start_rows(self.bank, i), self.pool["goal_xy"][k], self.pool["goal_yaw"][k], s)
+ return
+ # held-cube rest starts (RestConfig): a share of the rows from the rest bank; the others as above (same draws)
+ r = torch.rand(len(idx), generator=self.rest_gen, dtype=torch.float64, device=self.dev) < self.cfg.rest.share
+ n = ~r
+ if bool(n.any()):
+ self._reset_rows(idx[n], start_rows(self.bank, i[n]), self.pool["goal_xy"][k[n]],
+ self.pool["goal_yaw"][k[n]], s[n])
+ if bool(r.any()):
+ ri, R = idx[r], self.rest
+ j = torch.randint(len(R["q"]), (len(ri),), generator=self.rest_gen, device=self.dev)
+ self._reset_rows(ri, start_rows(R, j), R["goal_xy"][j], R["goal_yaw"][j], s[r])
+ self.set_rest(ri, R["lifted"][j], R["air"][j], R["jaw_cmd"][j] if "jaw_cmd" in R else None)
+ self.rest_n += int(r.sum())
+ self.rest_resets += len(idx)
+
+ def set_rest(self, idx, lifted, air_steps, jaw_cmd=None):
+ """Worlds ``idx`` (just reset) start at rest with the cube in the jaw (``RestConfig``; fixed tasks:
+ ``joint_teacher.run_tasks``): the task's lifted flag ``lifted`` [n] bool, the held time ``air_steps`` [n] (20 ms
+ steps, the tracker's ``air_run``: the JT observation's held-time input), held now (``since_release`` 0); with
+ the robot dynamics stage its past jaw commands = ``jaw_cmd`` [n] (rad: the closed command of the carry, not
+ the measured jaw; None = keep the reset's measured jaw). The caller computes the observation afterwards."""
+ tr = self.task.tr
+ tr.lifted[idx] = torch.as_tensor(lifted, device=self.dev).bool()
+ tr.air_run[idx] = torch.as_tensor(air_steps, device=self.dev).long()
+ tr.prev_held[idx] = True
+ tr.since_release[idx] = 0
+ if jaw_cmd is not None and self.dyn is not None:
+ cj = torch.as_tensor(jaw_cmd, dtype=torch.float64, device=self.dev)
+ self.dyn.hold[idx, 5] = cj
+ self.dyn.prev5[idx, :, 5] = cj[:, None]
+ self.dyn.f[idx, 5] = cj
+ if self.dyn.servo is not None:
+ self.dyn.servo.hist[idx, :, 5] = cj[:, None]
+
+ def rest_info(self) -> dict | None:
+ """The rest-start option for logs (None = off): bank, share, rows (after the roll cap), rows dropped, rest
+ starts / all automatic resets so far."""
+ if self.rest is None:
+ return None
+ return dict(bank=self.cfg.rest.bank, share=self.cfg.rest.share, rows=int(len(self.rest["q"])),
+ dropped=int(self.rest_dropped), rest_starts=int(self.rest_n), resets=int(self.rest_resets))
+
+ def reset(self):
+ idx = torch.arange(self.B, device=self.dev)
+ self._pool_reset(idx)
+ if self.cfg.stagger and self.cfg.auto_reset:
+ k = torch.randint(self.max_episode_length, (self.B,), generator=self.gen, device=self.dev)
+ self.task.tr.t.copy_(k * STEPS)
+ self.obs = self._observe()
+ return self.obs
+
+ def reset_tasks(self, idx, starts: WorldState, goal_xy, goal_yaw, seeds, mj_start=None, check_tol=1e-6):
+ idx = torch.as_tensor(idx, dtype=torch.long, device=self.dev)
+ st = starts.to(self.dev)
+ if self.table_plane is not None and self.cfg.world == "mujoco":
+ # the task's cube (start and stored settled pose) moved onto the plane; the warm-up settles it there
+ from nedm.so101_policy import table as TB
+ mj_start = dict(mj_start)
+ mj_start["cube_pos"], mj_start["cube_quat"] = TB.map_cube(self.table_plane, mj_start["cube_pos"],
+ mj_start["cube_quat"])
+ cp, cq = TB.map_cube(self.table_plane, st.cube_pos.cpu().numpy(), st.cube_quat.cpu().numpy())
+ st = WorldState(**{**{f: getattr(st, f) for f in st.__dataclass_fields__},
+ "cube_pos": torch.as_tensor(cp, dtype=st.cube_pos.dtype, device=self.dev),
+ "cube_quat": torch.as_tensor(cq, dtype=st.cube_quat.dtype, device=self.dev)})
+ check_tol = None if check_tol is None else max(check_tol, 1e-4) # a new settle on the plane
+ if self.dyn is not None: # fixed tasks: robot dynamics draws from the env seed and the task seeds
+ sd = torch.as_tensor(seeds).reshape(-1)
+ self.dyn.reseed(int(self.cfg.seed) * 1_000_003 + 7919 * (int(sd[0]) if len(sd) else 0) + len(sd) + 0xD1A)
+ if self.goal_jump is not None: # fixed tasks: goal-jump draws from the env seed and the task seeds
+ sd = torch.as_tensor(seeds).reshape(-1)
+ self.goal_jump.reseed(int(self.cfg.seed) * 1_000_033 + 7927 * (int(sd[0]) if len(sd) else 0) + len(sd)
+ + 0x6A1)
+ if self.roll_hi is not None: # a start above the cap: the first targets pull the roll down to it
+ r0 = st.q[:, ROLL].to(torch.float64) + (0.0 if self.q_offset is None else self.q_offset[ROLL])
+ n_hi = int((r0 > float(self.thi[ROLL]) + 1e-9).sum())
+ if n_hi:
+ import warnings
+ warnings.warn(f"roll cap {self.cfg.roll_hi_deg:g} deg: {n_hi} of {len(r0)} task starts have the wrist "
+ f"roll above it (max {math.degrees(float(r0.max())):.1f} deg)", stacklevel=2)
+ self._reset_rows(idx, st, torch.as_tensor(goal_xy, dtype=torch.float64, device=self.dev),
+ torch.as_tensor(goal_yaw, dtype=torch.float64, device=self.dev),
+ torch.as_tensor(seeds, dtype=torch.long, device=self.dev), mj_start)
+ if self.cfg.world == "mujoco" and check_tol is not None:
+ got = self.ws.index(idx)
+ dq = float((got.q - st.q).abs().max())
+ dc = float((got.cube_pos - st.cube_pos).abs().max())
+ if dq > check_tol or dc > check_tol:
+ raise RuntimeError(f"MuJoCo warm-up start differs from the stored settled state ({dq:.2e}, {dc:.2e})")
+ self.obs = self._observe()
+ return self.obs
+
+ # ---- observation ---------------------------------------------------------------------------------------------
+ def _observe(self, F=None, idx=None):
+ ws = self.ws if idx is None else self.ws.index(idx)
+ if F is None:
+ F = T.features(ws, self.kin, None, self.tcfg)
+ return markov_obs(F, self.task, idx, self.obs_tcfg)
+
+ def get_observations(self):
+ return self.obs
+
+ # ---- one decision --------------------------------------------------------------------------------------------
+ @torch.no_grad()
+ def step(self, actions=None, targets=None, use_targets=None, step_hook=None):
+ """actions [B, 18] normalised coefficients (``Codec``) and/or targets [B, 5, 6] absolute (``use_targets`` [B]
+ bool: rows that take ``targets``; default all rows if only targets are given) -> (obs [B, 47], reward [B],
+ done [B], extras). step_hook(env, j): called after each of the 5 world steps (records)."""
+ task, B = self.task, self.B
+ live0 = task.tr.end == 0
+ q0 = self.ws.q.to(torch.float64)
+ if actions is not None:
+ a = actions.to(device=self.dev, dtype=torch.float64).clamp(-8.0, 8.0)
+ u5 = self.codec.targets(a, q0)
+ else:
+ u5 = None
+ if targets is not None:
+ tg = targets.to(device=self.dev, dtype=torch.float64)
+ if u5 is None:
+ u5 = tg
+ else:
+ m = torch.ones(B, dtype=torch.bool, device=self.dev) if use_targets is None else use_targets.to(self.dev)
+ u5 = torch.where(m[:, None, None], tg, u5)
+ rew = torch.zeros(B, dtype=torch.float64, device=self.dev)
+ info = None
+ ex = []
+ fz = self.floor_z if self.raise_z is None else self.floor_z + self.raise_z # (floor raise: flat part)
+ fl = (FLOOR if fz == 0.0 else FLOOR + fz) if self.cfg.floor_guard else None
+ lk = {} if self.raise_lift is None else dict(floor_lift=self.raise_lift) # (floor raise: tilted; off: {})
+ dyn = self.dyn if self.dyn is not None and self.dyn.active else None # None: the old path, bit for bit
+ if dyn is not None:
+ dyn.begin()
+ if self.pause is not None:
+ self.pause.begin(task, self.ws.q)
+ rc = self.roll_hi is not None # the wrist-roll cap (off: the old path, bit for bit)
+ fo = self.cfg.far_open if task.F is not None else None # FarOpenConfig (None: the old reward, bit for bit)
+ atc = self.cfg.arm_table # ArmTableConfig (None: the old world flags, bit for bit)
+ gs = self.cfg.grasp_shift # GraspShiftConfig (None: the old reward, bit for bit)
+ for j in range(STEPS):
+ if rc: # the commanded roll before the action layer (policy frame), live worlds
+ self.roll_cmd_max = torch.where(task.tr.end == 0, torch.fmax(self.roll_cmd_max, u5[:, j, ROLL]),
+ self.roll_cmd_max)
+ if self.q_offset is None:
+ u = safety(u5[:, j], self.ws.q.to(torch.float64), self.tlo, self.thi, self.lead, self.kin, fl,
+ self.floor_plane, **lk)
+ else: # the action layer in the policy's joint frame (targets u5 are in it), mapped back to the world
+ qo = self.q_offset
+ u = safety(u5[:, j], self.ws.q.to(torch.float64) + qo, self.tlo, self.thi, self.lead, self.kin, fl,
+ self.floor_plane, **lk) - qo
+ if rc: # the cap after the floor guard too (it pulls a target toward a measured roll
+ u = self.cap_roll(u) # above the cap), as the guard's range clamp after its action layer
+ ex.append(u) # u_exe: the action layer's targets (before the robot dynamics / servo scale)
+ if dyn is not None: # the robot's timing and servo (RobotDyn), perturbed worlds only; the held
+ u = dyn.apply(j, ex, u, self.ws.q, self.tlo, self.thi, self.ws.qd, # flag: the servo's cube / jaw
+ None if task.F is None else task.F["held"])
+ if EVAL_KP_SCALE != 1.0:
+ qn = self.ws.q.to(device=u.device, dtype=u.dtype)
+ u = u.clone()
+ u[:, :5] = qn[:, :5] + EVAL_KP_SCALE * (u[:, :5] - qn[:, :5])
+ if self.pause is not None: # the robot's hold state (training only): frozen arm in paused worlds
+ u = self.pause.apply(u)
+ if rc: # the cap on the target sent to the world, after every stage
+ u = self.cap_roll(u)
+ lv = task.tr.end == 0
+ if fo is not None: # FarOpenConfig: held, lifted, far from the goal (task.F of the last step);
+ Fp = task.F # the executed jaw target above the measured jaw before this step
+ far = (task.tr.end == 0) & Fp["held"] & task.tr.lifted & \
+ ((Fp["c"][:, :2] - task.goal_xy).norm(dim=-1) > fo.far_m)
+ jo = (ex[-1][:, 5].to(torch.float64) - self.ws.q[:, 5].to(torch.float64)).clamp(min=0.0)
+ fo_cost = torch.where(far, fo.cost * jo, torch.zeros_like(jo))
+ ws = self.world.step(u)
+ self.ws = ws if self.cfg.world != "mujoco" else ws.to(self.dev)
+ if atc is not None: # ArmTableConfig: the kinematic arm-table end (a new WorldState, the world's
+ hit = arm_table_rule(self.ws.q, self.ws.qd, self.kin, atc, self.table_plane) # own record unchanged)
+ if atc.grasp_only: # before the first firm lift only (the tracker before this step)
+ hit = hit & ~task.tr.lifted
+ self.arm_table_n = self.arm_table_n + (hit & (task.tr.end == 0)).sum()
+ self.ws = replace(self.ws, arm_table=self.ws.arm_table.to(device=hit.device, dtype=torch.bool) | hit)
+ if rc: # the measured roll after the step (policy frame)
+ rq = self.ws.q[:, ROLL].to(torch.float64) + (0.0 if self.q_offset is None else self.q_offset[ROLL])
+ self.roll_q_max = torch.where(lv, torch.fmax(self.roll_q_max, rq), self.roll_q_max)
+ if gs is not None: # the tracker before this step: live worlds, lifted flag
+ gs_live, gs_lifted = task.tr.end == 0, task.tr.lifted.clone()
+ r, _, _, info = task.step(self.ws, None, None)
+ if fo is not None:
+ r = r - fo_cost
+ self.far_open_sum = self.far_open_sum + fo_cost.sum()
+ if gs is not None: # GraspShiftConfig: placement cost at the descent / close events
+ e1, e2, err, h = grasp_shift_events(task.F, self.gs_h, self.gs_jaw, gs_lifted, gs)
+ e1, e2 = e1 & gs_live, e2 & gs_live
+ gc = (e1.to(torch.float64) + e2.to(torch.float64)) * grasp_shift_cost(err, gs)
+ r = r - gc
+ hx = task.F["hx"]
+ self.gs_stats = self.gs_stats + torch.stack((
+ e1.sum().to(torch.float64), (hx * e1).sum(), (err.abs() * e1).sum(),
+ e2.sum().to(torch.float64), (hx * e2).sum(), (err.abs() * e2).sum(), gc.sum()))
+ self.gs_h, self.gs_jaw = h, task.F["jaw"].clone() # own tensors (F["jaw"] can view ws.q)
+ rew += r
+ if step_hook is not None:
+ step_hook(self, j)
+ self.u_exe = torch.stack(ex, 1)
+ self.world_steps += B * STEPS
+ self.decisions += B
+ end = info["end"]
+ done = live0 & (end != 0)
+ time_out = done & (end == T.EC["timeout"])
+ self.ep_ret += rew
+ self.ep_len += live0.long()
+ ep = dict(end=end.clone(), success=end == T.EC["success"], success10=info["success10"].clone(),
+ lifted=info["lifted"].clone(), end_xy=info["end_xy_err"].clone(), end_yaw=info["end_yaw_err"].clone(),
+ ret=self.ep_ret.clone(), length=self.ep_len.clone(), steps=info["t"].clone(),
+ lenient=task.lenient.clone(), lenient_t=task.lenient_t.clone())
+ if self.goal_jump is not None: # jumps of the episode (final for the worlds that ended in this step)
+ ep["goal_jumps"] = self.goal_jump.n.clone()
+ if rc: # the largest commanded / measured wrist roll of the episode so far (rad)
+ ep["roll_cmd_max"], ep["roll_q_max"] = self.roll_cmd_max.clone(), self.roll_q_max.clone()
+ obs = self._observe(task.F)
+ if self.goal_jump is not None: # after the outcome record: the next decision sees the moved goals
+ gj = self.goal_jump.apply(task, task.tr.end == 0)
+ if len(gj):
+ obs = obs.clone()
+ obs[gj] = markov_obs({k: v[gj] for k, v in task.F.items() if torch.is_tensor(v)}, task, gj,
+ self.obs_tcfg)
+ final_obs = obs
+ if self.cfg.auto_reset:
+ idx = done.nonzero().flatten()
+ if len(idx):
+ obs = obs.clone()
+ self._pool_reset(idx)
+ obs[idx] = self._observe(idx=idx)
+ self.obs = obs
+ mask = torch.ones(B, ACT_DIM, dtype=torch.bool, device=self.dev)
+ extras = dict(time_outs=time_out, final_obs=final_obs, action_mask=mask, episode=ep, counts={},
+ world_steps=B * STEPS)
+ return obs, rew.float(), done, extras
+
+ def close(self):
+ if hasattr(self.world, "close"):
+ self.world.close()
+
+
+# ---- the joint teacher ----------------------------------------------------------------------------------------------
+class JointTeacher:
+ """A JT checkpoint (``ppo.PPO.save`` / ``save_bc``): ``act(obs)`` -> deterministic normalised action [B, 18];
+ ``targets(obs, q)`` -> absolute targets [B, 5, 6]; ``std`` the PPO action std."""
+
+ def __init__(self, path, device="cuda"):
+ from nedm.so101_policy.ppo import Policy, sha256
+ self.path = str(Path(path).expanduser())
+ d = torch.load(self.path, map_location=device, weights_only=False)
+ self.pol = Policy(**d["policy_kwargs"]).to(device)
+ self.pol.load_state_dict(d["policy"])
+ self.pol.eval()
+ rec = d.get("env") or {}
+ self.codec = Codec(np.asarray(rec["codec"]["mean"]), np.asarray(rec["codec"]["std"]), device)
+ self.env_rec = rec
+ self.dev = torch.device(device)
+ self.std = self.pol.std.detach().float()
+ self.sha256 = sha256(self.path)
+ self.iteration = int(d.get("iteration", 0))
+
+ @torch.no_grad()
+ def act(self, obs):
+ return self.pol.act_inference(obs.to(self.dev, torch.float32)).to(obs.device)
+
+ @torch.no_grad()
+ def targets(self, obs, q):
+ a = self.act(obs).to(q.device, torch.float64)
+ return self.codec.to(q.device).targets(a, q.to(torch.float64))
+
+ def info(self):
+ return dict(path=self.path, sha256=self.sha256, iteration=self.iteration)
+
+
+def save_bc(path, policy, codec: Codec, env_cfg: dict, extra=None):
+ """A BC-trained ``ppo.Policy`` in the ``PPO.save`` layout (so ``JointTeacher`` and PPO resume read it)."""
+ rec = dict(env=env_cfg, codec={k: v.tolist() for k, v in codec.state().items()}, kind="joint_env",
+ num_obs=OBS_DIM, num_actions=ACT_DIM, action_groups=list(ACTION_GROUPS))
+ torch.save(dict(policy=policy.state_dict(), policy_kwargs=policy.kwargs, iteration=0, env=rec,
+ extra=extra or {}), path)
diff --git a/so101_pick_place/code/src/nedm/so101_policy/joint_teacher.py b/so101_pick_place/code/src/nedm/so101_policy/joint_teacher.py
new file mode 100644
index 0000000000000000000000000000000000000000..30bbc3dc13c2deab6e472d4159231ccd6d8f9946
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/joint_teacher.py
@@ -0,0 +1,618 @@
+"""The Markov joint teacher (JT) of build9: behaviour cloning from the current teacher + decoder v3, PPO fine-tune in the
+NRD, and fixed-task episodes in any world (``joint_env`` module docstring for the observation, action and action layer).
+
+1. ``expert_collect``: the current teacher (state PPO through decoder v3 = build8's ``tray.TEACHER_DECODER``) in a
+ ``tray.TrayWorld`` (label decoder + DART driver decoder: labels = the CLEAN teacher's joint targets from the noisy
+ state). Recorded per decision boundary: the JT observation (``joint_env.markov_obs``, 47) next to build8's row
+ records; per 20 ms step the label targets ``u_lab``. Tasks: the start bank (production_plus split 0, as PPO) +
+ ``task.sample_goals`` (``bank_tasks``; decoder / noise seeds 700,000+), or any task file.
+2. ``BCSet`` / ``train_bc``: rows (obs, the 5 label targets of the decision relative to q) -> a ``ppo.Policy`` whose actor
+ outputs the normalised coefficients (``joint_env.Codec`` fitted on the data); loss = L1 on the 5 reconstructed targets
+ divided by a per-joint scale (std of the relative targets), masked inside the episode.
+3. ``JointPPO``: ``ppo.PPO`` with (a) ``critic_warmup`` iterations in which the actor and its std do not change (the
+ critic is fitted first: a BC actor with a random critic would be pushed by noise advantages), (a2) the observation
+ normaliser frozen at the BC statistics (measured: PPO's running update moved the frozen BC actor's NRD development
+ success from 95 to 12 % in 20 warm-up iterations), (b) an optional
+ behaviour-cloning anchor ``bc_coef`` x mean squared distance of the actor mean to a frozen reference actor on the
+ rollout states, (c) the lenient success in the learning curve.
+4. ``run_tasks``: one episode per task in a ``JointVecEnv`` (auto reset off) driven per WORLD by the JT (with optional
+ noise on its action) or by a student callback; -> outcomes and (``record``) per-boundary rows for student data.
+"""
+from __future__ import annotations
+
+import json
+import math
+import time
+from pathlib import Path
+
+import numpy as np
+import torch
+import torch.nn as nn
+
+from nedm.so101_policy import joint_env as JE
+from nedm.so101_policy import ppo as P
+from nedm.so101_policy import task as T
+
+BANK_SEED0 = 700_000
+
+
+def log_default(s):
+ print(f"[{time.strftime('%H:%M:%S')}] {s}", flush=True)
+
+
+# ---- tasks from the start bank ----------------------------------------------------------------------------------------
+def bank_tasks(n, seed=0, first=0, starts=str(JE.PP_DATA), split=0, device="cpu"):
+ """n tasks from the start bank (``vec_env.load_starts``) with goals from ``task.sample_goals`` (generator ``seed``):
+ the tray-task layout with state_* only (no MuJoCo start: NRD / kinematic worlds). Seeds BANK_SEED0 + first + i
+ (they seed the decoder durations and the noise only)."""
+ from nedm.so101_policy.vec_env import load_starts
+ bank = load_starts(starts, split, device)
+ g = torch.Generator(device).manual_seed(int(seed))
+ i = torch.randint(bank["q"].shape[0], (int(n),), generator=g, device=device)
+ yaw, _ = T.cube_yaw_tilt(bank["cube_quat"][i])
+ gxy, gyaw = T.sample_goals(bank["cube_pos"][i, :2], yaw, g)
+ out = dict(seeds=np.arange(n, dtype=np.int64) + BANK_SEED0 + int(first), goal_xy=gxy.cpu().numpy(),
+ goal_yaw=gyaw.cpu().numpy(), bank_index=i.cpu().numpy())
+ for k in ("q", "qd", "cube_pos", "cube_quat", "cube_v", "cube_w"):
+ out[f"state_{k}"] = bank[k][i].cpu().numpy()
+ return out
+
+
+# ---- 1. expert data ---------------------------------------------------------------------------------------------------
+def expert_world_class():
+ from nedm.so101_policy.vision import tray as TR
+
+ class ExpertWorld(TR.TrayWorld):
+ """``tray.TrayWorld`` that also records the JT observation at every decision boundary and the lenient flag."""
+
+ def __init__(self, *a, **k):
+ super().__init__(*a, **k)
+ JE.attach_lenient(self.task)
+ self._mobs = None
+
+ def observation(self, F):
+ if self._mobs is not None:
+ self._mobs.append(JE.markov_obs(F, self.task).cpu())
+ return super().observation(F)
+
+ def run_expert(self, tasks, noise=None, seed=0, record=True, record_states=False):
+ self._mobs = []
+ r = self.run(tasks, None, 1.0, noise, seed, record=record, record_states=record_states)
+ M = torch.stack(self._mobs, 1).numpy()
+ self._mobs = None
+ if record:
+ r["row_mobs"] = M[r["row_ep"], r["row_t"].astype(np.int64) // JE.STEPS]
+ r["lenient"] = self.task.lenient.cpu().numpy()
+ r["lenient_t"] = self.task.lenient_t.cpu().numpy()
+ return r
+
+ return ExpertWorld
+
+
+@torch.no_grad()
+def expert_collect(tasks, teacher, world="nrd", noise=0.0, seed=0, device="cuda", nrd_ckpt=None, workers=0,
+ mj_python=None, horizon=400, batch=1024, log=log_default, record=True, cache=None):
+ """The current teacher + decoder v3 on all tasks (batches of ``batch`` worlds) -> packed dict (build8 layout +
+ row_mobs, lenient) + meta. noise: float or [n] (DART scale of the teacher's move columns per task)."""
+ from nedm.so101_policy.vision import tray as TR
+ EW = expert_world_class()
+ n = len(tasks["seeds"])
+ nzs = np.broadcast_to(np.asarray(noise, np.float64), (n,))
+ parts, t0 = [], time.time()
+ cache = {} if cache is None else cache
+ for s0 in range(0, n, batch):
+ idx = np.arange(s0, min(n, s0 + batch))
+ t = TR.subset(tasks, idx)
+ key = (world, len(idx))
+ if key not in cache:
+ cache[key] = EW(world, len(idx), teacher, device, nrd_ckpt, workers, mj_python, horizon)
+ tw = cache[key]
+ r = tw.run_expert(t, nzs[idx], seed, record=record)
+ parts.append(r)
+ log(f" expert {world}: tasks {s0}-{idx[-1]}, success {r['success'].mean() * 100:.1f} %, lenient "
+ f"{r['lenient'].mean() * 100:.1f} %, {time.time() - t0:.0f} s")
+ out = TR.concat(parts) if record else {k: np.concatenate([p[k] for p in parts]) for k in
+ ("success", "lenient", "end", "lifted", "end_xy", "end_yaw", "steps")}
+ if record:
+ out["lenient"] = np.concatenate([p["lenient"] for p in parts])
+ meta = dict(world=world, nrd_ckpt=str(nrd_ckpt), teacher=teacher.info(), n_tasks=n, noise=float(np.mean(nzs)),
+ seed=int(seed), horizon=int(horizon), wall_s=time.time() - t0, success=float(np.mean(out["success"])),
+ lenient=float(np.mean(out["lenient"])), seeds=[int(tasks["seeds"][0]), int(tasks["seeds"][-1])],
+ decoder_over=TR.TEACHER_DECODER)
+ out["meta"] = np.array(json.dumps(meta, default=str))
+ return out
+
+
+# ---- 2. behaviour cloning -------------------------------------------------------------------------------------------
+class BCSet:
+ """Expert files -> tensors on ``device``: obs [N, 47], rel [N, 5, 6] (label targets - q at the boundary), valid
+ [N, 5]. Validation = ``val_frac`` of the episodes of the FIRST file (seeded)."""
+
+ def __init__(self, paths, device="cuda", val_frac=0.03, seed=0):
+ obs, rel, val, ok = [], [], [], []
+ for fi, p in enumerate(paths):
+ z = np.load(Path(p).expanduser())
+ ep, t = z["row_ep"].astype(np.int64), z["row_t"].astype(np.int64)
+ s0, st = z["ep_step_start"].astype(np.int64), z["steps"].astype(np.int64)
+ j = np.arange(JE.STEPS)
+ g = s0[ep][:, None] + t[:, None] + j[None]
+ v = (t[:, None] + j[None]) < st[ep][:, None]
+ g = np.minimum(g, len(z["u_lab"]) - 1)
+ rel.append(z["u_lab"][g] - z["row_q"][:, None, :])
+ obs.append(z["row_mobs"])
+ ok.append(v)
+ E = len(st)
+ isv = np.zeros(E, bool)
+ if fi == 0:
+ rng = np.random.default_rng(seed)
+ isv[rng.permutation(E)[: int(round(val_frac * E))]] = True
+ val.append(isv[ep])
+ tt = lambda x, dt=torch.float32: torch.as_tensor(np.concatenate(x), dtype=dt, device=device) # noqa: E731
+ self.obs, self.rel, self.valid = tt(obs), tt(rel), tt(ok, torch.bool)
+ isval = tt(val, torch.bool)
+ self.train_rows = torch.nonzero(~isval).flatten()
+ self.val_rows = torch.nonzero(isval).flatten()
+ self.dev = torch.device(device)
+
+ def codec(self):
+ full = self.valid[self.train_rows].all(1)
+ return JE.Codec.fit(self.rel[self.train_rows][full].double().cpu())
+
+ def scale(self, floor=2e-3):
+ v = self.valid[self.train_rows][..., None].float()
+ r = self.rel[self.train_rows]
+ m = (r * v).sum((0, 1)) / v.sum((0, 1))
+ return (((r - m) ** 2 * v).sum((0, 1)) / v.sum((0, 1))).sqrt().clamp_min(floor) # [6]
+
+
+RATE_DIMS = list(range(6, 12)) + list(range(27, 33)) # qd, cube v, cube w in the 47-dim observation
+
+
+def bc_loss(pol, codec: JE.Codec, obs, rel, valid, scale, rate_noise=0.0):
+ """L1 on the 5 reconstructed targets / per-joint scale. ``rate_noise``: Gaussian noise (std units) on the normalised
+ rate inputs (qd, cube v, w) in training (build8's fix of the copycat shortcut of behaviour cloning)."""
+ on = pol.norm(obs)
+ if rate_noise > 0:
+ on = on.clone()
+ on[:, RATE_DIMS] = on[:, RATE_DIMS] + rate_noise * torch.randn_like(on[:, RATE_DIMS])
+ a = pol.actor(on)
+ d = codec.decode(a.float())
+ e = ((d - rel).abs() / scale) * valid[..., None]
+ return e.sum() / (valid.sum() * 6).clamp_min(1)
+
+
+def train_bc(data: BCSet, out_dir, hidden=(512, 256, 128), steps=20000, batch=4096, lr=1e-3, wd=1e-5, seed=0,
+ log=log_default, init_std=0.25, env_cfg=None, val_every=1000, rate_noise=0.0):
+ """-> (policy, codec). Writes out_dir/{bc.pt, bc_curve.csv, codec.npz}."""
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ torch.manual_seed(seed)
+ dev = data.dev
+ codec = data.codec().to(dev)
+ np.savez(out / "codec.npz", **codec.state())
+ scale = data.scale().to(dev)
+ pol = P.Policy(JE.OBS_DIM, JE.ACT_DIM, [n for _, n in JE.ACTION_GROUPS], hidden, hidden, "elu", init_std,
+ actor_out_gain=1.0).to(dev)
+ tr = data.obs[data.train_rows].double()
+ with torch.no_grad():
+ pol.norm.mean.copy_(tr.mean(0))
+ pol.norm.var.copy_(tr.var(0, unbiased=False))
+ pol.norm.count.fill_(float(len(tr)))
+ opt = torch.optim.AdamW(pol.actor.parameters(), lr=lr, weight_decay=wd)
+ g = torch.Generator(device=dev).manual_seed(seed)
+ f = open(out / "bc_curve.csv", "w")
+ f.write("step,loss,val_loss,val_mae_arm_mrad,val_mae_jaw_mrad,lr\n")
+ t0 = time.time()
+ run = 0.0
+ for s in range(1, steps + 1):
+ frac = 0.5 * (1 + math.cos(math.pi * s / steps))
+ for gr in opt.param_groups:
+ gr["lr"] = lr * (0.05 + 0.95 * frac) * min(1.0, s / 300)
+ i = data.train_rows[torch.randint(len(data.train_rows), (batch,), device=dev, generator=g)]
+ loss = bc_loss(pol, codec, data.obs[i], data.rel[i], data.valid[i], scale, rate_noise)
+ opt.zero_grad(set_to_none=True)
+ loss.backward()
+ nn.utils.clip_grad_norm_(pol.actor.parameters(), 1.0)
+ opt.step()
+ run = 0.98 * run + 0.02 * float(loss) if s > 1 else float(loss)
+ if s % val_every == 0 or s == steps:
+ with torch.no_grad():
+ vl, ea, ej, n = 0.0, 0.0, 0.0, 0
+ for k in range(0, len(data.val_rows), 16384):
+ i = data.val_rows[k:k + 16384]
+ vl += float(bc_loss(pol, codec, data.obs[i], data.rel[i], data.valid[i], scale)) * len(i)
+ d = codec.decode(pol.actor(pol.norm(data.obs[i])).float())
+ e = (d - data.rel[i]).abs() * data.valid[i][..., None]
+ ea += float(e[..., :5].sum()) / 5
+ ej += float(e[..., 5].sum())
+ n += int(data.valid[i].sum())
+ row = (s, run, vl / max(len(data.val_rows), 1), 1e3 * ea / max(n, 1), 1e3 * ej / max(n, 1),
+ opt.param_groups[0]["lr"])
+ f.write(",".join(f"{x:.6g}" for x in row) + "\n")
+ f.flush()
+ log(f" bc step {s}: loss {run:.4f} val {row[2]:.4f} mae arm {row[3]:.2f} jaw {row[4]:.2f} mrad "
+ f"({time.time() - t0:.0f} s)")
+ f.close()
+ JE.save_bc(out / "bc.pt", pol, codec, env_cfg or {}, dict(steps=steps, batch=batch, lr=lr, hidden=list(hidden),
+ rate_noise=rate_noise))
+ return pol, codec
+
+
+# ---- 3. PPO fine-tune -----------------------------------------------------------------------------------------------
+class JointPPO(P.PPO):
+ """``ppo.PPO`` + critic warm-up, behaviour-cloning anchor and lenient statistics (module docstring)."""
+
+ def __init__(self, env, policy, cfg, ref_actor=None, bc_coef=0.0, critic_warmup=0, device=None, freeze_norm=True):
+ super().__init__(env, policy, cfg, device)
+ if freeze_norm: # keep the BC statistics: PPO's running update shifts the inputs of the BC actor
+ policy.norm.update = lambda x: None
+ self.ref = ref_actor
+ self.bc_coef = float(bc_coef)
+ self.critic_warmup = int(critic_warmup)
+ self._lenient = 0.0
+
+ @torch.no_grad()
+ def collect(self):
+ env = self.env
+ step0 = env.step
+ acc = torch.zeros((), dtype=torch.float64, device=self.dev)
+ cap = env.roll_cap() if getattr(env, "roll_hi", None) is not None else None
+ acc_r = torch.zeros((), dtype=torch.float64, device=self.dev)
+
+ def step(a):
+ out = step0(a)
+ acc.add_((out[3]["episode"]["lenient"] & out[2]).sum())
+ if cap is not None: # the roll cap: finished episodes whose command went above it
+ acc_r.add_(((out[3]["episode"]["roll_cmd_max"] > cap + 1e-9) & out[2]).sum())
+ return out
+
+ env.step = step
+ try:
+ st = super().collect()
+ finally:
+ env.step = step0
+ self._last_len = float(acc)
+ self._last_roll = float(acc_r) if cap is not None else None
+ return st
+
+ def update(self):
+ al, pol, R = self.al, self.policy, self.roll
+ warm = self.iteration < self.critic_warmup
+ with torch.no_grad():
+ returns, adv = P.gae(R.rewards, R.values, R.dones, self.last_values, self.gamma, self.lam)
+ adv = (adv - adv.mean()) / (adv.std() + 1e-8)
+ N = R.T * R.B
+ flat = lambda x: x.reshape(N, *x.shape[2:]) # noqa: E731
+ obs, act, mask, old_lp, old_mu = flat(R.obs), flat(R.act), flat(R.mask).float(), flat(R.logp), flat(R.mu)
+ old_v, ret, adv = flat(R.values), flat(returns), flat(adv)
+ old_std_all = flat(R.std)
+ clip = float(al["clip_param"])
+ n_mb = int(al["num_mini_batches"])
+ mb = N // n_mb
+ out = dict(value_loss=0.0, surrogate_loss=0.0, entropy=0.0, kl=0.0, clip_frac=0.0, bc_loss=0.0)
+ n_up = 0
+ for _ in range(int(al["num_learning_epochs"])):
+ perm = torch.randperm(N, generator=self.gen, device=self.dev)
+ for k in range(n_mb):
+ i = perm[k * mb:(k + 1) * mb]
+ m = mask[i]
+ mu = pol.actor(obs[i])
+ v = pol.value(obs[i])
+ std = pol.std_of(None)
+ lp = P.log_prob(mu, std, act[i], m)
+ with torch.no_grad():
+ kl = P.kl_div(old_mu[i], old_std_all[i], mu, std, m)
+ kl_mean = float(kl.mean())
+ if not warm and al.get("desired_kl") is not None and al.get("schedule") == "adaptive":
+ if kl_mean > al["desired_kl"] * 2.0:
+ self.lr = max(1e-6, self.lr / 1.5)
+ elif 0.0 < kl_mean < al["desired_kl"] / 2.0:
+ self.lr = min(1e-3, self.lr * 1.5)
+ self.opt.param_groups[0]["lr"] = 0.0 if warm else self.lr
+ self.opt.param_groups[1]["lr"] = self.critic_lr
+ ratio = torch.exp(lp - old_lp[i])
+ a_ = adv[i]
+ surr = torch.max(-a_ * ratio, -a_ * ratio.clamp(1 - clip, 1 + clip)).mean()
+ if al.get("use_clipped_value_loss", True):
+ vc = old_v[i] + (v - old_v[i]).clamp(-clip, clip)
+ vloss = torch.max((v - ret[i]) ** 2, (vc - ret[i]) ** 2).mean()
+ else:
+ vloss = ((v - ret[i]) ** 2).mean()
+ ent = P.entropy(std, m).mean()
+ loss = float(al["value_loss_coef"]) * vloss
+ if not warm:
+ loss = loss + surr - float(al["entropy_coef"]) * ent
+ if self.ref is not None and self.bc_coef > 0:
+ with torch.no_grad():
+ mu_ref = self.ref(obs[i])
+ bcl = ((mu - mu_ref) ** 2).mean()
+ loss = loss + self.bc_coef * bcl
+ out["bc_loss"] += float(bcl.detach())
+ self.opt.zero_grad()
+ loss.backward()
+ nn.utils.clip_grad_norm_(pol.parameters(), float(al["max_grad_norm"]))
+ self.opt.step()
+ self.clamp_std()
+ with torch.no_grad():
+ out["clip_frac"] += float(((ratio - 1).abs() > clip).float().mean())
+ out["value_loss"] += float(vloss.detach())
+ out["surrogate_loss"] += float(surr.detach())
+ out["entropy"] += float(ent.detach())
+ out["kl"] += kl_mean
+ n_up += 1
+ res = {k: v / max(n_up, 1) for k, v in out.items()}
+ res["critic_warmup"] = float(warm)
+ return res
+
+ def iterate(self):
+ row = super().iterate()
+ n = row.get("episodes", 0.0)
+ row["lenient"] = float(self._last_len) / n if n else math.nan
+ if getattr(self, "_last_roll", None) is not None: # roll cap: share of the episodes that commanded above it
+ row["roll_cmd_over"] = self._last_roll / n if n else math.nan
+ return row
+
+
+def ppo_train_cfg(over=None):
+ cfg = P.train_cfg_default(1)
+ cfg["algorithm"].update(learning_rate=1e-4, desired_kl=0.01, entropy_coef=0.0, num_mini_batches=8,
+ num_learning_epochs=5)
+ cfg["policy"].update(actor_out_gain=1.0, action_bias=None)
+ cfg.update(num_steps_per_env=32, critic_lr=3e-4, init_std=[0.25, 0.25], std_floor=[0.05, 0.05],
+ std_cap=[0.5, 0.5], std_reset=[0.25, 0.25])
+ return P.merge(cfg, over)
+
+
+# ---- 4. fixed-task episodes -----------------------------------------------------------------------------------------
+EP_OUT = ("end", "success", "success10", "lifted", "end_xy", "end_yaw", "ret", "length", "steps", "lenient",
+ "lenient_t")
+
+
+def make_env(world, B, codec, device="cuda", nrd_ckpt=None, workers=0, mj_python=None, horizon=400, members="split",
+ lead_clamp=True, floor_guard=True, hold_cap_s=None, hold_obs_s=0.0, dyn=None, goal_jump=None,
+ roll_hi_deg=None, floor_raise=None):
+ """Fixed-task env (evaluation, round collection). ``hold_cap_s`` / ``hold_obs_s``: ``JE.hold_cap_kw`` (None / 0 =
+ the task defaults). ``dyn``: robot dynamics (``JE.RobotDynConfig`` or its dict); None = the process-wide
+ evaluation setting of ``$NEDM_SO101_DYN`` (unset = off), False = off. ``goal_jump``: ``JE.GoalJumpConfig`` (or
+ its dict; None = off): goal jumps during the episodes (the evaluation-only goal shift). ``roll_hi_deg``: the
+ wrist-roll target cap (sim deg, ``JE.JointEnvConfig.roll_hi_deg``); None = off. ``floor_raise``: the action-layer
+ floor raise (``JE.JointEnvConfig.floor_raise``: a height in m or (c0, c1, c2)); None = off."""
+ ck = [str(Path(c).expanduser()) for c in ([nrd_ckpt] if isinstance(nrd_ckpt, (str, Path)) else (nrd_ckpt or []))]
+ dyn = JE.dyn_from_env() if dyn is None else JE.dyn_config(dyn)
+ cfg = JE.JointEnvConfig(world=world, num_envs=B, device=device, ckpts=ck, members=members, auto_reset=False,
+ stagger=False, starts="", horizon=int(horizon), mj_workers=workers, mj_python=mj_python,
+ lead_clamp=lead_clamp, floor_guard=floor_guard, dyn=dyn, goal_jump=goal_jump,
+ roll_hi_deg=roll_hi_deg, floor_raise=floor_raise, **JE.hold_cap_kw(hold_cap_s, hold_obs_s))
+ return JE.JointVecEnv(cfg, codec)
+
+
+def jt_floor_raise(jt):
+ """The floor raise (``JE.JointEnvConfig.floor_raise`` tuple) a JT was trained with (its checkpoint's env record;
+ ``JE.JointTeacher.env_rec``), None = none (also a JT without the record)."""
+ rec = getattr(jt, "env_rec", None) or {}
+ env = rec.get("env") if isinstance(rec, dict) else None
+ return JE.floor_raise_config(env.get("floor_raise")) if isinstance(env, dict) else None
+
+
+FLOOR_RAISE_OFF = ("0", "off", "none")
+
+
+def resolve_floor_raise(spec, jt, log=log_default, what="evaluation"):
+ """The ``--floor-raise`` of the JT-driven commands (v12 review finding 4): "auto" or "" = the JT's own
+ (``jt_floor_raise``; a JT without a raise: off, the old behaviour), "0" / "off" / "none" = off, else a height (m) or
+ "c0,c1,c2" (``JE.floor_raise_config``). A value other than the JT's own is logged as a WARNING (an NRD-vs-MuJoCo
+ comparison of one JT must use one floor). -> tuple or None."""
+ s = str(spec if spec is not None else "").strip().lower()
+ own = jt_floor_raise(jt)
+ if s in ("", "auto"):
+ fr = own
+ if fr is not None:
+ log(f"floor raise: auto = the JT's own {list(fr)} ({what})")
+ elif s in FLOOR_RAISE_OFF:
+ fr = None
+ else:
+ fr = JE.floor_raise_config(spec)
+ a = (0.0, 0.0, 0.0) if fr is None else fr
+ b = (0.0, 0.0, 0.0) if own is None else own
+ if max(abs(u - v) for u, v in zip(a, b)) > 1e-9:
+ log(f"WARNING: {what} floor raise {None if fr is None else list(fr)}, the JT was trained with "
+ f"{None if own is None else list(own)}")
+ return fr
+
+
+@torch.no_grad()
+def run_tasks(env: JE.JointVecEnv, tasks, teacher: JE.JointTeacher | None, student=None, src=None, noise=None,
+ noise_seed=0, record=False, record_states=False, full_horizon=False, log=None, student_hook=None,
+ floor_gap=False):
+ """One episode per world on ``tasks`` (env.B rows). ``src`` [B] int: 0 = JT drives, 1 = student drives (default:
+ student if given, else JT). ``noise`` [B] float: Gaussian noise of that many PPO std on the JT's normalised action
+ (JT-driven worlds; counter-based draws from the task seed, decision index and ``noise_seed``). ``student``: object
+ with ``reset(B)`` and ``__call__(ws, goal_pose, k) -> absolute targets [B, 5, 6]`` for the executed part.
+ ``record``: per boundary (live worlds) q, qd, cube pose, the JT's absolute targets of the decision ``lab`` [5, 6]
+ (the label: defined at every state), the JT observation ``obs`` [47] (relabelling by another JT), who drove; per
+ episode the outcomes. ``record_states``: per 20 ms step q and
+ cube pose [B, S, ...] (videos). ``full_horizon``: keep stepping after the task ended (videos).
+ ``floor_gap`` (v12 review finding 2; off: no key): per episode ``floor_gap_prelift`` = the lowest measured
+ gripper / moving-jaw point above the action layer's floor (``JointVecEnv.floor_gap``; m, negative = below), min
+ over the 20 ms steps of the live episode before its first firm lift (inf: no such step).
+ Goal jumps (``env.goal_jump``, off by default): the student gets the env's CURRENT goal at every decision; extra
+ outputs ``goal_jumps`` (per episode), ``goal_xy_final``, ``goal_jump_d`` / ``goal_jump_lat`` (the last jump's
+ offset of the cube from the new goal, m; + = past along the carry) and, with ``record``, ``row_goal_xy``
+ (``goal_xy`` stays the task's own goal).
+ Held-cube rest starts (round v9 task files with ``rest_lifted`` / ``rest_air_s`` / ``rest_ctrl``): after the reset
+ the task's lifted flag and held time are preset (``JointVecEnv.set_rest``); files without these keys: unchanged.
+ The NRD start keeps its one-entry history; CPU MuJoCo needs the exact held-target reset of
+ ~/so101_r2s_claude/v9/restart/scripts/step0_eval.py (its warm-up moves a held cube past the start check).
+ -> dict of numpy arrays."""
+ from nedm.so101_policy.vision.demos import start_state
+ from nedm.so101_policy.vision.teacher import hash_normal
+ B, dev = env.B, env.dev
+ if len(tasks["seeds"]) != B:
+ raise ValueError(f"{len(tasks['seeds'])} tasks for {B} worlds")
+ g = lambda k: torch.as_tensor(tasks[k], dtype=torch.float64, device=dev) # noqa: E731
+ mj = dict(q=tasks["start_q"], cube_pos=tasks["start_cube_pos"], cube_quat=tasks["start_cube_quat"]) \
+ if env.cfg.world == "mujoco" else None
+ seeds = torch.as_tensor(tasks["seeds"], dtype=torch.long, device=dev)
+ obs = env.reset_tasks(torch.arange(B, device=dev), start_state(tasks, dev), g("goal_xy"), g("goal_yaw"), seeds, mj)
+ if "rest_lifted" in tasks: # held-cube rest starts (round v9 task files, rest_* keys): lifted flag, held time
+ env.set_rest(torch.arange(B, device=dev), torch.as_tensor(np.asarray(tasks["rest_lifted"], bool)),
+ torch.as_tensor(np.round(np.asarray(tasks["rest_air_s"], np.float64) / JE.CONTROL_DT)),
+ torch.as_tensor(np.asarray(tasks["rest_ctrl"], np.float64)[:, 5]) if "rest_ctrl" in tasks else None)
+ obs = env.obs = env._observe()
+ goal_pose = torch.cat((g("goal_xy"), g("goal_yaw")[:, None]), -1)
+ if src is None:
+ src = np.full(B, 1 if student is not None else 0)
+ src_t = torch.as_tensor(np.asarray(src), dtype=torch.long, device=dev)
+ stud = src_t == 1
+ if bool(stud.any()) and student is None:
+ raise ValueError("student-driven worlds need a student")
+ if student is not None:
+ student.reset(B)
+ nz = torch.zeros(B, dtype=torch.float64, device=dev) if noise is None else \
+ torch.as_tensor(np.broadcast_to(np.asarray(noise, np.float64), (B,)).copy(), device=dev)
+ hseed = seeds * 1_000_003 + 7919 * int(noise_seed) + 23
+ std = teacher.std.to(dev, torch.float64) if teacher is not None else None
+ gj = getattr(env, "goal_jump", None)
+ R = {k: [] for k in ("q", "qd", "cube_pos", "cube_quat", "lab", "obs", "live")} if record else None
+ if R is not None and gj is not None:
+ R["goal_xy"] = []
+ SS = {k: [] for k in ("q", "cube", "u")} if record_states else None
+ keep = None
+ t0 = time.time()
+ t_student = 0.0
+
+ fgap = torch.full((B,), math.inf, dtype=torch.float64, device=dev) if floor_gap else None
+
+ def hook(e, j):
+ if SS is not None:
+ SS["q"].append(e.ws.q.float().cpu())
+ SS["cube"].append(torch.cat((e.ws.cube_pos, e.ws.cube_quat), -1).float().cpu())
+ if fgap is not None: # the floor creep before the first firm lift (live episodes)
+ pre = (e.task.tr.end == 0) & ~e.task.tr.lifted
+ fgap.copy_(torch.where(pre.to(dev), torch.minimum(fgap, e.floor_gap().to(dev)), fgap))
+
+ for k in range(env.max_episode_length + 1):
+ live = env.task.tr.end == 0
+ if not bool(live.any()) and not full_horizon:
+ break
+ ws = env.ws
+ a = lab = None
+ if teacher is not None:
+ a = teacher.act(obs).to(dev, torch.float64)
+ lab = env.codec.targets(a, ws.q.to(torch.float64))
+ if getattr(env, "roll_hi", None) is not None: # the roll cap: the label's wrist roll capped as well
+ lab = env.cap_roll(lab)
+ if bool((nz > 0).any()):
+ eps = hash_normal(hseed, k, JE.ACT_DIM).to(a)
+ a = a + (nz[:, None] * std[None]) * eps
+ tg = None
+ if gj is not None: # goal jumps: the current goal (the task's, the teacher observation's)
+ goal_pose = torch.cat((env.task.goal_xy, env.task.goal_yaw[:, None]), -1).to(dev, torch.float64)
+ if bool(stud.any()):
+ ts = time.time()
+ tg = student(ws, goal_pose, k).to(dev, torch.float64)
+ t_student += time.time() - ts
+ if R is not None:
+ for name, v in (("q", ws.q), ("qd", ws.qd), ("cube_pos", ws.cube_pos), ("cube_quat", ws.cube_quat)):
+ R[name].append(v.float().cpu())
+ R["lab"].append(lab.float().cpu() if lab is not None else torch.zeros(B, JE.STEPS, 6))
+ R["obs"].append(obs.float().cpu())
+ R["live"].append(live.cpu())
+ if "goal_xy" in R:
+ R["goal_xy"].append(env.task.goal_xy.float().cpu())
+ obs, _, done, ex = env.step(a, targets=tg, use_targets=stud if tg is not None else None,
+ step_hook=hook if SS is not None or fgap is not None else None)
+ ep = ex["episode"]
+ if keep is None:
+ keep = {n_: v.clone() for n_, v in ep.items()}
+ else:
+ for n_, v in ep.items():
+ keep[n_] = torch.where(done, v, keep[n_])
+ if log is not None and k % 20 == 19:
+ log(f" decision {k + 1}: ended {int((env.task.tr.end != 0).sum())}/{B}")
+ out = {n_: v.cpu().numpy() for n_, v in keep.items()}
+ out["seeds"] = np.asarray(tasks["seeds"])
+ out["goal_xy"] = np.asarray(tasks["goal_xy"], np.float32)
+ out["goal_yaw"] = np.asarray(tasks["goal_yaw"], np.float32)
+ out["src"] = np.asarray(src, np.int8)
+ out["noise"] = nz.cpu().numpy()
+ out["wall_s"] = np.float64(time.time() - t0)
+ out["student_s"] = np.float64(t_student)
+ if env.cfg.world == "mujoco":
+ out["mj_reason"] = env.world.end_reason.clone().numpy().astype(np.int16)
+ if getattr(env, "roll_hi", None) is not None: # the roll cap (per-episode roll_cmd_max / roll_q_max: rad)
+ out["roll_hi_deg"] = np.float64(env.cfg.roll_hi_deg)
+ out["roll_cap_rad"] = np.float64(env.thi[JE.ROLL])
+ if getattr(env.cfg, "floor_raise", None) is not None: # the floor raise (JSON [c0, c1, c2], m); off: no key
+ out["floor_raise"] = np.array(json.dumps(list(env.cfg.floor_raise)))
+ if fgap is not None: # the floor creep before the first firm lift (m; off: no key)
+ out["floor_gap_prelift"] = fgap.cpu().numpy()
+ if gj is not None:
+ out["goal_jumps"] = gj.n.cpu().numpy().astype(np.int16)
+ out["goal_xy_final"] = env.task.goal_xy.float().cpu().numpy()
+ out["goal_jump_d"] = gj.d_last.float().cpu().numpy()
+ out["goal_jump_lat"] = gj.lat_last.float().cpu().numpy()
+ out["goal_jump_z"] = gj.z_last.float().cpu().numpy()
+ out["goal_jump_cfg"] = np.array(json.dumps(JE.asdict(gj.cfg)))
+ if R is not None:
+ rows = {k_: torch.stack(v, 1).numpy() for k_, v in R.items()}
+ n_rows = out["length"].astype(np.int64)
+ for b in range(B):
+ if not rows["live"][b, : n_rows[b]].all():
+ raise RuntimeError(f"episode {b}: live rows are not a prefix")
+ rb = np.repeat(np.arange(B), n_rows)
+ rt = np.concatenate([np.arange(n) for n in n_rows]) if B else np.zeros(0, np.int64)
+ for k_ in ("q", "qd", "cube_pos", "cube_quat", "lab", "obs") + (("goal_xy",) if "goal_xy" in rows else ()):
+ out[f"row_{k_}"] = rows[k_][rb, rt]
+ out["row_ep"], out["row_t"] = rb.astype(np.int32), rt.astype(np.int16)
+ out["ep_row_start"] = np.concatenate([[0], np.cumsum(n_rows)[:-1]]).astype(np.int64)
+ if SS is not None:
+ out["state_q"] = torch.stack(SS["q"], 1).numpy()
+ out["state_cube"] = torch.stack(SS["cube"], 1).numpy()
+ return out
+
+
+def summarize(r):
+ """Strict / lenient success with Wilson intervals, failure causes (non-lenient episodes), lifted, end errors."""
+ from nedm.so101_policy.vision.tray import wilson
+ s = np.asarray(r["success"]).astype(bool)
+ le = np.asarray(r["lenient"]).astype(bool)
+ n = len(s)
+ causes = {T.ENDS[int(k)]: int(v) for k, v in zip(*np.unique(np.asarray(r["end"])[~le], return_counts=True))}
+ out = dict(n=n, lenient=float(le.mean()), lenient_ci95=list(wilson(int(le.sum()), n)), strict=float(s.mean()),
+ strict_ci95=list(wilson(int(s.sum()), n)), success10=float(np.mean(r["success10"])),
+ lifted=float(np.mean(r["lifted"])), causes_not_lenient=causes)
+ if s.any():
+ out["end_xy_mm_p50_strict"] = float(np.median(np.asarray(r["end_xy"])[s]) * 1e3)
+ if "roll_cmd_max" in r and "roll_cap_rad" in r: # the roll cap: episodes that pushed above / reached it
+ out.update(roll_summary(r["roll_cmd_max"], r["roll_q_max"], float(r["roll_cap_rad"])))
+ if "floor_gap_prelift" in r: # the floor creep before the lift (run_tasks floor_gap): mm, negative = below
+ out.update(floor_gap_summary(r["floor_gap_prelift"]))
+ return out
+
+
+# the real robot's floor creep (v12 review, ~/so101_r2s_claude/v12/table/review/creep_robot.json): the lowest measured
+# gripper point before the lift minus the 1.5 mm flat floor, eval episodes 10-24..10-26 (n 68 holds, all students)
+ROBOT_FLOOR_GAP_MM = dict(p50=-4.4, p10=-11.6, min=-14.0, n=68)
+
+
+def floor_gap_summary(g):
+ """Per-episode ``floor_gap_prelift`` (m) -> dict floor_gap_mm_p50 / _p10 / _min (finite episodes, mm; negative =
+ below the action layer's floor) and floor_gap_n; the teacher gate compares p10 with ``ROBOT_FLOOR_GAP_MM``."""
+ g = np.asarray(g, np.float64)
+ g = g[np.isfinite(g)] * 1e3
+ if not len(g):
+ return dict(floor_gap_n=0)
+ return dict(floor_gap_mm_p50=float(np.median(g)), floor_gap_mm_p10=float(np.percentile(g, 10)),
+ floor_gap_mm_min=float(g.min()), floor_gap_n=int(len(g)))
+
+
+def roll_summary(cmd_max, q_max, cap):
+ """Per-episode largest commanded / measured wrist roll (rad) and the cap (rad) -> shares of the episodes whose
+ command went above the cap (``roll_cmd_over``) and whose measured roll came within ``JE.ROLL_NEAR_DEG`` of it
+ (``roll_q_at_cap``), and the largest command (deg)."""
+ c, q = np.asarray(cmd_max, np.float64), np.asarray(q_max, np.float64)
+ n = max(len(c), 1)
+ return dict(roll_cmd_over=float((c > cap + 1e-9).sum() / n),
+ roll_q_at_cap=float((q >= cap - math.radians(JE.ROLL_NEAR_DEG)).sum() / n),
+ roll_cmd_max_deg=float(np.degrees(c.max())) if len(c) else float("nan"))
diff --git a/so101_pick_place/code/src/nedm/so101_policy/kin.py b/so101_pick_place/code/src/nedm/so101_policy/kin.py
new file mode 100644
index 0000000000000000000000000000000000000000..b25447f1cf0a6445d57458a8b7a6b97576ebb0c4
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/kin.py
@@ -0,0 +1,448 @@
+"""Batched torch kinematics of the MuJoCo Menagerie SO101 arm of the grasp collector (no MuJoCo in a step).
+
+Frames and units: world = arm base frame (base at the origin, z up, table top at z = 0), metres, radians, quaternions
+w x y z. Joint vector q [..., 6] in the collector's order (``JOINTS``): shoulder_pan, shoulder_lift, elbow_flex,
+wrist_flex, wrist_roll, gripper (= the moving jaw). Every joint is a hinge about its body's local z axis at the body
+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
+``model.KinematicChain`` and of MuJoCo for this model). The body constants below are the compiled ``body_pos`` /
+``body_quat`` of ``collect.so101_grasp.build_spec`` (MuJoCo 3.15, Menagerie rev 0059d43); ``tests/so101_policy/
+test_kin.py`` checks them, the FK, the lowest point and the IK against MuJoCo.
+
+- ``fk(q)``: grasp point (``GRASP_POINT`` in the gripper frame, world) and the gripper rotation (columns = gripper axes
+ in the world; top-down = gripper z up, fingertips down, closing axis x at the yaw, ``topdown``).
+- ``body_poses(q)``: world pose of every arm body (``BODIES``), for rendering.
+- ``lowest_point(q)``: lowest world z of the collision geoms of the gripper and the moving jaw (``Scene.lowest`` with
+ ``which`` = those bodies: every vertex of boxes and meshes, capsule ends and sphere centres minus their radius). The
+ points come from MuJoCo once (``collision_points``) or from a saved ``.npz`` (``save_points`` / ``points=``).
+ ``exact=False`` uses only the points that are lowest for one of 20,000 directions (1,645 of 4,763 points; error
+ <= 0.033 mm against all points over 200,000 random directions, measured 2026-10-11): the command decoder's floor.
+- ``box_distance(q, centre, quat, half)``: smallest distance (m) from the gripper and moving-jaw points (the reduced
+ set) to a box (the cube); 0 inside. Vertices only, so a face of a hull can be closer than this (decoder yaw rule).
+- ``ik`` / ``pose_ik`` / ``ik_topdown``: batched damped least squares with the collector's rules (``Scene.ik``,
+ ``Scene.pose_ik``, ``Scene.solve``): the same iterations, stopping rules, tolerances, seeds and seed order, so a
+ world gets the same solution branch as the collector would.
+"""
+from __future__ import annotations
+
+import math
+from pathlib import Path
+
+import torch
+
+JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper")
+# body name, parent index in BODIES (-1 = world), compiled body_pos, compiled body_quat (w x y z), joint index or None
+_TREE = (
+ ("base", -1, (0.0, 0.0, 0.0), (1.0, 0.0, 0.0, 0.0), None),
+ ("shoulder", 0, (0.0388353, 0.0, 0.0624), (0.0, 0.0, -1.0, 0.0), 0),
+ ("upper_arm", 1, (-0.0303992, -0.0182778, -0.0542), (0.5, -0.5, -0.5, -0.5), 1),
+ ("lower_arm", 2, (-0.11257, -0.028, 0.0), (0.7071067811865475, 0.0, 0.0, 0.7071067811865475), 2),
+ ("wrist", 3, (-0.1349, 0.0052, 0.0), (0.7071067811865475, 0.0, 0.0, -0.7071067811865475), 3),
+ ("gripper", 4, (5.55112e-17, -0.0611, 0.0181),
+ (0.017209108230571014, -0.017209108230571014, 0.7068973380865913, 0.7068973380865913), 4),
+ ("camera_mount", 5, (0.0, 0.0, 0.0), (1.0, 0.0, 0.0, 0.0), None),
+ ("moving_jaw_so101_v1", 5, (0.0202, 0.0188, -0.0234), (0.7071067811865475, 0.7071067811865475, 0.0, 0.0), 5),
+)
+BODIES = tuple(t[0] for t in _TREE)
+GRIPPER, JAW = BODIES.index("gripper"), BODIES.index("moving_jaw_so101_v1")
+GRASP_POINT = (0.0105, 0.0, -0.092) # grasp point in the gripper frame (collector grasp_point_m)
+PAN_AXIS_XY = (0.0388, 0.0) # vertical pan axis in the world (collector workspace)
+# applied-target range of the collector (Scene.tlo / thi: joint range 0.05 rad inside, within the ctrlrange)
+TLO = (-1.8698599999999999, -1.6953293, -1.64, -1.608063, -2.6938473000000003, -0.12453299999999999)
+THI = (1.8698599999999999, 1.6953293, 1.64, 1.608063, 2.7912063000000003, 1.6953292)
+IK_TOL_M, IK_TOL_RAD = 0.0005, math.radians(2.0) # collector cfg["ik"]
+GUARD_BODIES = ("gripper", "moving_jaw_so101_v1")
+_POINTS_CACHE: dict = {}
+
+
+# ---- small rotation helpers (batched, any float dtype) ----------------------------------------------------------
+def quat_mat(q):
+ """Unit quaternions [..., 4] (w x y z) -> rotation matrices [..., 3, 3]."""
+ w, x, y, z = q.unbind(-1)
+ return torch.stack((1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y),
+ 2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x),
+ 2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)), -1).reshape(*q.shape[:-1], 3, 3)
+
+
+def mat_quat(r):
+ """Rotation matrices [..., 3, 3] -> unit quaternions [..., 4] (w x y z, w >= 0), branch-free Shepperd form."""
+ m00, m11, m22 = r[..., 0, 0], r[..., 1, 1], r[..., 2, 2]
+ t = torch.stack((1 + m00 + m11 + m22, 1 + m00 - m11 - m22, 1 - m00 + m11 - m22, 1 - m00 - m11 + m22), -1)
+ k = t.argmax(-1, keepdim=True)
+ s = torch.sqrt(t.gather(-1, k).clamp_min(1e-30))[..., 0] * 2 # 4 * |largest component|
+ a = torch.stack((s / 4, (r[..., 2, 1] - r[..., 1, 2]) / s, (r[..., 0, 2] - r[..., 2, 0]) / s,
+ (r[..., 1, 0] - r[..., 0, 1]) / s), -1)
+ b = torch.stack(((r[..., 2, 1] - r[..., 1, 2]) / s, s / 4, (r[..., 0, 1] + r[..., 1, 0]) / s,
+ (r[..., 0, 2] + r[..., 2, 0]) / s), -1)
+ c = torch.stack(((r[..., 0, 2] - r[..., 2, 0]) / s, (r[..., 0, 1] + r[..., 1, 0]) / s, s / 4,
+ (r[..., 1, 2] + r[..., 2, 1]) / s), -1)
+ d = torch.stack(((r[..., 1, 0] - r[..., 0, 1]) / s, (r[..., 0, 2] + r[..., 2, 0]) / s,
+ (r[..., 1, 2] + r[..., 2, 1]) / s, s / 4), -1)
+ q = torch.where(k == 0, a, torch.where(k == 1, b, torch.where(k == 2, c, d)))
+ q = q / q.norm(dim=-1, keepdim=True)
+ return torch.where(q[..., :1] < 0, -q, q)
+
+
+def quat_rotvec(q):
+ """Unit quaternions [..., 4] -> rotation vectors [..., 3] (the shorter way round, as mju_quat2Vel of w >= 0)."""
+ q = torch.where(q[..., :1] < 0, -q, q)
+ v = q[..., 1:]
+ n = v.norm(dim=-1, keepdim=True)
+ ang = 2 * torch.atan2(n, q[..., :1])
+ return v * torch.where(n > 1e-15, ang / n.clamp_min(1e-300), torch.full_like(n, 2.0))
+
+
+def rotvec(r):
+ """Rotation matrices [..., 3, 3] -> rotation vectors [..., 3] (angle in [0, pi])."""
+ return quat_rotvec(mat_quat(r))
+
+
+def rotvec_fast(r):
+ """rotvec for rotations below about 170 deg with fewer operations (axis from the skew part, angle by atan2; the
+ direction degrades near 180 deg). Used where the error angle stays small (ik_track)."""
+ v = torch.stack((r[..., 2, 1] - r[..., 1, 2], r[..., 0, 2] - r[..., 2, 0], r[..., 1, 0] - r[..., 0, 1]), -1)
+ n = v.norm(dim=-1, keepdim=True)
+ ang = torch.atan2(0.5 * n, 0.5 * (r[..., 0, 0] + r[..., 1, 1] + r[..., 2, 2] - 1)[..., None])
+ return v * torch.where(n > 1e-15, ang / n.clamp_min(1e-300), torch.full_like(n, 0.5))
+
+
+def rotz(yaw):
+ """Rotations about the world z axis [..., 3, 3]; topdown(yaw) of the collector (gripper z up, x at the yaw)."""
+ c, s = torch.cos(yaw), torch.sin(yaw)
+ o, z = torch.ones_like(c), torch.zeros_like(c)
+ return torch.stack((c, -s, z, s, c, z, z, z, o), -1).reshape(*yaw.shape, 3, 3)
+
+
+topdown = rotz
+
+
+def yaw_of(r):
+ """Yaw of the gripper closing axis (first column) as Scene.solve reads it: atan2(r10, r00)."""
+ return torch.atan2(r[..., 1, 0], r[..., 0, 0])
+
+
+def tilt_of(r):
+ """Angle (rad) between the gripper z axis and the world z axis (0 = top-down)."""
+ return torch.acos(r[..., 2, 2].clamp(-1.0, 1.0))
+
+
+def wrap(a):
+ return torch.remainder(a + math.pi, 2 * math.pi) - math.pi
+
+
+def _turn_z(r, a):
+ """r @ Rz(a) for rotations r [..., 3, 3] and angles a [...] (column mix, fewer ops than a matrix product)."""
+ c, s = torch.cos(a)[..., None], torch.sin(a)[..., None]
+ x, y = r[..., :, 0], r[..., :, 1]
+ return torch.stack((x * c + y * s, y * c - x * s, r[..., :, 2]), -1)
+
+
+# ---- collision points of the guard bodies ------------------------------------------------------------------------
+def collision_points(bodies=GUARD_BODIES):
+ """{body: (points [N, 3] in the body frame, radius [N])} of the arm collision geoms of the collector scene, exactly
+ as ``Scene.lowest`` reads them (``so101_grasp.geom_points``). Needs mujoco and the vendor model; cached."""
+ key = tuple(bodies)
+ if key not in _POINTS_CACHE:
+ import mujoco
+ import numpy as np
+
+ from nedm.contact_nrd.collect import so101_grasp as g
+ s = g.Scene(g.load_config())
+ m = s.m
+ out = {}
+ for name in bodies:
+ b = m.body(name).id
+ pts, rad = [], []
+ for gid, (p, r) in zip(s.arm_geoms, s.points):
+ if m.geom_bodyid[gid] != b:
+ continue
+ rot = np.zeros(9)
+ mujoco.mju_quat2Mat(rot, m.geom_quat[gid])
+ pts.append(p @ rot.reshape(3, 3).T + m.geom_pos[gid])
+ rad.append(np.full(len(p), r))
+ out[name] = (np.concatenate(pts), np.concatenate(rad))
+ _POINTS_CACHE[key] = out
+ return _POINTS_CACHE[key]
+
+
+def save_points(path, bodies=GUARD_BODIES):
+ """Write the collision points to an .npz (for machines without mujoco)."""
+ import numpy as np
+ pts = collision_points(bodies)
+ np.savez(path, bodies=np.array(list(bodies)), **{f"{b}_points": p for b, (p, _) in pts.items()},
+ **{f"{b}_radius": r for b, (_, r) in pts.items()})
+
+
+def reduce_points(points, radius, n_dirs=20000):
+ """Indices of the points that are lowest (point . u - radius smallest) for at least one of n_dirs directions u
+ (Fibonacci sphere): the decoder's fast floor set (module docstring for its error)."""
+ import numpy as np
+ i = np.arange(n_dirs) + 0.5
+ phi, th = np.arccos(1 - 2 * i / n_dirs), math.pi * (1 + 5 ** 0.5) * i
+ u = np.stack((np.cos(th) * np.sin(phi), np.sin(th) * np.sin(phi), np.cos(phi)), -1)
+ s = u @ np.asarray(points).T - np.asarray(radius)
+ return np.flatnonzero((s <= s.min(1, keepdims=True)).any(0))
+
+
+def load_points(path):
+ import numpy as np
+ f = np.load(path)
+ return {str(b): (f[f"{b}_points"], f[f"{b}_radius"]) for b in f["bodies"]}
+
+
+# ---- the kinematics ----------------------------------------------------------------------------------------------
+class SO101Kin:
+ """Batched FK, Jacobians, lowest point and IK of the SO101 on one device (float64 by default).
+
+ points: None (collision points from MuJoCo on the first ``lowest_point`` call), a path to a ``save_points`` .npz,
+ or the dict of ``collision_points``.
+ """
+
+ def __init__(self, device="cpu", dtype=torch.float64, points=None):
+ self.device, self.dtype = torch.device(device), dtype
+ f = dict(device=self.device, dtype=dtype)
+ self.pos = torch.tensor([t[2] for t in _TREE], **f)
+ self.rot = quat_mat(torch.tensor([t[3] for t in _TREE], **f))
+ self.parent = [t[1] for t in _TREE]
+ self.joint = [t[4] for t in _TREE]
+ self.point = torch.tensor(GRASP_POINT, **f)
+ self.tlo, self.thi = torch.tensor(TLO, **f), torch.tensor(THI, **f)
+ self.pan_axis = torch.tensor(PAN_AXIS_XY, **f)
+ self._points_src = points
+ self._guard = None
+
+ # -- forward kinematics --
+ def body_poses(self, q):
+ """q [..., >=5] (joint 5 = jaw needed for the moving jaw; missing -> 0) -> (pos [..., 8, 3], rot [..., 8, 3, 3])
+ of BODIES in the world."""
+ q = q.to(self.dtype)
+ lead = q.shape[:-1]
+ ps, rs = [], []
+ for k in range(len(_TREE)):
+ par, j = self.parent[k], self.joint[k]
+ if par < 0:
+ p = self.pos[k].expand(*lead, 3)
+ r = self.rot[k].expand(*lead, 3, 3)
+ else:
+ p = ps[par] + (rs[par] @ self.pos[k])
+ r = rs[par] @ self.rot[k]
+ if j is not None:
+ r = _turn_z(r, q[..., j] if j < q.shape[-1] else torch.zeros(lead, dtype=q.dtype, device=q.device))
+ ps.append(p)
+ rs.append(r)
+ return torch.stack(ps, -2), torch.stack(rs, -3)
+
+ def _chain(self, q):
+ """Bodies up to the gripper only (5 arm joints): positions and rotations lists."""
+ lead = q.shape[:-1]
+ p = self.pos[0].expand(*lead, 3)
+ r = self.rot[0].expand(*lead, 3, 3)
+ ps, rs = [p], [r]
+ for k in range(1, GRIPPER + 1):
+ p = p + (r @ self.pos[k])
+ r = _turn_z(r @ self.rot[k], q[..., self.joint[k]])
+ ps.append(p)
+ rs.append(r)
+ return ps, rs
+
+ def fk(self, q):
+ """q [..., >=5] -> grasp point [..., 3] (world) and gripper rotation [..., 3, 3]."""
+ ps, rs = self._chain(q.to(self.dtype))
+ return ps[-1] + rs[-1] @ self.point, rs[-1]
+
+ def jacobian(self, q):
+ """q [..., >=5] -> (jp [..., 3, 5], jr [..., 3, 5], grasp point, gripper rotation): world-frame Jacobians of the
+ grasp point and the gripper angular velocity in the 5 arm joints (mj_jac of the collector's Scene.ik)."""
+ ps, rs = self._chain(q.to(self.dtype))
+ p = ps[-1] + rs[-1] @ self.point
+ axes = torch.stack([rs[k][..., :, 2] for k in range(1, GRIPPER + 1)], -1) # [..., 3, 5]
+ lever = p[..., :, None] - torch.stack([ps[k] for k in range(1, GRIPPER + 1)], -1) # [..., 3, 5]
+ return torch.cross(axes, lever, dim=-2), axes, p, rs[-1]
+
+ # -- arm-table guard --
+ def _guard_points(self, exact=True):
+ """[(body index, points [N, 3] with radius 0, points [M, 3] with a radius, radii [M])] per guard body; exact
+ False: the extreme-point subset (``reduce_points``)."""
+ if self._guard is None:
+ src = self._points_src
+ pts = load_points(src) if isinstance(src, (str, Path)) else (src or collision_points())
+ f = dict(device=self.device, dtype=self.dtype)
+ self._guard = {}
+ for key in (True, False):
+ rows = []
+ for b, (p, r) in pts.items():
+ keep = reduce_points(p, r) if not key else slice(None)
+ p, r = p[keep], r[keep]
+ z = r == 0
+ rows.append((BODIES.index(b), torch.as_tensor(p[z], **f), torch.as_tensor(p[~z], **f),
+ torch.as_tensor(r[~z], **f)))
+ self._guard[key] = rows
+ return self._guard[exact]
+
+ def lowest_point(self, q, chunk=4096, per_body=False, exact=True, plane=None):
+ """Lowest world z (m) of the gripper and moving-jaw collision geoms at joint angles q [B, 6] -> [B]
+ (per_body: [B, 2] in GUARD_BODIES order). Arm-table guard of the NRD: lowest_point < 0.5 mm (critic 3.7).
+ exact False: the reduced point set (error <= 0.033 mm, module docstring). ``plane`` (c0, c1, c2): the lowest
+ signed height above the plane z = c0 + c1 x + c2 y instead (``table.py``; None: the old code)."""
+ q = q.to(self.dtype)
+ if plane is not None:
+ from nedm.so101_policy import table as TB
+ n_np, off = TB.normal(plane)
+ nv = torch.as_tensor(n_np, dtype=self.dtype, device=q.device)
+ out = []
+ for s in range(0, max(1, q.shape[0]), chunk):
+ pos, rot = self.body_poses(q[s: s + chunk])
+ cols = []
+ for b, p0, p1, rad in self._guard_points(exact):
+ if plane is None:
+ u = rot[:, b, 2, :] # world z row of the body rotation
+ base = pos[:, b, 2]
+ else:
+ u = torch.einsum("k,bkj->bj", nv, rot[:, b]) # normal row of the rotation
+ base = pos[:, b] @ nv - off
+ low = (u @ p0.T).amin(-1)
+ if len(rad):
+ low = torch.minimum(low, ((u @ p1.T) - rad).amin(-1))
+ cols.append(base + low)
+ out.append(torch.stack(cols, -1))
+ low = torch.cat(out)
+ return low if per_body else low.amin(-1)
+
+ def box_distance(self, q, centre, quat, half):
+ """Smallest distance (m) from the reduced gripper and moving-jaw collision points (minus their radius) to the box
+ of half size ``half`` (m) at ``centre`` [B, 3] with orientation ``quat`` [B, 4] (w x y z); <= 0 inside."""
+ q = q.to(self.dtype)
+ pos, rot = self.body_poses(q)
+ rc = quat_mat(quat.to(self.dtype))
+ best = None
+ for b, p0, p1, rad in self._guard_points(False):
+ for pts, r in ((p0, None), (p1, rad)):
+ if not len(pts):
+ continue
+ w = pos[:, b, None, :] + pts @ rot[:, b].transpose(-1, -2) # [B, N, 3] world
+ loc = (w - centre.to(w)[:, None, :]) @ rc # cube frame
+ d = (loc.abs() - half).clamp_min(0.0).norm(dim=-1)
+ d = d - r if r is not None else d
+ d = d.amin(-1)
+ best = d if best is None else torch.minimum(best, d)
+ return best
+
+ # -- inverse kinematics --
+ def ik(self, q0, pos, rot=None, w_rot=0.1, iters=150, damping=1e-4):
+ """Scene.ik, batched: damped least squares on the 5 arm joints for the grasp point at ``pos`` [B, 3] and the
+ gripper rotation ``rot`` [B, 3, 3] (None: position only), rotation weight w_rot (m/rad), joints clipped to
+ TLO..THI. Per world the same stopping rules (error below 1e-6 m and 1e-5 rad; every 10 iterations, stop when
+ 10 iterations gained less than 10 %). q0 [B, >=5] -> (q [B, 5], position error [B] m, angle error [B] rad)."""
+ q = q0[..., :5].to(self.dtype).clone()
+ b = q.shape[0]
+ lo, hi = self.tlo[:5], self.thi[:5]
+ active = torch.ones(b, dtype=torch.bool, device=q.device)
+ last = torch.full((b,), math.inf, dtype=self.dtype, device=q.device)
+ eye = torch.eye(6, dtype=self.dtype, device=q.device)
+ for it in range(iters):
+ jp, jr, p, r = self.jacobian(q)
+ ep = pos - p
+ er = rotvec(rot @ r.transpose(-1, -2)) if rot is not None else torch.zeros_like(ep)
+ nep, ner = ep.norm(dim=-1), er.norm(dim=-1)
+ err = nep + w_rot * ner
+ active = active & ~((nep < 1e-6) & (ner < 1e-5))
+ if it % 10 == 0:
+ active = active & ~(err > 0.9 * last)
+ last = torch.where(active, err, last)
+ if not bool(active.any()):
+ break
+ jac = torch.cat((jp, w_rot * jr), -2) # [B, 6, 5]
+ rhs = torch.cat((ep, w_rot * er), -1)[..., None]
+ dq = (jac.transpose(-1, -2) @ torch.linalg.solve(jac @ jac.transpose(-1, -2) + damping * eye, rhs))[..., 0]
+ q = torch.where(active[:, None], torch.minimum(torch.maximum(q + dq, lo), hi), q)
+ p, r = self.fk(q)
+ ea = rotvec(rot @ r.transpose(-1, -2)).norm(dim=-1) if rot is not None else torch.zeros_like(p[:, 0])
+ return q, (pos - p).norm(dim=-1), ea
+
+ def pose_ik(self, q0, pos, rot, max_tilt=None):
+ """Scene.pose_ik, batched: within IK_TOL_M / IK_TOL_RAD, or else (max_tilt given, rad) the position within
+ IK_TOL_M and the orientation within max_tilt (second IK from the first result, w_rot 0.001, 600 iterations).
+ -> (q [B, 5], ok [B], position error, angle error)."""
+ q, ep, ea = self.ik(q0, pos, rot)
+ ok = (ep < IK_TOL_M) & (ea < IK_TOL_RAD)
+ if max_tilt is not None and not bool(ok.all()):
+ redo = ~ok
+ q2, ep2, ea2 = self.ik(q[redo], pos[redo], rot[redo], w_rot=0.001, iters=600)
+ ok2 = (ep2 < IK_TOL_M) & (ea2 < max_tilt)
+ q, ep, ea, ok = q.clone(), ep.clone(), ea.clone(), ok.clone()
+ q[redo], ep[redo], ea[redo], ok[redo] = q2, ep2, ea2, ok2
+ return q, ok, ep, ea
+
+ def seeds(self, pos, yaw):
+ """Scene.solve's 3 starting guesses [3, B, 5]: [pan, lift in (0, -0.6, 0.6), 0.6, 1.1, wrap(yaw - pan)]."""
+ pan = torch.atan2(pos[:, 1] - self.pan_axis[1], pos[:, 0] - self.pan_axis[0])
+ roll = wrap(yaw - pan)
+ return torch.stack([torch.stack((pan, torch.full_like(pan, lift), torch.full_like(pan, 0.6),
+ torch.full_like(pan, 1.1), roll), -1) for lift in (0.0, -0.6, 0.6)])
+
+ def ik_topdown(self, q0, pos, yaw, max_tilt=None, seeds=True):
+ """Scene.solve for a top-down gripper at the yaw, batched: the hint q0 [B, >=5] (None: no hint) and then (seeds)
+ the 3 standard guesses, all first within the tight tolerances, then (max_tilt) all with the tilt fallback; the
+ first guess that succeeds wins, as in the collector. -> (q [B, 5], ok [B], position error [B] m, angle error
+ [B] rad); worlds without a solution keep the last guess's result and ok False."""
+ pos = pos.to(self.dtype)
+ yaw = yaw.to(self.dtype)
+ rot = rotz(yaw)
+ guesses = ([] if q0 is None else [q0[..., :5].to(self.dtype)]) + (list(self.seeds(pos, yaw)) if seeds else [])
+ b = pos.shape[0]
+ out_q = torch.zeros(b, 5, dtype=self.dtype, device=pos.device)
+ out_ep = torch.full((b,), math.inf, dtype=self.dtype, device=pos.device)
+ out_ea = torch.full((b,), math.inf, dtype=self.dtype, device=pos.device)
+ done = torch.zeros(b, dtype=torch.bool, device=pos.device)
+ strict = []
+ for g in guesses:
+ q, ep, ea = self.ik(g, pos, rot)
+ strict.append(q)
+ ok = (ep < IK_TOL_M) & (ea < IK_TOL_RAD) & ~done
+ out_q[ok], out_ep[ok], out_ea[ok] = q[ok], ep[ok], ea[ok]
+ done |= ok
+ out_q[~done], out_ep[~done], out_ea[~done] = q[~done], ep[~done], ea[~done]
+ if max_tilt is not None:
+ for qs in strict:
+ todo = ~done
+ if not bool(todo.any()):
+ break
+ q, ep, ea = self.ik(qs[todo], pos[todo], rot[todo], w_rot=0.001, iters=600)
+ ok = (ep < IK_TOL_M) & (ea < max_tilt)
+ idx = torch.nonzero(todo).flatten()
+ out_q[idx], out_ep[idx], out_ea[idx] = q, ep, ea
+ done[idx[ok]] = True
+ return out_q, done, out_ep, out_ea
+
+ def ik_track(self, q0, pos, rot, iters=3, w_rot=0.01, damping=1e-6, step_max=0.1):
+ """Warm-started IK for a target that moves a little every step (the command decoder): ``iters`` damped
+ least-squares iterations on the grasp-point position and the gripper rotation ``rot`` (rotation-vector error)
+ weighted w_rot (m/rad). Where ``rot`` is reachable (top-down below a grasp-point height of about 6-7 cm) the
+ solution is exact, the collector's (Scene.pose_ik within tolerance); above it (the wrist-flex limit) it
+ minimises |position error|^2 + w_rot^2 |rotation error|^2: position errors of a few 0.1 mm for the least
+ rotation error, between the collector's two stages (weights 0.1 and 0.001). One weight with small damping
+ converges in a few iterations per step and gives a consistent solution from step to step (a two-stage tracker,
+ 3 + 3 iterations at 0.1 and 0.001, alternated between two solutions at large tilts; a task-priority tracker
+ stalled 1.3 mm off where the reach needs the wrist flex off its limit; both 2026-10-11). A joint at its limit
+ (TLO..THI) that a step would push further leaves that step's Jacobian, and an iteration changes a joint by at
+ most step_max (rad); fixed shapes, no early stop; orientation errors by rotvec_fast.
+ -> (q [B, 5], position error [B] m, angle error [B] rad)."""
+ q = q0[..., :5].to(self.dtype)
+ lo, hi = self.tlo[:5], self.thi[:5]
+ eye = torch.eye(6, dtype=self.dtype, device=q.device)
+ for _ in range(iters):
+ jp, jr, p, r = self.jacobian(q)
+ jac0 = torch.cat((jp, w_rot * jr), -2) # [B, 6, 5]
+ rhs = torch.cat((pos - p, w_rot * rotvec_fast(rot @ r.transpose(-1, -2))), -1)[..., None]
+ free = torch.ones_like(q)
+ for _ in range(2): # a joint at its limit that the step would push further leaves the Jacobian
+ jac = jac0 * free[:, None, :]
+ jt = jac.transpose(-1, -2)
+ dq = (jt @ torch.linalg.solve(jac @ jt + damping * eye, rhs))[..., 0]
+ # (a dead band: a rounding-level step must not flip the active set between devices / batch layouts)
+ stuck = ((q >= hi - 1e-9) & (dq > 1e-12)) | ((q <= lo + 1e-9) & (dq < -1e-12))
+ free = free * (~stuck).to(free)
+ big = dq.abs().amax(-1, keepdim=True)
+ dq = dq * torch.where(big > step_max, step_max / big.clamp_min(1e-12), torch.ones_like(big))
+ q = torch.minimum(torch.maximum(q + dq, lo), hi)
+ p, r = self.fk(q)
+ return q, (pos - p).norm(dim=-1), rotvec_fast(rot @ r.transpose(-1, -2)).norm(dim=-1)
diff --git a/so101_pick_place/code/src/nedm/so101_policy/mujoco_env.py b/so101_pick_place/code/src/nedm/so101_policy/mujoco_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5ed9039372cb223a32c69d8f999118aa01188a4
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/mujoco_env.py
@@ -0,0 +1,915 @@
+"""Batched CPU MuJoCo worlds of the SO101 grasp collector scene (spec 2.7): joint targets in, ``WorldState`` out.
+
+The physics is the collector's (``nedm.contact_nrd.collect.so101_grasp.Scene``: Menagerie SO101, table, 30 mm cube,
+0.5 ms implicitfast, elliptic cones, Newton solver, tolerance 1e-10). One ``step`` = one 20 ms command = 2 records of
+20 physics steps, the command clipped to the collector's target range and cast to float32 (the applied value, as
+``run_episode``). Worlds are split in contiguous blocks over worker processes (``workers`` > 0; numpy + mujoco only,
+commands and arrays over pipes) or run in this process (``workers=0``). CPU MuJoCo is deterministic: the same starts
+and commands give bit-identical states for any worker count. Units SI, world frame z up, table top z = 0, arm base at
+the origin.
+
+WorldState definitions = the grasp NRD data (``collect.so101_grasp.run_episode`` records, stored float32, then
+``data.step_average_rates`` with the 20 ms model step; ``float32_records=False`` skips the float32 rounding):
+
+- ``q``: joint angles (``qpos``) at the end of the command. ``qd``: 20 ms step average (q(t) - q(t - 20 ms)) / 0.02.
+- ``cube_pos``; ``cube_quat`` w x y z: the TRUE orientation, unit (``export.quat_continuous``: w >= 0 at the reset
+ record, then sign continuous over every 10 ms record).
+- ``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
+ the world frame (computed by ``data.step_average_rates`` itself). After ``reset`` / ``set_cube`` the rates are the
+ instantaneous ones (MuJoCo qvel, spin rotated to the world frame), as the first record of a data episode.
+- ``contact`` [fixed jaw-cube, moving jaw-cube, cube-table]: physical label of a step = the pair's summed normal
+ force (first efc row of each elliptic contact = mj_contactForce normal) above ``contact_threshold_n`` (0.01 N) in
+ any of the 40 physics steps of the command = OR of the data's two 10 ms interval labels = ``data.physical_labels``.
+ ``contact_rule="gate"`` (default) reports the NRD switch meaning instead: the physical label of this step OR of the
+ step before (``data.model_labels`` of the previous grid state; the first step after a reset has no step before),
+ the meaning of ``GraspNrdSim``'s default contact (review_spec_feasibility sec. 9). Both views are attributes.
+ After a reset / set_cube: the forces of one ``mj_forward`` at that state. Nothing in reward, success or
+ observation should read it (spec v2 B2).
+- ``arm_table``: the same force rule for any arm geom (gripper, moving jaw, other links, base hulls) against the table.
+- ``invalid``: any other collector end condition (``so101_grasp.TERMINAL``), checked as the collector does:
+ cube_other_link (cube against shoulder / upper arm / lower arm / wrist / camera mount geoms), arm_self (arm-arm
+ contact), cube_base (cube against the base hulls) - all with the force rule above; cube_off_table (cube centre x
+ 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
+ more than 1 mm inside the visual meshes of the gripper or the moving jaw beyond the collision penetration, at
+ either record of the step); plus numerical failure (``mjWARN_BADQACC`` or non-finite qpos / qvel; the collector
+ rejects such episodes).
+
+Flags are per step (this command); physics always runs the whole command and never stops a world. ``end_reason``
+[B] keeps the FIRST end since the reset (TERMINAL index, ``NUMERICAL`` = 7; collector precedence inside a record:
+numerical, contact kinds in TERMINAL order, off table, overlap) and ``end_step`` the step that raised it; a collector
+episode ends exactly there (the data's last grid state is the one before). ``step_code`` is the code of the last
+command alone.
+
+Starts: ``sample_starts(seeds)`` draws fresh task starts with the collector's sampler (``task_start``) and warm-up;
+``reset(idx, starts, warmup=True)`` reproduces them bit for bit, ``starts["state"]`` is the same settled state for the
+NRD world. ``nrd_state`` / ``world_from_nrd`` convert WorldState <-> the NRD's [B, D, S] layout (``model.finish``).
+
+The visual-overlap grids need scipy once (``VisualOverlap``); they are cached as .npz (``overlap_cache_dir``) and
+then load in any interpreter. Interpolation uses scipy's ``map_coordinates`` when present, else ``_map_linear``
+(numpy trilinear, the same float32 result except within an ulp; only the 1 mm threshold decision depends on it).
+
+ python -m nedm.so101_policy.mujoco_env overlap-cache # build the overlap cache (needs scipy, about 2-6 s)
+"""
+from __future__ import annotations
+
+import hashlib
+import inspect
+import json
+import os
+import pickle
+import subprocess
+import sys
+from dataclasses import fields
+from pathlib import Path
+
+import numpy as np
+
+try: # the worker side needs only numpy and mujoco (and runs in torch-free interpreters such as the env nrdsim)
+ if os.environ.get("NEDM_MJ_WORKER") == "1":
+ raise ImportError("worker process: no torch")
+ import torch
+
+ from nedm.so101_policy.world import CONTROL_DT, JOINTS, WorldState
+except ImportError:
+ torch = None
+ CONTROL_DT, JOINTS = 0.02, 6
+
+RAW = 25 # raw record: q 6, qvel 6, cube pos 3, quat 4 (unit, sign continuous), v 3, w 3 (world)
+NUMERICAL = 7 # end code after so101_grasp.TERMINAL ("end", arm_table, ..., cube_visual_overlap)
+REST_Z = 0.014993169 # cube centre z (m) of a flat cube resting on the table after the 0.3 s warm-up (luffy,
+ # 40 starts, spread < 1e-15 m): the height for set_cube disturbances
+ARM_TABLE = 1
+CUBE_NAMES = ("x", "y", "z", "qw", "qx", "qy", "qz", "vx", "vy", "vz", "wx", "wy", "wz")
+JOINT_NAMES = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper")
+SRC_ROOT = Path(__file__).resolve().parents[2]
+DEFAULT_CACHE = Path(os.environ.get("NEDM_SO101_OVERLAP_CACHE", Path.home() / ".cache" / "nedm" / "so101_overlap"))
+# bodies of the two data channels sets, as data.step_average_rates reads them (system.json kinds and channel types)
+_RATE_SYSTEM = {"bodies": [
+ {"name": "arm", "kind": "articulated", "moving": True, "channel_types": ["angle"] * 6 + ["angular_rate"] * 6},
+ {"name": "cube", "kind": "rigid", "moving": True,
+ "channel_types": ["position"] * 3 + ["quaternion"] * 4 + ["velocity"] * 3 + ["angular_velocity"] * 3}]}
+if 2 * 0.01 != CONTROL_DT: # the data's step = stride x record step
+ raise AssertionError("CONTROL_DT must equal 2 x 10 ms")
+
+
+def end_names():
+ from nedm.contact_nrd.collect.so101_grasp import TERMINAL
+ return list(TERMINAL) + ["numerical"]
+
+
+# ---- visual-overlap grids: cache and scipy-free interpolation ----------------------------------------------------
+def _map_linear(input, coordinates, order=1, mode="nearest"):
+ """scipy.ndimage.map_coordinates(input [nx, ny, nz], coordinates [3, N], order=1, mode="nearest") in numpy:
+ trilinear interpolation, coordinates clamped to the grid; result in input's dtype."""
+ if order != 1 or mode != "nearest":
+ raise ValueError("only order=1, mode='nearest'")
+ shape = np.asarray(input.shape)
+ c = np.clip(np.asarray(coordinates, np.float64), 0.0, (shape - 1)[:, None])
+ i0 = np.minimum(np.floor(c).astype(np.int64), np.maximum(shape - 2, 0)[:, None])
+ t = c - i0
+ out = np.zeros(c.shape[1])
+ for a in (0, 1):
+ wa = t[0] if a else 1.0 - t[0]
+ for b in (0, 1):
+ wb = t[1] if b else 1.0 - t[1]
+ for e in (0, 1):
+ we = t[2] if e else 1.0 - t[2]
+ out += input[i0[0] + a, i0[1] + b, i0[2] + e] * (wa * wb * we)
+ return out.astype(input.dtype)
+
+
+def _overlap_key(s) -> str:
+ """sha256 of everything the overlap grids depend on: the meshes and poses of the visual geoms of the two bodies,
+ the overlap config and the source of VisualOverlap."""
+ from nedm.contact_nrd.collect import so101_grasp as g
+ m, h = s.m, hashlib.sha256()
+ h.update(json.dumps(s.cfg["visual_overlap"], sort_keys=True).encode())
+ h.update(inspect.getsource(g.VisualOverlap).encode())
+ for b in s.overlap_bodies:
+ for gid in np.flatnonzero(m.geom_bodyid == b):
+ if m.geom_type[gid] != 7 or m.geom_contype[gid] or m.geom_conaffinity[gid]: # 7 = mjGEOM_MESH
+ continue
+ k = m.geom_dataid[gid]
+ v = m.mesh_vert[m.mesh_vertadr[k]: m.mesh_vertadr[k] + m.mesh_vertnum[k]]
+ f = m.mesh_face[m.mesh_faceadr[k]: m.mesh_faceadr[k] + m.mesh_facenum[k]]
+ for x in (v, f, m.geom_pos[gid], m.geom_quat[gid]):
+ h.update(np.ascontiguousarray(x).tobytes())
+ return h.hexdigest()[:24]
+
+
+_FIELDS = ("lo", "hi", "h", "sdf", "cell", "ncell", "points", "start", "parity_disagreements")
+
+
+def install_overlap(s, cache_dir=None, build=True):
+ """Give Scene ``s`` its VisualOverlap grids from the cache (``cache_dir``, default $NEDM_SO101_OVERLAP_CACHE or
+ ~/.cache/nedm/so101_overlap);
+ if missing and ``build``: build them (scipy) and write the cache. -> path of the cache file."""
+ from nedm.contact_nrd.collect import so101_grasp as g
+ path = Path(cache_dir or DEFAULT_CACHE) / f"overlap_{_overlap_key(s)}.npz"
+ try:
+ from scipy.ndimage import map_coordinates
+ except ImportError:
+ map_coordinates = _map_linear
+ if not path.exists():
+ if not build:
+ raise FileNotFoundError(path)
+ try:
+ import scipy # noqa: F401
+ except ImportError as e:
+ raise RuntimeError(f"overlap cache {path} missing and no scipy here: run `python -m "
+ "nedm.so101_policy.mujoco_env overlap-cache` once with an interpreter that has scipy "
+ "(conda env nrdsim or kyle_madrona), or pass overlap=False") from e
+ grids = s.overlap
+ path.parent.mkdir(parents=True, exist_ok=True)
+ arrays = {f"{n}_{f}": np.asarray(getattr(o, f)) for n, o in enumerate(grids.values()) for f in _FIELDS}
+ arrays["meshes"] = np.array(json.dumps([o.meshes for o in grids.values()]))
+ tmp = path.with_suffix(f".{os.getpid()}.tmp.npz")
+ np.savez(tmp, **arrays)
+ tmp.replace(path)
+ with np.load(path) as z:
+ meshes = json.loads(str(z["meshes"]))
+ grids = {}
+ for n, b in enumerate(s.overlap_bodies):
+ o = object.__new__(g.VisualOverlap)
+ for f in _FIELDS:
+ x = z[f"{n}_{f}"]
+ setattr(o, f, x if x.ndim else x.item())
+ o.map, o.meshes = map_coordinates, meshes[n]
+ grids[b] = o
+ s._overlap = grids
+ return path
+
+
+# ---- worker side: worlds of one block -----------------------------------------------------------------------------
+class _Block:
+ """n worlds in one process: one collector Scene (model, kinematics workspace ``dk``, overlap grids) and one MjData
+ per world. All arrays numpy float64; the methods return dicts of arrays for the main process."""
+
+ def __init__(self, n, overlap=True, cache_dir=None, overlap_margin=0.02, cpus=None, labels="exact"):
+ if cpus:
+ os.sched_setaffinity(0, cpus)
+ import mujoco
+ from nedm.contact_nrd.collect import so101_grasp as g
+ self.mj, self.g = mujoco, g
+ self.s = s = g.Scene(g.load_config())
+ self.m = s.m
+ self.data = [mujoco.MjData(s.m) for _ in range(n)]
+ self.n = n
+ self.kind = s.kind[s.cls[:, None], s.cls[None, :]] # contact class of a geom pair, -1 none
+ self.kind_list, self.ngeom = self.kind.ravel().tolist(), int(s.m.ngeom)
+ self.thr = s.thr
+ self.cube = s.cube_body
+ self.prev_q = np.zeros((n, 4)) # last recorded quaternion (sign continuity)
+ self.nbad = np.zeros(n, np.int64) # BADQACC count at the last check
+ self.overlap = bool(overlap)
+ self.cache = install_overlap(s, cache_dir) if overlap else None
+ self.margin = float(overlap_margin)
+ if overlap: # body-frame bounding boxes of the overlap grids, for the conservative prefilter
+ self.boxes = [(b, o.lo - self.margin, o.hi + self.margin) for b, o in s._overlap.items()]
+ self.badqacc = mujoco.mjtWarning.mjWARN_BADQACC
+ if labels not in ("exact", "record"):
+ raise ValueError("labels is 'exact' (forces after every physics step) or 'record' (once per 10 ms)")
+ self.exact = labels == "exact"
+ self.plane = None # table plane (``set_table``); None: z = 0
+
+ def set_table(self, plane=None):
+ """Put the table top on the plane z = c0 + c1 x + c2 y (``table.py``; None: back to the collector's z = 0) for
+ every world of the block (the compiled model is shared). The cube-off-table height test follows the plane.
+ Starts are world poses: a caller moves task starts onto the plane itself (``table.map_cube``)."""
+ from nedm.so101_policy import table as TB
+ m = self.m
+ gid = m.geom("table").id
+ if not hasattr(self, "_table0"):
+ self._table0 = (m.geom_pos[gid].copy(), m.geom_quat[gid].copy(), int(m.geom_sameframe[gid]))
+ plane = None if plane is None or not any(plane) else tuple(float(c) for c in plane)
+ pos, quat = TB.table_geom(plane, *self._table0[:2])
+ m.geom_pos[gid], m.geom_quat[gid] = pos, quat
+ # the compiler marked the axis-aligned table "same rotation as its body" (mj_kinematics then ignores
+ # geom_quat): a tilted table needs the full local frame
+ m.geom_sameframe[gid] = self._table0[2] if TB.is_flat(plane) else 0
+ self.plane = plane
+ return dict(plane=plane, table_pos=pos.tolist(), table_quat=quat.tolist())
+
+ def info(self):
+ return dict(pid=os.getpid(), cache=str(self.cache), n=self.n, python=sys.executable,
+ mujoco=self.mj.__version__, numpy=np.__version__, tlo=self.s.tlo.tolist(), thi=self.s.thi.tolist())
+
+ # -- collector arithmetic --
+ def _forces(self, d):
+ """Summed normal force [7] by collector contact kind of the contacts in d (Scene.contact_forces()[0][:7])."""
+ n = d.ncon
+ c = d.contact
+ a = c.efc_address[:n]
+ f = np.where(a >= 0, d.efc_force[np.maximum(a, 0)], 0.0)
+ k = self.kind[c.geom1[:n], c.geom2[:n]]
+ ok = k >= 0
+ return np.bincount(k[ok], weights=f[ok], minlength=7)
+
+ def _forces_list(self, d):
+ """_forces as a list, in a Python loop over the contacts: the same sums in the same order (bit-identical),
+ about 3x cheaper for the few contacts of this scene (5.6 vs 14.8 us at 4 contacts, luffy)."""
+ out = [0.0] * 7
+ n = d.ncon
+ if n:
+ c, ef, kl, ng = d.contact, d.efc_force, self.kind_list, self.ngeom
+ for (g1, g2), ad in zip(c.geom[:n].tolist(), c.efc_address[:n].tolist()):
+ k = kl[g1 * ng + g2]
+ if k >= 0 and ad >= 0: # ad < 0: the collector adds 0.0
+ out[k] += float(ef[ad])
+ return out
+
+ def _near(self, d):
+ """False if the cube is surely more than overlap_margin away from both overlap grids (bounding boxes in the
+ body frames, poses of d: then visual_overlap is exactly 0)."""
+ s = self.s
+ rc, c = d.xmat[self.cube].reshape(3, 3), d.xpos[self.cube]
+ for b, lo, hi in self.boxes:
+ rb = d.xmat[b].reshape(3, 3)
+ ext = s.half * np.abs(rb.T @ rc).sum(1)
+ cb = (c - d.xpos[b]) @ rb
+ if not (((cb + ext) < lo).any() or ((cb - ext) > hi).any()):
+ return True
+ return False
+
+ def _overlap_now(self, d, fresh):
+ """Visual overlap (m) of the current state of d. fresh: d holds the kinematics and contacts of its state
+ (after mj_forward), as at the collector's record check; else they are recomputed in the workspace dk
+ (Scene.overlap_at, the collector's last-record check)."""
+ if not self.overlap or not self._near(d):
+ return 0.0
+ return self.s.visual_overlap(d) if fresh else self.s.overlap_at(d.qpos)
+
+ def _record_end(self, d, i, bad, fresh):
+ """End code after a record (0 = none), collector order; and the per-flag conditions."""
+ s, g = self.s, self.g
+ num = d.warning[self.badqacc].number != self.nbad[i] or not (np.isfinite(d.qpos).all() and np.isfinite(d.qvel).all())
+ self.nbad[i] = d.warning[self.badqacc].number
+ hit = bad > self.thr
+ p = d.qpos[s.cq: s.cq + 3]
+ pz = p[2] if self.plane is None else p[2] - (self.plane[0] + self.plane[1] * p[0] + self.plane[2] * p[1])
+ off = bool((p[:2] < s.table_lo).any() or (p[:2] > s.table_hi).any() or pz < -0.01)
+ ov = self._overlap_now(d, fresh) > s.overlap_thr
+ code = NUMERICAL if num else 1 + int(np.argmax(hit)) if hit.any() else (
+ g.TERMINAL.index("cube_off_table") if off else g.TERMINAL.index("cube_visual_overlap") if ov else 0)
+ return code, bool(hit[0]), bool(num or hit[1:].any() or off or ov)
+
+ def _record(self, d, i, first=False):
+ """Raw record [25] of d (Scene.state, quaternion as export.quat_continuous)."""
+ s = self.s
+ s.d = d
+ arm, cube = s.state()
+ q = cube[3:7]
+ q = q / np.linalg.norm(q[None], axis=-1, keepdims=True)[0]
+ if (first and q[0] < 0) or (not first and np.dot(self.prev_q[i], q) < 0):
+ q = -q
+ self.prev_q[i] = q
+ cube[3:7] = q
+ return np.concatenate((arm, cube))
+
+ def _now(self, d, i, first):
+ """Outputs of a state without a step (after a reset or a cube move; d after mj_forward)."""
+ f = self._forces(d) if d.ncon else np.zeros(7)
+ if first:
+ self.nbad[i] = 0
+ code, at, inv = self._record_end(d, i, f[3:7], fresh=True)
+ return self._record(d, i, first), f[:3] > self.thr, at, inv, code, f
+
+ def _pack(self, rows):
+ raw, lab, at, inv, code, force = zip(*rows)
+ return dict(raw=np.array(raw), contact=np.array(lab, bool), arm_table=np.array(at, bool),
+ invalid=np.array(inv, bool), code=np.array(code, np.int8), force=np.array(force))
+
+ # -- API --
+ def reset(self, rows, start, ctrl=None, warmup=False, spawn=False):
+ """Worlds ``rows`` to the packed starts [n, 25] (raw layout). warmup: Scene.reset (arm targets = q, cube
+ resting at its pose, or parked and then placed with its v, w for spawn; 0.3 s; time 0). Else the exact
+ state: qpos / qvel from the start (cube spin world -> body), targets ``ctrl`` (default q), mj_forward."""
+ mj, s = self.mj, self.s
+ out = []
+ for k, i in enumerate(rows):
+ d, x = self.data[i], start[k]
+ s.d = d
+ q = x[15:19] / np.linalg.norm(x[15:19])
+ if warmup:
+ s.reset(x[0:6], x[12:15], x[15:19], x[19:22], x[22:25], bool(spawn)) # quaternion as given
+ else:
+ mj.mj_resetData(s.m, d)
+ d.qpos[s.qadr], d.qvel[s.vadr] = x[0:6], x[6:12]
+ d.qpos[s.cq: s.cq + 3], d.qpos[s.cq + 3: s.cq + 7] = x[12:15], q
+ d.qvel[s.cv: s.cv + 3] = x[19:22]
+ d.qvel[s.cv + 3: s.cv + 6] = self.g.quat_mat(q).T @ x[22:25]
+ u = x[0:6] if ctrl is None else ctrl[k]
+ d.ctrl[s.act] = np.clip(u, s.tlo, s.thi).astype(np.float32)
+ d.time = 0.0
+ mj.mj_forward(s.m, d)
+ out.append(self._now(d, i, first=True))
+ return self._pack(out)
+
+ def set_cube(self, rows, pose):
+ """Move the cube of worlds ``rows``: pose [n, 13] = pos, quat (w x y z), world v, world w; mj_forward."""
+ mj, s = self.mj, self.s
+ out = []
+ for k, i in enumerate(rows):
+ d, x = self.data[i], pose[k]
+ q = x[3:7] / np.linalg.norm(x[3:7])
+ d.qpos[s.cq: s.cq + 3], d.qpos[s.cq + 3: s.cq + 7] = x[0:3], q
+ d.qvel[s.cv: s.cv + 3] = x[7:10]
+ d.qvel[s.cv + 3: s.cv + 6] = self.g.quat_mat(q).T @ x[10:13]
+ mj.mj_forward(s.m, d)
+ out.append(self._now(d, i, first=False))
+ return self._pack(out)
+
+ def step(self, targets):
+ """One 20 ms command for every world of the block: targets [n, 6] -> raw records, flags, end codes, and the
+ 10 ms records of the step (``mid`` = the record after the first 10 ms; ``rec_contact`` [n, 2, 3] the
+ collector's interval labels of the two 10 ms intervals)."""
+ mj, s, m = self.mj, self.s, self.m
+ u_all = np.clip(targets, s.tlo, s.thi).astype(np.float32) # stored and applied (run_episode)
+ out, mids, rlab = [], [], []
+ for i, d in enumerate(self.data):
+ u = u_all[i]
+ at, inv, code = False, False, 0
+ force, rl = np.zeros(7), np.zeros((s.per_ctrl, 3), bool)
+ for r in range(s.per_ctrl):
+ d.ctrl[s.act] = u
+ if self.exact:
+ mx = [0.0] * 7 # largest summed force per kind over the record's physics steps
+ for _ in range(s.nsub):
+ mj.mj_step(m, d)
+ if d.ncon:
+ mx = [a if a >= b else b for a, b in zip(mx, self._forces_list(d))]
+ else: # same physics; forces of the last physics step of the record only
+ mj.mj_step(m, d, nstep=s.nsub)
+ mx = self._forces_list(d)
+ mx = np.array(mx)
+ fmax, bad = mx[:3], mx[3:7]
+ rl[r] = fmax > self.thr
+ force = np.maximum(force, mx)
+ c, a, v = self._record_end(d, i, bad, fresh=False)
+ code, at, inv = code or c, at or a, inv or v
+ if r + 1 < s.per_ctrl:
+ mids.append(self._record(d, i)) # the mid-step record (also keeps the quaternion sign continuous)
+ rlab.append(rl)
+ out.append((self._record(d, i), rl.any(0), at, inv, code, force))
+ res = self._pack(out)
+ res["mid"], res["rec_contact"] = np.array(mids).reshape(len(self.data), -1, RAW), np.array(rlab, bool)
+ return res
+
+
+def _enc(x):
+ if isinstance(x, np.ndarray):
+ return ("__nd__", x.dtype.str, x.shape, x.tobytes())
+ if isinstance(x, dict):
+ return {k: _enc(v) for k, v in x.items()}
+ return x
+
+
+def _dec(x):
+ if isinstance(x, tuple) and len(x) == 4 and x[0] == "__nd__":
+ return np.frombuffer(x[3], dtype=x[1]).reshape(x[2]).copy()
+ if isinstance(x, dict):
+ return {k: _dec(v) for k, v in x.items()}
+ return x
+
+
+def _serve():
+ """Worker process: pickled (method, kwargs) on stdin -> pickled result on the original stdout (MuJoCo and
+ other prints go to stderr)."""
+ import faulthandler
+ import traceback
+ faulthandler.enable() # a crash in MuJoCo prints the Python stack to stderr
+ inp = sys.stdin.buffer
+ out = os.fdopen(os.dup(1), "wb")
+ os.dup2(2, 1)
+ block = None
+ while True:
+ try:
+ cmd, kw = pickle.load(inp)
+ except EOFError:
+ return
+ if cmd == "close":
+ return
+ try:
+ kw = _dec(kw)
+ if cmd == "init":
+ block = _Block(**kw)
+ res = block.info()
+ else:
+ res = getattr(block, cmd)(**kw)
+ msg = ("ok", _enc(res))
+ except Exception: # noqa: BLE001 - sent to the main process
+ msg = ("error", traceback.format_exc())
+ pickle.dump(msg, out, protocol=4)
+ out.flush()
+
+
+class _Proc:
+ """A worker process running _serve()."""
+
+ def __init__(self, python):
+ code = f"import sys; sys.path.insert(0, {str(SRC_ROOT)!r}); from nedm.so101_policy.mujoco_env import _serve; _serve()"
+ env = dict(os.environ, OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1", MKL_NUM_THREADS="1", NEDM_MJ_WORKER="1")
+ # -P: no current directory on sys.path (python >= 3.11; every interpreter of this study is 3.12)
+ self.p = subprocess.Popen([python, "-P", "-c", code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env)
+
+ def send(self, cmd, **kw):
+ pickle.dump((cmd, _enc(kw)), self.p.stdin, protocol=4)
+ self.p.stdin.flush()
+
+ def recv(self):
+ try:
+ status, res = pickle.load(self.p.stdout)
+ except EOFError:
+ raise RuntimeError(f"MuJoCo worker {self.p.pid} died (exit {self.p.poll()}); see its stderr") from None
+ if status != "ok":
+ raise RuntimeError(f"MuJoCo worker {self.p.pid} failed:\n{res}")
+ return _dec(res)
+
+ def close(self):
+ if self.p.poll() is None:
+ try:
+ self.send("close")
+ self.p.wait(timeout=10)
+ except Exception: # noqa: BLE001
+ self.p.kill()
+ self.p.wait()
+ for f in (self.p.stdin, self.p.stdout):
+ try:
+ f.close()
+ except Exception: # noqa: BLE001
+ pass
+
+
+class _Local:
+ """The same interface in this process (workers=0)."""
+
+ def __init__(self):
+ self.block, self.res = None, None
+
+ def send(self, cmd, **kw):
+ if cmd == "init":
+ self.block = _Block(**kw)
+ self.res = self.block.info()
+ elif cmd != "close":
+ self.res = getattr(self.block, cmd)(**kw)
+
+ def recv(self):
+ return self.res
+
+ def close(self):
+ pass
+
+
+# ---- main side ----------------------------------------------------------------------------------------------------
+def _get(start, name):
+ return start.get(name) if isinstance(start, dict) else getattr(start, name, None)
+
+
+def pack_start(start, n=None) -> np.ndarray:
+ """WorldState-like (attributes or dict keys q, qd, cube_pos, cube_quat, cube_v, cube_w; qd, cube_v, cube_w may be
+ missing = 0) -> raw rows [n, 25] float64 (numpy)."""
+ q = np.asarray(_tonp(_get(start, "q")), np.float64)
+ n = q.reshape(-1, JOINTS).shape[0] if n is None else n
+ parts = []
+ for k, dim in (("q", 6), ("qd", 6), ("cube_pos", 3), ("cube_quat", 4), ("cube_v", 3), ("cube_w", 3)):
+ x = _get(start, k)
+ parts.append(np.zeros((n, dim)) if x is None else np.asarray(_tonp(x), np.float64).reshape(n, dim))
+ return np.concatenate(parts, 1)
+
+
+def _tonp(x):
+ if torch is not None and torch.is_tensor(x):
+ return x.detach().cpu().double().numpy()
+ return x
+
+
+def step_rates(prev: "torch.Tensor", cur: "torch.Tensor"):
+ """20 ms step-average rates between two raw records [B, 25] (float64 tensors) by the data pipeline's own code
+ (data.step_average_rates): -> (qd [B, 6], cube_v [B, 3], cube_w [B, 3])."""
+ from nedm.contact_nrd.data import step_average_rates
+ st = torch.zeros(len(cur), 2, 2, 13, dtype=torch.float64)
+ st[:, 0, 0, :12], st[:, 1, 0, :12] = prev[:, :12], cur[:, :12]
+ st[:, 0, 1], st[:, 1, 1] = prev[:, 12:], cur[:, 12:]
+ out = step_average_rates({"states": st, "stride": 1, "dt": CONTROL_DT, "system": _RATE_SYSTEM},
+ {"articulated", "rigid"})["states"][:, 1]
+ return out[:, 0, 6:12], out[:, 1, 7:10], out[:, 1, 10:13]
+
+
+class MujocoWorlds:
+ """``num_envs`` worlds of the collector scene in CPU MuJoCo, split over ``workers`` processes (0 = here).
+
+ ``reset(idx, start, warmup=False)`` places worlds at a WorldState-like start (``warmup=True``: the collector's
+ 0.3 s warm-up first, arm held at ``start.q``, cube resting at its pose = ``Scene.reset``, bit-identical to the
+ collector; ``spawn=True``: cube parked during the warm-up, then placed with ``cube_v``, ``cube_w``, as the
+ collector's probes); ``step(targets [B, 6])`` runs one 20 ms command; ``set_cube(idx, pos, quat, v, w)`` moves
+ the cube (disturbance). All return the WorldState of all worlds (float64, on ``device``; module docstring for the
+ definitions). Attributes: ``end_reason`` / ``end_step`` [B] (first end since the reset, ``end_names()``),
+ ``step_code`` [B] (end code raised by the last command, 0 none), ``physical_contact`` / ``switch_contact``
+ [B, 3] (the two contact views, ``contact_rule`` picks the one in the WorldState), ``contact_force`` [B, 7]
+ (largest summed normal force per collector kind in the last command, N), ``applied`` [B, 6] float32 targets of
+ the last command, ``steps`` [B] commands since the reset, ``records`` [B, 2, 25] the two 10 ms raw records the
+ last command ended (mid, end; float32-rounded when float32_records; ``raw_state`` layout) and
+ ``record_contact`` [B, 2, 3] the collector's interval labels of its two 10 ms intervals (the data's
+ ``contacts``): with ``applied`` they give the collection arrays of a rollout (NRD data rounds).
+
+ ``python``: interpreter of the workers (default $NEDM_MJ_PYTHON or this one; needs numpy and mujoco, scipy only to
+ build the overlap cache; with scipy the overlap check is cheaper: luffy 1 worker 406 vs 211 steps/s with conda
+ ``nrdsim`` vs ``nedm`` workers, same bit-exact replay of 177 validation episodes). ``overlap``: the visual-overlap end
+ check. ``cpus``: CPU affinity of the workers (e.g. to keep off a faulty core; newton 2026-10-11: logical CPUs
+ 10-11 crash, use [0..9, 12..31]). ``labels``: "exact" (contact forces after every 0.5 ms physics step, the data
+ rule) or "record" (once per 10 ms record: the same physics and states, but contacts and force-based ends shorter
+ than a record can be missed). ``contact_rule``: "gate" (default; this step or the one before = the NRD switch,
+ ``data.model_labels``, the meaning of ``GraspNrdSim``'s default) or "physical" (this step only,
+ ``data.physical_labels``)."""
+
+ def __init__(self, num_envs: int, workers: int = 0, device="cpu", overlap: bool = True,
+ float32_records: bool = True, python: str | None = None, overlap_cache_dir=None, cpus=None,
+ labels: str = "exact", contact_rule: str = "gate"):
+ if torch is None:
+ raise ImportError("MujocoWorlds needs torch in the main process")
+ if contact_rule not in ("gate", "physical"):
+ raise ValueError(f"contact_rule {contact_rule!r}: 'gate' or 'physical'")
+ self.contact_rule = contact_rule
+ self.B, self.device, self.float32_records = int(num_envs), torch.device(device), bool(float32_records)
+ nw = max(0, min(int(workers), self.B))
+ cuts = np.linspace(0, self.B, (nw or 1) + 1).round().astype(int)
+ self.blocks = [(int(a), int(b)) for a, b in zip(cuts[:-1], cuts[1:])]
+ python = python or os.environ.get("NEDM_MJ_PYTHON") or sys.executable
+ self.procs = [_Proc(python) for _ in self.blocks] if nw else [_Local()]
+ kw = dict(overlap=overlap, cache_dir=None if overlap_cache_dir is None else str(overlap_cache_dir), labels=labels,
+ cpus=None if cpus is None or not nw else sorted(int(c) for c in cpus))
+ try: # the first worker builds the overlap cache if needed, then the others load it
+ self.procs[0].send("init", n=self.blocks[0][1] - self.blocks[0][0], **kw)
+ self.info = [self.procs[0].recv()]
+ for p, (a, b) in zip(self.procs[1:], self.blocks[1:]):
+ p.send("init", n=b - a, **kw)
+ self.info += [p.recv() for p in self.procs[1:]]
+ except BaseException:
+ self.close()
+ raise
+ self.tlo, self.thi = np.array(self.info[0]["tlo"]), np.array(self.info[0]["thi"]) # applied-target range
+ B, f64 = self.B, torch.float64
+ self._raw = torch.zeros(B, RAW, dtype=f64)
+ self._ws = WorldState(q=torch.zeros(B, 6, dtype=f64), qd=torch.zeros(B, 6, dtype=f64),
+ cube_pos=torch.zeros(B, 3, dtype=f64), cube_quat=torch.zeros(B, 4, dtype=f64),
+ cube_v=torch.zeros(B, 3, dtype=f64), cube_w=torch.zeros(B, 3, dtype=f64),
+ contact=torch.zeros(B, 3, dtype=torch.bool), arm_table=torch.zeros(B, dtype=torch.bool),
+ invalid=torch.zeros(B, dtype=torch.bool))
+ self.ready = torch.zeros(B, dtype=torch.bool)
+ self.end_reason = torch.zeros(B, dtype=torch.int8)
+ self.end_step = torch.full((B,), -1, dtype=torch.long)
+ self.step_code = torch.zeros(B, dtype=torch.int8)
+ self.steps = torch.zeros(B, dtype=torch.long)
+ self.physical_contact = torch.zeros(B, 3, dtype=torch.bool)
+ self.switch_contact = torch.zeros(B, 3, dtype=torch.bool)
+ self.contact_force = torch.zeros(B, 7, dtype=f64)
+ self.applied = torch.zeros(B, 6, dtype=torch.float32)
+ self.records = torch.zeros(B, 2, RAW, dtype=f64)
+ self.record_contact = torch.zeros(B, 2, 3, dtype=torch.bool)
+
+ # -- plumbing --
+ def _idx(self, idx) -> np.ndarray:
+ if idx is None:
+ return np.arange(self.B)
+ x = np.asarray(_tonp(idx) if not (torch is not None and torch.is_tensor(idx)) else idx.cpu().numpy())
+ return np.flatnonzero(x) if x.dtype == bool else x.astype(np.int64).reshape(-1)
+
+ def _scatter(self, cmd, idx, arrays, **const):
+ """Send cmd to the blocks owning idx (rows of ``arrays`` follow idx; ``const`` go as they are) -> (idx in
+ block order, merged result)."""
+ if len(np.unique(idx)) != len(idx) or (len(idx) and (idx.min() < 0 or idx.max() >= self.B)):
+ raise ValueError("world indices must be unique and inside 0 .. B-1")
+ order, calls = [], []
+ for p, (a, b) in zip(self.procs, self.blocks):
+ sel = np.flatnonzero((idx >= a) & (idx < b))
+ if len(sel):
+ p.send(cmd, rows=(idx[sel] - a).tolist(), **{k: (None if v is None else v[sel]) for k, v in arrays.items()},
+ **const)
+ calls.append(p)
+ order.append(sel)
+ res = [p.recv() for p in calls]
+ sel = np.concatenate(order)
+ return idx[sel], {k: np.concatenate([r[k] for r in res]) for k in res[0]}
+
+ def _round(self, raw: np.ndarray) -> torch.Tensor:
+ x = raw.astype(np.float32) if self.float32_records else raw
+ return torch.from_numpy(x.astype(np.float64))
+
+ def _place(self, idx, res, first: bool):
+ """State rows idx after a reset (first) or a cube move: the raw record of the new state, rates instantaneous.
+ A cube move keeps the arm fields (the arm did not move; its rate stays the last step average) and restarts
+ the step-average buffer of the cube at the new pose (review_spec_feasibility sec. 5)."""
+ t = torch.from_numpy(idx)
+ raw = self._round(res["raw"])
+ ws = self._ws
+ if first:
+ self._raw[t] = raw
+ ws.q[t], ws.qd[t] = raw[:, 0:6], raw[:, 6:12]
+ else:
+ self._raw[t, 12:] = raw[:, 12:]
+ ws.cube_pos[t], ws.cube_quat[t] = raw[:, 12:15], raw[:, 15:19]
+ ws.cube_v[t], ws.cube_w[t] = raw[:, 19:22], raw[:, 22:25]
+ lab = torch.from_numpy(res["contact"])
+ ws.contact[t] = lab
+ ws.arm_table[t], ws.invalid[t] = torch.from_numpy(res["arm_table"]), torch.from_numpy(res["invalid"])
+ self.contact_force[t] = torch.from_numpy(res["force"])
+ code = torch.from_numpy(res["code"])
+ self.step_code[t] = code
+ if first:
+ self.end_reason[t], self.end_step[t] = code, torch.where(code > 0, 0, -1)
+ self.steps[t], self.physical_contact[t], self.switch_contact[t] = 0, False, False
+ self.records[t] = raw[:, None]
+ self.record_contact[t] = False
+ self.ready[t] = True
+ else:
+ new = (self.end_reason[t] == 0) & (code > 0)
+ self.end_reason[t] = torch.where(new, code, self.end_reason[t])
+ self.end_step[t] = torch.where(new, self.steps[t], self.end_step[t])
+
+ # -- API --
+ def reset(self, idx=None, start=None, warmup: bool = False, spawn: bool = False, targets=None) -> WorldState:
+ """Reset worlds idx (None = all; indices or bool mask [B]) to ``start`` (one row per selected world; a
+ ``sample_starts`` dict works as it is). warmup=False: the exact state (rates as instantaneous MuJoCo
+ velocities; held targets ``targets`` [n, 6], default start.q; NOT the collector's solver warm start, so a
+ stored episode diverges slowly, bench replay B). warmup=True: Scene.reset (start rates ignored unless spawn).
+ The returned contact of a reset world = the forces of one mj_forward at its start (both views), flags and
+ end codes of that state. Returns the state of all worlds."""
+ if start is None:
+ raise ValueError("reset needs a start state")
+ idx = self._idx(idx)
+ rows = pack_start(start, len(idx))
+ ctrl = None if targets is None else np.asarray(_tonp(targets), np.float64).reshape(len(idx), JOINTS)
+ if spawn and not warmup:
+ raise ValueError("spawn needs warmup=True (the collector's probe start)")
+ order, res = self._scatter("reset", idx, dict(start=rows, ctrl=ctrl), warmup=bool(warmup), spawn=bool(spawn))
+ self._place(order, res, first=True)
+ return self.state()
+
+ def set_cube(self, idx, pos, quat, v=None, w=None) -> WorldState:
+ """Move the cube of worlds idx to pos [n, 3] (m), quat [n, 4] (w x y z, true orientation) with world velocity
+ v and world spin w (default 0): a disturbance (qpos / qvel of the free joint, mj_forward; arm untouched).
+ The returned rows hold the new pose with these (instantaneous) rates and the arm fields of the last step;
+ the next step's step-average cube rates start from the new pose (the jump itself is no rate). Flags and
+ contacts are those of the new state (one mj_forward); a cube placed into the gripper meshes is ``invalid``
+ at once. In-distribution moves (review_spec_feasibility sec. 5; the NRD side must use the same values):
+ flat, at rest, centre z = ``REST_Z``, on the start annulus, >= 2 cm from every gripper collision point,
+ before the GRASP close starts."""
+ idx = self._idx(idx)
+ n = len(idx)
+ z = np.zeros((n, 3))
+ pose = np.concatenate([np.asarray(_tonp(x), np.float64).reshape(n, k) if x is not None else z
+ for x, k in ((pos, 3), (quat, 4), (v, 3), (w, 3))], 1)
+ order, res = self._scatter("set_cube", idx, dict(pose=pose))
+ self._place(order, res, first=False)
+ return self.state()
+
+ def step(self, targets) -> WorldState:
+ """One 20 ms command: targets [B, 6] absolute joint targets (rad, jaw last), clipped to the collector's
+ applied range (joint limits minus 50 mrad) and cast to float32. Returns the new state of all worlds."""
+ if not bool(self.ready.all()):
+ raise RuntimeError("reset every world before stepping")
+ u = np.asarray(_tonp(targets), np.float64).reshape(self.B, JOINTS)
+ for p, (a, b) in zip(self.procs, self.blocks):
+ p.send("step", targets=u[a:b])
+ res = [p.recv() for p in self.procs]
+ res = {k: np.concatenate([r[k] for r in res]) for k in res[0]}
+ cur = self._round(res["raw"])
+ qd, v, w = step_rates(self._raw, cur)
+ self._raw = cur
+ ws = self._ws
+ ws.q, ws.qd, ws.cube_pos, ws.cube_quat = cur[:, 0:6].clone(), qd, cur[:, 12:15].clone(), cur[:, 15:19].clone()
+ ws.cube_v, ws.cube_w = v, w
+ phys = torch.from_numpy(res["contact"])
+ self.switch_contact = phys | self.physical_contact
+ self.physical_contact = phys
+ ws.contact = (self.switch_contact if self.contact_rule == "gate" else phys).clone()
+ ws.arm_table, ws.invalid = torch.from_numpy(res["arm_table"]), torch.from_numpy(res["invalid"])
+ self.contact_force = torch.from_numpy(res["force"])
+ self.applied = torch.from_numpy(np.clip(u, self.tlo, self.thi).astype(np.float32))
+ self.records = torch.cat((self._round(res["mid"]), cur[:, None]), 1)
+ self.record_contact = torch.from_numpy(res["rec_contact"])
+ self.steps += 1
+ code = torch.from_numpy(res["code"])
+ self.step_code = code
+ new = (self.end_reason == 0) & (code > 0)
+ self.end_reason = torch.where(new, code, self.end_reason)
+ self.end_step = torch.where(new, self.steps, self.end_step)
+ return self.state()
+
+ def set_table(self, plane=None):
+ """Table top on the plane z = c0 + c1 x + c2 y in every worker (``_Block.set_table``; None: z = 0). Call
+ before the resets; starts stay world poses (``table.map_cube`` moves a task start onto the plane)."""
+ for p in self.procs:
+ p.send("set_table", plane=None if plane is None else [float(c) for c in plane])
+ self.table = [p.recv() for p in self.procs][0]
+ self.ready[:] = False
+ return self.table
+
+ def state(self) -> WorldState:
+ """Current WorldState of all worlds (copies, on ``device``)."""
+ return WorldState(**{f.name: getattr(self._ws, f.name).to(self.device, copy=True) for f in fields(WorldState)})
+
+ def raw_state(self) -> torch.Tensor:
+ """[B, 25] the collector's raw record of the current state (instantaneous rates, cube spin in the world
+ frame; float32-rounded when float32_records)."""
+ return self._raw.clone()
+
+ def close(self):
+ for p in getattr(self, "procs", []):
+ p.close()
+ self.procs = []
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+
+ def __del__(self):
+ try:
+ self.close()
+ except Exception: # noqa: BLE001
+ pass
+
+
+# ---- start sampling -----------------------------------------------------------------------------------------------
+_SAMPLER = {}
+
+
+def reserved_seeds() -> frozenset:
+ """Seeds a start sampler must not use: the master seeds of every collector campaign (pilot, production, the
+ SEALED TEST 20261034, extra, noisy_v1) and of the convergence check, and every episode seed of these campaigns at
+ their configured counts (``so101_grasp.episode_seed``; a task episode draws its start first, so its seed would
+ repeat its start). 83,274 seeds for the current config, 3.7 s to compute: cached as .npy next to the overlap cache
+ (key = sha256 of the config)."""
+ if "reserved" not in _SAMPLER:
+ from nedm.contact_nrd.collect import so101_grasp as g
+ cfg = g.load_config()
+ key = hashlib.sha256(json.dumps(cfg, sort_keys=True).encode()).hexdigest()[:24]
+ path = DEFAULT_CACHE / f"reserved_seeds_{key}.npy"
+ if path.exists():
+ out = set(np.load(path).tolist())
+ else:
+ names = [f["name"] for f in cfg["families"]]
+ out = {int(c["master_seed"]) for c in cfg["campaigns"].values()} | {int(cfg["convergence"]["master_seed"])}
+ for name, c in cfg["campaigns"].items():
+ out |= {g.episode_seed(c["master_seed"], f, i) for f, n in g.campaign_counts(cfg, name)
+ for i in range(n)}
+ conv = cfg["convergence"]
+ out |= {g.episode_seed(conv["master_seed"], names.index(k), i) for k, n in conv["episodes"].items()
+ for i in range(n)}
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(f".{os.getpid()}.tmp.npy")
+ np.save(tmp, np.array(sorted(out), np.int64))
+ tmp.replace(path)
+ except OSError:
+ pass
+ _SAMPLER["reserved"] = frozenset(int(x) for x in out)
+ return _SAMPLER["reserved"]
+
+
+def sample_starts(seeds, spread_deg: float = 40.0, overlap: bool = True, float32_records: bool = True,
+ max_tries: int = 200) -> dict:
+ """One fresh task start per seed with the collector's start sampler and warm-up (spec v2 B4 test starts).
+
+ Seed k: ``rng = numpy.random.default_rng(seed)``; ``so101_grasp.task_start(scene, rng, spread_deg)`` (cube flat on
+ 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),
+ 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
+ ``spread_deg`` of the cube direction (nominal family 40 deg), jaw U(0, 1.2) rad, lowest arm point > 2 cm, no
+ self-contact); then ``Scene.reset`` (0.3 s warm-up, arm held at q0, cube resting). A PlanError draws again from
+ the same rng (as ``make_episode``); so does a settled start that already ends (any collector end code) or has a
+ jaw on the cube (stricter than the collector, which would keep a touching start). Seeds in ``reserved_seeds()``
+ raise (never the sealed test or a data episode's start).
+
+ -> dict (numpy unless noted): ``q`` [n, 6] start pose = held targets, ``cube_pos`` [n, 3], ``cube_quat`` [n, 4]
+ (w x y z, before the warm-up): pass the dict to ``MujocoWorlds.reset(idx, starts, warmup=True)`` (bit-identical
+ to the collector and to ``state``); ``state``: the settled WorldState (torch float64, float32-rounded like a data
+ record; rates instantaneous; contact = one mj_forward) for the NRD world's reset; ``raw`` [n, 25]; ``seed`` [n];
+ ``tries`` [n] draws per start."""
+ seeds = [int(x) for x in np.asarray(_tonp(seeds)).reshape(-1)]
+ bad = sorted(set(seeds) & reserved_seeds())
+ if bad:
+ raise ValueError(f"seeds {bad[:5]} are collector campaign seeds (sealed test / data starts)")
+ from nedm.contact_nrd.collect import so101_grasp as g
+ key = ("block", bool(overlap))
+ if key not in _SAMPLER:
+ _SAMPLER[key] = _Block(1, overlap=overlap)
+ blk = _SAMPLER[key]
+ s = blk.s
+ n = len(seeds)
+ q, pos, quat, raw = np.zeros((n, 6)), np.zeros((n, 3)), np.zeros((n, 4)), np.zeros((n, RAW))
+ lab, tries = np.zeros((n, 3), bool), np.zeros(n, np.int64)
+ for k, seed in enumerate(seeds):
+ rng = np.random.default_rng(seed)
+ while True:
+ tries[k] += 1
+ if tries[k] > max_tries:
+ raise RuntimeError(f"seed {seed}: no start after {max_tries} draws")
+ try:
+ cube, cyaw, q0, _ = g.task_start(s, rng, spread_deg)
+ except g.PlanError:
+ continue
+ c = g.resting_cube(cube, cyaw)
+ row = np.concatenate((q0, np.zeros(6), c["pos"], c["quat"], np.zeros(6)))[None]
+ res = blk.reset([0], row, warmup=True)
+ if res["code"][0] == 0 and not res["arm_table"][0] and not res["contact"][0, :2].any():
+ break
+ q[k], pos[k], quat[k], raw[k], lab[k] = q0, c["pos"], c["quat"], res["raw"][0], res["contact"][0]
+ r = raw.astype(np.float32).astype(np.float64) if float32_records else raw
+ t = torch.from_numpy(r)
+ f = torch.zeros(n, dtype=torch.bool)
+ 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],
+ cube_w=t[:, 22:25], contact=torch.from_numpy(lab), arm_table=f, invalid=f.clone())
+ return dict(q=q, cube_pos=pos, cube_quat=quat, state=state, raw=r, seed=np.array(seeds, np.int64), tries=tries)
+
+
+# ---- NRD layout ---------------------------------------------------------------------------------------------------
+def _body_cols(model):
+ """Moving bodies of the model -> (arm slot, cube slot, arm q cols, arm qd cols, cube cols) by channel name."""
+ mov = [b for b in model.system["bodies"] if b["moving"]]
+ ia = next(n for n, b in enumerate(mov) if b.get("kind") == "articulated")
+ ic = next(n for n, b in enumerate(mov) if b.get("kind") == "rigid")
+ ach, cch = mov[ia]["channels"], mov[ic]["channels"]
+ return (ia, ic, [ach.index(f"q_{j}") for j in JOINT_NAMES], [ach.index(f"qd_{j}") for j in JOINT_NAMES],
+ [cch.index(c) for c in CUBE_NAMES])
+
+
+def nrd_state(ws: WorldState, model) -> torch.Tensor:
+ """WorldState -> NRD state [B, D, S] float64 (on ws's device): the 12 + 13 base channels placed by channel name
+ from model.system, then model.finish (unit quaternion, FK and relative channels if the model has them). The
+ cube orientation is the given (true) one: the NRD sim canonicalises it, not this function."""
+ ia, ic, qc, qdc, cc = _body_cols(model)
+ B = ws.q.shape[0]
+ x = torch.zeros(B, model.n_bodies, model.smax, dtype=torch.float64, device=ws.q.device)
+ x[:, ia, qc], x[:, ia, qdc] = ws.q.double(), ws.qd.double()
+ x[:, ic, cc] = torch.cat((ws.cube_pos, ws.cube_quat, ws.cube_v, ws.cube_w), -1).double()
+ return model.finish(x)
+
+
+def world_from_nrd(state: torch.Tensor, model) -> WorldState:
+ """NRD state [B, D, S] -> WorldState (contact, arm_table, invalid False): a start for MujocoWorlds.reset."""
+ ia, ic, qc, qdc, cc = _body_cols(model)
+ c = state[:, ic, cc].double()
+ B = state.shape[0]
+ f = torch.zeros(B, dtype=torch.bool, device=state.device)
+ return WorldState(q=state[:, ia, qc].double(), qd=state[:, ia, qdc].double(), cube_pos=c[:, 0:3],
+ cube_quat=c[:, 3:7], cube_v=c[:, 7:10], cube_w=c[:, 10:13],
+ contact=torch.zeros(B, 3, dtype=torch.bool, device=state.device), arm_table=f, invalid=f.clone())
+
+
+def main(argv=None):
+ import argparse
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = p.add_subparsers(dest="cmd", required=True)
+ c = sub.add_parser("overlap-cache", help="build the visual-overlap grid cache (needs scipy)")
+ c.add_argument("--dir", default=None)
+ a = p.parse_args(argv)
+ if a.cmd == "overlap-cache":
+ from nedm.contact_nrd.collect import so101_grasp as g
+ s = g.Scene(g.load_config())
+ print(install_overlap(s, a.dir))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/so101_pick_place/code/src/nedm/so101_policy/npz_rows.py b/so101_pick_place/code/src/nedm/so101_policy/npz_rows.py
new file mode 100644
index 0000000000000000000000000000000000000000..e113032528911b8eb3e98fa8d4dc00664e50e4ae
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/npz_rows.py
@@ -0,0 +1,43 @@
+"""Memory-mapped reader of an uncompressed .npz (np.savez): the start banks read the first states of chosen episodes
+of the NRD data (unified_data.npz, up to 4.2 GB) without loading the whole file.
+
+Copy of ``npz_members`` of the study branch's ``nedm/contact_nrd/rollouts.py`` (commit 359910370 on the branch
+so101-pick-place-study), unchanged; that module is not part of this release (``task.load_start_bank`` uses only this
+function). Main's ``nedm.g1_footstep_rl.npz_rows.npz_members`` is the same function.
+"""
+from __future__ import annotations
+
+import struct
+import zipfile
+
+import numpy as np
+
+
+def npz_members(path):
+ """{name: read-only np.memmap} of the arrays of an uncompressed .npz (np.savez): rows are read on access, not
+ the whole file."""
+ out = {}
+ with zipfile.ZipFile(path) as z, open(path, "rb") as fh:
+ for info in z.infolist():
+ if not info.filename.endswith(".npy"):
+ continue
+ if info.compress_type != zipfile.ZIP_STORED:
+ raise ValueError(f"{path}: {info.filename} is compressed; this reader needs np.savez (no compression)")
+ fh.seek(info.header_offset)
+ head = fh.read(30)
+ if head[:4] != b"PK\x03\x04":
+ raise ValueError(f"{path}: bad local header of {info.filename}")
+ name_len, extra_len = struct.unpack("= 0), contact network on ALL (world, pair) entries, each change multiplied by its switch (``torch.where``,
+ so a non-finite output of a switched-off pair cannot leak) and written to BOTH bodies of the pair (the pair's first
+ body and its moving partner). Pose integration and ``finish`` (quaternion re-normalised) use the model's own
+ channel tables (``model.chan``, ``model.quat``) as host-side slices, so the step has no host sync and can be
+ captured in a CUDA graph (``ContactNRD.assemble``/``finish`` call ``torch.nonzero(...).tolist()``).
+ ``ContactNRD.details`` runs the contact network only on the switched-on entries (``torch.nonzero``) and gives the
+ same next state up to float32 rounding of the contact network (other GEMM batch shapes; measured on 21,506
+ recorded validation windows: max 1.8e-7, switches equal; ``scripts/so101_policy/bench_nrd_sim.py``). At
+ construction the sim checks that its assemble/finish equal ``model.assemble``/``model.finish`` bit for bit on a
+ probe batch; if a future model differs, the sim warns
+ and calls the model's own functions (eager only, no CUDA graph).
+2. History shift (``ContactNRD.advance``).
+3. Cube canonicalisation (``canonical=True``, default): the newest cube quaternion picks one of the 24 cube rotations
+ r (``cube_symmetry.canonical_index``); the quaternions of all K history slots of the world are relabelled
+ q -> q r and their sign set so that the newest has w >= 0 (one relabel per world: the step differences stay
+ consistent), then each relabelled slot is finished again. Positions, world velocity and world spin do not change.
+ The refinish is ``model.finish`` restricted to the cube (quaternion re-normalised): the arm channels do not
+ change. At
+ construction the sim checks that this equals ``model.finish`` bit for bit on relabelled probe states (else it uses
+ ``model.finish``). The cumulative relabelling C of each world (an index into the group,
+ ``q_internal = q_true G[C]`` up to sign) is kept with the exact group table, and ``WorldState.cube_quat`` is the
+ TRUE orientation ``q_internal conj(G[C])``, its sign kept continuous with the previous output.
+ ``canonical=False`` leaves the quaternions alone (C = 0); then the sim is ``ContactNRD.rollout`` with the dense
+ contact step.
+
+Members: ``members="split"`` loads all checkpoints and gives member j the contiguous worlds
+[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
+the dict keys of ``ckpts``, or the file stems; a string also matches a name that ends with it ("s61").
+
+WorldState fields (``nedm.so101_policy.world``):
+
+| Field | NRD rule |
+|---|---|
+| q, qd | arm angle and rate channels of the newest state (rates = 20 ms step averages, the data definition) |
+| cube_pos, cube_v, cube_w | cube channels of the newest state (world frame) |
+| cube_quat | the TRUE orientation (see 3.), w x y z |
+| 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 |
+| 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) |
+| 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 |
+
+The sim does not end or reset worlds: the caller resets invalid worlds. A non-finite world stays non-finite but does
+not touch the other worlds (every operation is per world).
+
+Resets (``reset``, ``reset_state``, ``reset_history``) and ``set_cube`` write in place, so a captured CUDA graph stays
+valid; each returns the WorldState of ALL worlds (as the MuJoCo worlds do). A reset from a single state uses
+``ContactNRD.start``: one valid history entry, the others masked (``ok`` False), as the evaluation's whole-episode
+rollouts.
+
+``set_cube`` (disturbance, review_spec_feasibility sec. 5): the 13 base cube channels (position, quaternion,
+velocity, spin) are written into ALL K history slots, the arm channels and the masks ``ok`` are kept, and
+``model.finish`` runs on each slot. With the default
+v = w = 0 all K cube entries are equal: the history of a cube that has rested there, the only disturbance that is in
+the data (approach phase: resting cube, arm moving above it). A nonzero v, w gives the constant-rate history
+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
+slot j; a sliding cube is NOT in the data. The caller keeps the new pose in distribution (``cube_rest_envelope``:
+flat, at rest, data resting height, on the start annulus) and >= 2 cm from every gripper collision point, before the
+GRASP close starts (the 2 cm check needs the arm's collision points: ``kin.SO101Kin``; not done here). The switches
+and the contact flags stay those of the last step until the next step.
+
+No gradient path: all methods run under ``torch.no_grad``. For gradients call the model methods directly.
+"""
+from __future__ import annotations
+
+import math
+import warnings
+from pathlib import Path
+from typing import Callable
+
+import torch
+
+from nedm.contact_nrd.model import ContactNRD, load_model
+from nedm.so101_policy import cube_symmetry as cs
+from nedm.so101_policy.kin import THI, TLO
+from nedm.so101_policy.paths import DATA
+from nedm.so101_policy.world import CONTACT_PAIRS, JOINTS, WorldState
+
+STUDY_CKPTS = {"c1_s62": DATA / "nrd" / "c1_s62" / "best.pt"} # the released policy NRD (so101_pick_place/README.md)
+LIMITS = dict(cube_z_min=0.010, cube_z_max=0.45, cube_speed_max=4.0, cube_spin_max=100.0)
+# Start states of the task families (val_only, 1,803 first records, measured): cube centre z = 0.014993 m in all, flat,
+# at rest, on the annulus r 0.150-0.270 m around the pan axis, angle -75.0..74.9 deg (collector sample_cube).
+CUBE_REST_Z = 0.014993
+ANNULUS = dict(center_xy=(0.0388, 0.0), r_min=0.15, r_max=0.27, angle_max_deg=75.0)
+ARM_TABLE_GUARD_M = 0.0005 # critic map 3.7: lowest gripper / moving-jaw collision point below 0.5 mm
+
+
+def _cols(x) -> list[int]:
+ return [int(c) for c in (x.tolist() if torch.is_tensor(x) else x) if int(c) >= 0]
+
+
+def _index(cols: list[int], device):
+ """A contiguous column list -> slice (no index tensor, no host-to-device copy); else a device index tensor."""
+ if not cols:
+ return None
+ if cols == list(range(cols[0], cols[0] + len(cols))):
+ return slice(cols[0], cols[0] + len(cols))
+ return torch.tensor(cols, dtype=torch.long, device=device)
+
+
+def _get(start, name):
+ return start.get(name) if isinstance(start, dict) else getattr(start, name, None)
+
+
+def lowest_point_guard(kin, threshold_m: float = ARM_TABLE_GUARD_M) -> Callable[[torch.Tensor], torch.Tensor]:
+ """arm_table_fn of the critic's rule (map 3.7): ``kin.lowest_point(q) < threshold_m``, with kin a
+ ``kin.SO101Kin`` (lowest world z of the gripper and moving-jaw collision geoms, m). q [B, 6] -> bool [B]."""
+ return lambda q: kin.lowest_point(q) < threshold_m
+
+
+def cube_rest_envelope(pos, quat, v=None, w=None, z_tol_m: float = 5e-4, tilt_max_deg: float = 1.0,
+ rate_max: float = 1e-6) -> torch.Tensor:
+ """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),
+ v, w [n, 3] (world, default 0) -> bool [n]: centre height within z_tol_m of CUBE_REST_Z, tilt (body z against
+ world z) <= tilt_max_deg, |v| and |w| <= rate_max, centre on ANNULUS. The 2 cm gripper clearance is NOT checked."""
+ pos = torch.as_tensor(pos, dtype=torch.float64)
+ quat = torch.as_tensor(quat, dtype=torch.float64, device=pos.device)
+ quat = quat / quat.norm(dim=-1, keepdim=True)
+ ok = (pos[:, 2] - CUBE_REST_Z).abs() <= z_tol_m
+ up = 1 - 2 * (quat[:, 1] ** 2 + quat[:, 2] ** 2) # world z of the body z axis
+ ok &= up >= math.cos(math.radians(tilt_max_deg))
+ for r in (v, w):
+ if r is not None:
+ ok &= torch.as_tensor(r, dtype=torch.float64, device=pos.device).reshape(-1, 3).norm(dim=-1) <= rate_max
+ dx, dy = pos[:, 0] - ANNULUS["center_xy"][0], pos[:, 1] - ANNULUS["center_xy"][1]
+ r = torch.hypot(dx, dy)
+ ok &= (r >= ANNULUS["r_min"]) & (r <= ANNULUS["r_max"])
+ ok &= torch.rad2deg(torch.atan2(dy, dx)).abs() <= ANNULUS["angle_max_deg"]
+ return ok
+
+
+class GraspNrdSim:
+ """ckpts: path, list of paths or {name: path} (default STUDY_CKPTS = the released policy NRD c1_s62; a loaded
+ ContactNRD may stand in for a path, it is moved to the device and its parameters frozen); num_envs
+ B; members "split" | name | [names] | int; canonical: per-step cube canonicalisation; canon_margin: hysteresis of
+ the relabelling (0 = the critic's rule); contact_rule "gate" | "physical"; arm_table_fn(q) -> bool [B] (e.g.
+ lowest_point_guard);
+ cuda_graph: capture the step in one CUDA graph at the first step (CUDA only); limits: overrides of LIMITS."""
+
+ def __init__(self, ckpts=None, num_envs: int = 1, device="cuda", members="split", canonical: bool = True,
+ canon_margin: float = 0.0, contact_rule: str = "gate",
+ arm_table_fn: Callable[[torch.Tensor], torch.Tensor] | None = None, cuda_graph: bool = False,
+ limits: dict | None = None):
+ ckpts = STUDY_CKPTS if ckpts is None else ckpts
+ if isinstance(ckpts, (str, Path, ContactNRD)):
+ ckpts = [ckpts]
+ named = dict(ckpts) if isinstance(ckpts, dict) else {
+ (f"m{j}" if isinstance(p, ContactNRD) else Path(p).stem): p for j, p in enumerate(ckpts)}
+ names = list(named)
+ if members in ("split", "all", None):
+ pick = names
+ else:
+ wanted = [members] if isinstance(members, (str, int)) else list(members)
+ pick = []
+ for w in wanted:
+ 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))]
+ if len(hit) != 1:
+ raise ValueError(f"member {w!r} matches {hit} of {names}")
+ pick += hit
+ self.device = torch.device(device)
+ self.member_names = pick
+ self.paths = [f"" if isinstance(named[n], ContactNRD) else str(named[n]) for n in pick]
+ self.models: list[ContactNRD] = []
+ for n, p in zip(pick, self.paths):
+ m = named[n].to(self.device).eval() if isinstance(named[n], ContactNRD) else load_model(p, self.device)[0]
+ for q in m.parameters():
+ q.requires_grad_(False)
+ if self.models and (m.config != self.models[0].config or m.system != self.models[0].system
+ or not torch.equal(m.smask, self.models[0].smask)):
+ raise ValueError(f"{p}: members must share model_config, system and channel masks")
+ self.models.append(m)
+ m0 = self.models[0]
+ self.B, self.M = int(num_envs), len(self.models)
+ if self.B < self.M:
+ raise ValueError(f"{self.B} worlds for {self.M} members")
+ 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
+ self.canonical, self.canon_margin, self.contact_rule = bool(canonical), float(canon_margin), contact_rule
+ if contact_rule not in ("gate", "physical"):
+ raise ValueError(f"contact_rule {contact_rule!r}")
+ self.arm_table_fn = arm_table_fn
+ self.limits = {**LIMITS, **(limits or {})}
+ self._tlo = torch.tensor(TLO, dtype=torch.float64, device=self.device)
+ self._thi = torch.tensor(THI, dtype=torch.float64, device=self.device)
+ self.use_graph = bool(cuda_graph) and self.device.type == "cuda"
+ self._graph = None
+ self._layout(m0)
+ dev, f64 = self.device, torch.float64
+ # fixed blocks of worlds per member, dense (world, pair) index lists per block
+ self.blocks = []
+ for j, m in enumerate(self.models):
+ s, e = j * self.B // self.M, (j + 1) * self.B // self.M
+ n = e - s
+ self.blocks.append((m, slice(s, e), torch.arange(n, device=dev).repeat_interleave(self.P),
+ torch.arange(self.P, device=dev).repeat(n)))
+ self.member_of_world = torch.cat([torch.full((b[1].stop - b[1].start,), j, dtype=torch.long, device=dev)
+ for j, b in enumerate(self.blocks)])
+ self._g, self._gconj = cs.group(f64, dev), cs.qconj(cs.group(f64, dev))
+ self._mul, self._scores = cs.mul_table(dev), cs.score_matrix(dtype=f64, device=dev)
+ # state buffers (written in place only: a captured graph keeps their addresses)
+ B, K, D, S, P = self.B, self.K, self.D, self.S, self.P
+ self.hist = torch.zeros(B, K, D, S, dtype=f64, device=dev) # newest last; cube quaternion canonical
+ self.ok = torch.zeros(B, K, dtype=torch.bool, device=dev)
+ self.act = torch.zeros(B, D, self.A, dtype=f64, device=dev) # row ia = the arm's joint targets
+ self.gates = torch.zeros(B, P, dtype=f64, device=dev) # model pair order
+ self.prev_gates = torch.zeros_like(self.gates)
+ self.logits = torch.zeros_like(self.gates)
+ self.canon = torch.zeros(B, dtype=torch.long, device=dev) # cumulative relabelling C
+ self.true_q = torch.zeros(B, 4, dtype=f64, device=dev)
+ self.true_q[:, 0] = 1.0
+ self.relabelled = torch.zeros(B, dtype=torch.bool, device=dev) # relabelled in the last step
+ self.contact = torch.zeros(B, len(CONTACT_PAIRS), dtype=torch.bool, device=dev)
+ self.bad = torch.zeros(B, dtype=torch.bool, device=dev)
+ self.t = torch.zeros(B, dtype=torch.long, device=dev) # steps since the last reset
+ self._self_check(m0)
+
+ # ---- layout ------------------------------------------------------------------------------------------------
+ def _layout(self, m):
+ """Channel and pair tables from the model (no hard-coded channel indices beyond the 6 + 6 arm and 13 cube
+ base channels, which are checked)."""
+ dev = self.device
+ mov = [b for b in m.system["bodies"] if b["moving"]]
+ self.ia = next(n for n, b in enumerate(mov) if int(b.get("action_dim", 0)) > 0)
+ self.ic = next(n for n, b in enumerate(mov) if b["name"] == "cube")
+ aq, aqd = _cols(m.chan[self.ia, 0]), _cols(m.chan[self.ia, 2])
+ cp, cq, cv, cw = (_cols(m.chan[self.ic, k]) for k in range(4))
+ if (len(aq), len(aqd), len(cp), len(cq), len(cv), len(cw)) != (JOINTS, JOINTS, 3, 4, 3, 3):
+ raise ValueError("expected an arm with 6 angles + 6 rates and a cube with position, quaternion, velocity, spin")
+ if int(mov[self.ia]["action_dim"]) != JOINTS:
+ raise ValueError("expected 6 arm joint targets")
+ self.c_aq, self.c_aqd = _index(aq, dev), _index(aqd, dev)
+ self.c_cp, self.c_cq, self.c_cv, self.c_cw = (_index(c, dev) for c in (cp, cq, cv, cw))
+ names = [pm.get("name") for pm in m.system.get("pair_metadata", [])]
+ self.pair_names = names
+ self.contact_order = torch.tensor([names.index(n) for n in CONTACT_PAIRS], dtype=torch.long, device=dev)
+ 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)]
+ self._integ = []
+ for n in torch.nonzero(m.integ_body).flatten().tolist():
+ pc, qc, vc, wc = (_cols(m.chan[n, k]) for k in range(4))
+ self._integ.append((n, _index(pc, dev) if pc and vc else None, _index(vc, dev) if pc and vc else None,
+ _index(qc, dev) if len(qc) == 4 and len(wc) == 3 else None,
+ _index(wc, dev) if len(qc) == 4 and len(wc) == 3 else None))
+ self._quat = [(n, _index(_cols(torch.nonzero(m.quat[n]).flatten()), dev)) for n in range(m.n_bodies)
+ if bool(m.quat[n].any())]
+ table = next((b for b in m.system["bodies"] if not b["moving"] and "size_xy_m" in b), None)
+ margin = float(m.system.get("physics_config", {}).get("table", {}).get("edge_margin_m", 0.05))
+ c, s = (table["center_xy_m"], table["size_xy_m"]) if table else ([0.25, 0.0], [1.2, 1.2])
+ self.table_lo = [c[i] - 0.5 * s[i] + margin for i in range(2)]
+ self.table_hi = [c[i] + 0.5 * s[i] - margin for i in range(2)]
+
+ # ---- the model's assemble / finish without host syncs ---------------------------------------------------------
+ def _finish(self, m, x):
+ """ContactNRD.finish with precomputed column slices (same arithmetic, no torch.nonzero / .tolist())."""
+ if not self._quat:
+ return x
+ out = x.clone()
+ for n, qc in self._quat:
+ q = x[:, n, qc]
+ out[:, n, qc] = q / q.norm(dim=-1, keepdim=True).clamp_min(1e-12)
+ return out
+
+ def _finish_cube(self, m, x):
+ """model.finish of states x [n, D, S] whose only change is the cube quaternion (a relabelling): the cube
+ quaternion re-normalised."""
+ out = x.clone()
+ q = x[:, self.ic, self.c_cq]
+ out[:, self.ic, self.c_cq] = q / q.norm(dim=-1, keepdim=True).clamp_min(1e-12)
+ return out
+
+ def _assemble(self, m, cur, d_core, change):
+ """ContactNRD.assemble with precomputed column slices."""
+ nxt = cur + d_core + change
+ out = nxt.clone()
+ for n, pc, vc, qc, wc in self._integ:
+ mk = m.smask[n]
+ if pc is not None:
+ out[:, n, pc] = cur[:, n, pc] + m.dt * nxt[:, n, vc] * mk[pc]
+ if qc is not None:
+ half = 0.5 * m.dt * (nxt[:, n, wc] * mk[wc])
+ ang = half.norm(dim=-1, keepdim=True)
+ 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)
+ q = ContactNRD._qmul(dq, cur[:, n, qc])
+ out[:, n, qc] = torch.where(mk[qc] > 0, q, cur[:, n, qc])
+ return self._finish(m, out)
+
+ @torch.no_grad()
+ def _self_check(self, m):
+ """The sync-free assemble/finish must equal the model's own, bit for bit, on a random probe batch. If not
+ (a model with other channels), fall back to ContactNRD.assemble / finish themselves: same results,
+ but host syncs, so no CUDA graph (warning)."""
+ g = torch.Generator(device="cpu").manual_seed(0)
+ cur = (torch.randn(16, self.D, self.S, generator=g, dtype=torch.float64) * 0.3).to(self.device) * m.smask
+ d1 = (torch.randn(16, self.D, self.S, generator=g, dtype=torch.float64) * 0.3).to(self.device) * m.smask
+ d2 = (torch.randn(16, self.D, self.S, generator=g, dtype=torch.float64) * 0.3).to(self.device) * m.smask
+ try:
+ self.fast_layout = bool(torch.equal(self._finish(m, cur), m.finish(cur))
+ and torch.equal(self._assemble(m, cur, d1, d2), m.assemble(cur, d1, d2)))
+ except (RuntimeError, IndexError, TypeError):
+ self.fast_layout = False
+ if not self.fast_layout:
+ warnings.warn("GraspNrdSim: the model's finish/assemble differ from the sim's sync-free copy; using "
+ "ContactNRD.finish/assemble (eager only, no CUDA graph)")
+ self._finish = lambda m_, x: m_.finish(x)
+ self._assemble = lambda m_, cur_, d_core, change: m_.assemble(cur_, d_core, change)
+ self.use_graph = False
+ # the cube-only refinish of a relabelled state must equal model.finish (finished probes, every group element)
+ x = m.finish(cur.repeat(2, 1, 1))
+ k = torch.arange(len(x), device=self.device) % cs.ORDER
+ x[:, self.ic, self.c_cq] = cs.relabel(x[:, self.ic, self.c_cq], k, self._g, newest_sign=False)
+ try:
+ self.fast_relabel = self.fast_layout and bool(torch.equal(self._finish_cube(m, x), m.finish(x)))
+ except (RuntimeError, IndexError, TypeError):
+ self.fast_relabel = False
+ if not self.fast_relabel:
+ self._finish_cube = lambda m_, x_: self._finish(m_, x_)
+
+ # ---- the step ----------------------------------------------------------------------------------------------
+ def _member_step(self, m, hist, ok, act, rows, pairs):
+ """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]."""
+ cur, diff, lag_ok = m.code(hist, ok)
+ d_core = m.run_core(cur, diff, act, lag_ok)
+ b = cur.shape[0]
+ inp = m.pair_inputs(cur, diff, act, lag_ok, rows, pairs) # the same inputs for both pair networks
+ logits = m.collision(*inp)[:, 0].reshape(b, self.P)
+ g = (logits >= 0).to(cur.dtype)
+ o = m.contact(*inp).reshape(b, self.P, 2, self.S)
+ gg = g[:, :, None, None]
+ o = torch.where(gg > 0, o * gg, torch.zeros_like(o))
+ parts = [torch.zeros_like(cur[:, 0]) for _ in range(self.D)]
+ for k, (i, j) in enumerate(self.slots): # BOTH bodies of a pair get its change
+ parts[i] = parts[i] + o[:, k, 0]
+ if j is not None:
+ parts[j] = parts[j] + o[:, k, 1]
+ change = torch.stack(parts, 1) * m.smask
+ return self._assemble(m, cur, d_core, change), g, logits
+
+ def _relabel_hist(self, hist, k, changed):
+ """Relabel the cube quaternions of all K slots by G[k] (sign of the newest slot: w >= 0) and refinish every
+ slot of the worlds where changed (masked slots too; the model never reads them). hist [n, K, D, S] -> new."""
+ h = hist.clone()
+ h[:, :, self.ic, self.c_cq] = cs.relabel(hist[:, :, self.ic, self.c_cq], k, self._g)
+ fin = self._finish_cube(self.models[0], h.flatten(0, 1)).view_as(h)
+ return torch.where(changed[:, None, None, None], fin, hist)
+
+ def _invalid(self, st):
+ lim = self.limits
+ p = st[:, self.ic, self.c_cp]
+ bad = ~torch.isfinite(st).all(-1).all(-1)
+ 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])
+ bad |= (p[:, 2] < lim["cube_z_min"]) | (p[:, 2] > lim["cube_z_max"])
+ bad |= st[:, self.ic, self.c_cv].norm(dim=-1) > lim["cube_speed_max"]
+ bad |= st[:, self.ic, self.c_cw].norm(dim=-1) > lim["cube_spin_max"]
+ return bad
+
+ def _step_inplace(self):
+ outs = [self._member_step(m, self.hist[sl], self.ok[sl], self.act[sl], rows, pairs)
+ for m, sl, rows, pairs in self.blocks]
+ nxt, g, lg = (torch.cat([o[i] for o in outs]) if self.M > 1 else outs[0][i] for i in range(3))
+ hist = torch.cat((self.hist[:, 1:], nxt[:, None]), 1)
+ ok = torch.cat((self.ok[:, 1:], torch.ones_like(self.ok[:, :1])), 1)
+ if self.canonical:
+ qn = nxt[:, self.ic, self.c_cq]
+ k = cs.canonical_index(qn, self._scores, self.canon_margin)
+ changed = (k != 0) | (qn[:, 0] < 0)
+ hist = self._relabel_hist(hist, k, changed)
+ self.canon.copy_(self._mul[self.canon, k])
+ self.relabelled.copy_(changed)
+ qt = ContactNRD._qmul(hist[:, -1, self.ic, self.c_cq], self._gconj[self.canon])
+ qt = qt * torch.where((qt * self.true_q).sum(-1, keepdim=True) < 0, -1.0, 1.0).to(qt.dtype)
+ else:
+ qt = hist[:, -1, self.ic, self.c_cq]
+ self.hist.copy_(hist)
+ self.ok.copy_(ok)
+ self.true_q.copy_(qt)
+ self.prev_gates.copy_(self.gates)
+ self.gates.copy_(g)
+ self.logits.copy_(lg)
+ on = g > 0
+ if self.contact_rule == "physical":
+ on = on & (self.prev_gates > 0)
+ self.contact.copy_(on[:, self.contact_order])
+ self.bad.copy_(self._invalid(hist[:, -1]))
+ self.t.add_(1)
+
+ def _buffers(self):
+ return [self.hist, self.ok, self.act, self.gates, self.prev_gates, self.logits, self.canon, self.true_q,
+ self.relabelled, self.contact, self.bad, self.t]
+
+ def _capture(self):
+ snap = [t.clone() for t in self._buffers()]
+ s = torch.cuda.Stream(self.device)
+ s.wait_stream(torch.cuda.current_stream(self.device))
+ with torch.cuda.stream(s):
+ for _ in range(3):
+ self._step_inplace()
+ torch.cuda.current_stream(self.device).wait_stream(s)
+ for t, c in zip(self._buffers(), snap):
+ t.copy_(c)
+ del snap
+ torch.cuda.synchronize(self.device)
+ torch.cuda.empty_cache() # the warm-up's cached blocks; the graph gets its own pool (shared GPUs: one, not two)
+ self._graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(self._graph):
+ self._step_inplace()
+
+ @torch.no_grad()
+ def step(self, joint_targets: torch.Tensor) -> WorldState:
+ """joint_targets [B, 6]: absolute joint position targets (rad; jaw = index 5), held for 20 ms -> WorldState.
+ The applied action is float32(clip(target, kin.TLO, kin.THI)), the collector's applied value (as MuJoCo and
+ MuJoCo Warp apply it and the data store it; review F3)."""
+ u = joint_targets.to(device=self.device, dtype=torch.float64)
+ u = torch.minimum(torch.maximum(u, self._tlo), self._thi)
+ self.act[:, self.ia, :JOINTS].copy_(u.to(torch.float32).to(torch.float64))
+ if self.use_graph:
+ if self._graph is None:
+ self._capture()
+ self._graph.replay()
+ else:
+ self._step_inplace()
+ return self.observe()
+
+ @torch.no_grad()
+ def observe(self) -> WorldState:
+ """The current WorldState of all worlds (copies, not views of the buffers)."""
+ st = self.hist[:, -1]
+ q = st[:, self.ia, self.c_aq].clone()
+ arm_table = (self.arm_table_fn(q).to(device=self.device, dtype=torch.bool).reshape(self.B)
+ if self.arm_table_fn is not None else torch.zeros(self.B, dtype=torch.bool, device=self.device))
+ return WorldState(q=q, qd=st[:, self.ia, self.c_aqd].clone(), cube_pos=st[:, self.ic, self.c_cp].clone(),
+ cube_quat=self.true_q.clone(), cube_v=st[:, self.ic, self.c_cv].clone(),
+ cube_w=st[:, self.ic, self.c_cw].clone(), contact=self.contact.clone(), arm_table=arm_table,
+ invalid=self.bad.clone())
+
+ @property
+ def state(self) -> torch.Tensor:
+ """The newest NRD state [B, D, S] (model layout; cube quaternion canonical when canonical=True)."""
+ return self.hist[:, -1]
+
+ # ---- resets and disturbances -----------------------------------------------------------------------------------
+ def _idx(self, idx) -> torch.Tensor:
+ if idx is None:
+ return torch.arange(self.B, device=self.device)
+ idx = torch.as_tensor(idx, device=self.device)
+ return torch.nonzero(idx).flatten() if idx.dtype == torch.bool else idx.long().reshape(-1)
+
+ @torch.no_grad()
+ def reset(self, idx, start) -> WorldState:
+ """Reset worlds idx (long [n], bool [B] or None = all) to a resting-history start: start is a WorldState-like
+ object or dict with q [n, 6], cube_pos [n, 3], cube_quat [n, 4] (true orientation, w x y z) and optionally
+ qd, cube_v, cube_w (default 0). The quaternion is normalised (w >= 0) by model.finish; one valid history
+ entry (ContactNRD.start); the held command = the start angles.
+ -> WorldState of all worlds."""
+ idx = self._idx(idx)
+ f64 = dict(dtype=torch.float64, device=self.device)
+ n = len(idx)
+ raw = torch.zeros(n, self.D, self.S, **f64)
+ z3 = torch.zeros(n, 3, **f64)
+ raw[:, self.ia, self.c_aq] = torch.as_tensor(_get(start, "q"), **f64).reshape(n, JOINTS)
+ qd = _get(start, "qd")
+ raw[:, self.ia, self.c_aqd] = torch.zeros(n, JOINTS, **f64) if qd is None else torch.as_tensor(qd, **f64).reshape(n, JOINTS)
+ q = torch.as_tensor(_get(start, "cube_quat"), **f64).reshape(n, 4)
+ q = q / q.norm(dim=-1, keepdim=True)
+ raw[:, self.ic, self.c_cp] = torch.as_tensor(_get(start, "cube_pos"), **f64).reshape(n, 3)
+ raw[:, self.ic, self.c_cq] = q * torch.where(q[:, :1] < 0, -1.0, 1.0).to(q.dtype)
+ for name, c in (("cube_v", self.c_cv), ("cube_w", self.c_cw)):
+ v = _get(start, name)
+ raw[:, self.ic, c] = z3 if v is None else torch.as_tensor(v, **f64).reshape(n, 3)
+ return self.reset_state(idx, raw, finish=True)
+
+ @torch.no_grad()
+ def reset_state(self, idx, state: torch.Tensor, finish: bool = True) -> WorldState:
+ """Reset worlds idx from model-layout states [n, D, S] (one valid history entry). finish=False keeps the
+ given quaternion as it is (exact replay of ContactNRD.rollout from a recorded state); a canonical relabelling
+ still re-normalises the cube quaternion of the relabelled worlds. -> WorldState of all worlds."""
+ state = state.to(device=self.device, dtype=torch.float64)
+ h, ok = self.models[0].start(state)
+ return self.reset_history(idx, h, ok, finish=finish)
+
+ @torch.no_grad()
+ def reset_history(self, idx, hist: torch.Tensor, ok: torch.Tensor, finish: bool = False) -> WorldState:
+ """Reset worlds idx from model-layout histories [n, K, D, S] (newest last) with masks ok [n, K] (a recorded
+ window, as rollouts.rollouts' "window" mode). The true orientation = the given newest cube quaternion.
+ -> WorldState of all worlds."""
+ idx = self._idx(idx)
+ h = hist.to(device=self.device, dtype=torch.float64).clone()
+ ok = ok.to(device=self.device, dtype=torch.bool)
+ m0 = self.models[0]
+ if finish:
+ h = torch.where(ok[..., None, None], m0.finish(h.flatten(0, 1)).view_as(h), h)
+ true_q = h[:, -1, self.ic, self.c_cq].clone()
+ if self.canonical:
+ k = cs.canonical_index(true_q, self._scores, self.canon_margin)
+ h = self._relabel_hist(h, k, (k != 0) | (true_q[:, 0] < 0))
+ self.canon[idx] = k
+ else:
+ self.canon[idx] = 0
+ self.hist[idx], self.ok[idx], self.true_q[idx] = h, ok, true_q
+ self.act[idx] = 0.0
+ self.act[idx, self.ia, :JOINTS] = h[:, -1, self.ia, self.c_aq]
+ for t in (self.gates, self.prev_gates, self.logits):
+ t[idx] = 0.0
+ self.relabelled[idx], self.contact[idx], self.t[idx] = False, False, 0
+ self.bad[idx] = self._invalid(h[:, -1])
+ return self.observe()
+
+ @torch.no_grad()
+ def set_cube(self, idx, pos, quat, v=None, w=None) -> WorldState:
+ """Move the cube of worlds idx (disturbance, module docstring): pos [n, 3] (m, world), quat [n, 4] (TRUE
+ orientation, w x y z), v, w [n, 3] (world, step average; default 0 = a resting cube, the only case in the
+ data). The base cube channels go into all K history slots, the arm channels and ok are kept, model.finish
+ runs on each slot; the cube is then canonicalised. -> WorldState of all worlds."""
+ idx = self._idx(idx)
+ n, K = len(idx), self.K
+ f64 = dict(dtype=torch.float64, device=self.device)
+ pos = torch.as_tensor(pos, **f64).reshape(n, 3)
+ quat = torch.as_tensor(quat, **f64).reshape(n, 4)
+ quat = quat / quat.norm(dim=-1, keepdim=True)
+ v = torch.zeros(n, 3, **f64) if v is None else torch.as_tensor(v, **f64).reshape(n, 3)
+ w = torch.zeros(n, 3, **f64) if w is None else torch.as_tensor(w, **f64).reshape(n, 3)
+ quat = quat * torch.where((quat * self.true_q[idx]).sum(-1, keepdim=True) < 0, -1.0, 1.0).to(quat.dtype)
+ age = torch.arange(K - 1, -1, -1, **f64)[None, :, None] * self.dt # [1, K, 1] age of each slot (s)
+ half = -0.5 * age * w[:, None] # rotation back in time
+ ang = half.norm(dim=-1, keepdim=True)
+ 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)
+ h = self.hist[idx].clone()
+ h[:, :, self.ic, self.c_cp] = pos[:, None] - age * v[:, None]
+ h[:, :, self.ic, self.c_cq] = ContactNRD._qmul(dq, quat[:, None].expand(-1, K, -1))
+ h[:, :, self.ic, self.c_cv] = v[:, None].expand(-1, K, -1)
+ h[:, :, self.ic, self.c_cw] = w[:, None].expand(-1, K, -1)
+ if self.canonical:
+ k = cs.canonical_index(quat, self._scores, self.canon_margin)
+ h[:, :, self.ic, self.c_cq] = cs.relabel(h[:, :, self.ic, self.c_cq], k, self._g)
+ self.canon[idx] = k
+ else:
+ self.canon[idx] = 0
+ h = self.models[0].finish(h.flatten(0, 1)).view_as(h) # every slot, masked ones too
+ self.hist[idx], self.true_q[idx] = h, quat
+ self.bad[idx] = self._invalid(h[:, -1])
+ return self.observe()
diff --git a/so101_pick_place/code/src/nedm/so101_policy/paths.py b/so101_pick_place/code/src/nedm/so101_policy/paths.py
new file mode 100644
index 0000000000000000000000000000000000000000..6803120a988c4e1938bd7a515079f9610295d254
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/paths.py
@@ -0,0 +1,21 @@
+"""Default locations of the data of the SO101 pick-and-place release (so101_pick_place/README.md).
+
+One rule for every default input path of this package and its scripts:
+
+- Files on the Hub (checkpoints, task sets, start banks, geometry, NRD data, robot recordings) are read from
+ ``DATA = /artifacts/so101_pick_place``, the Hub folder ``so101_pick_place/`` after
+ ``scripts/so101_pick_place/reproduce.sh --steps download``, with the Hub's sub-folders (``nrd/``,
+ ``rl_inputs/``, ``teacher/``, ...).
+- Small files in git (camera calibration, scene, servo fit, LeRobot motor calibration) are read from
+ ``CONFIGS = /configs/so101_pick_place``.
+
+Paths inside the JSON configs use the same two folders, written relative to the repository root
+(``artifacts/so101_pick_place/...``, ``configs/so101_pick_place/...``): run the commands from the repository root.
+To keep the data on another disk, link ``artifacts/`` there. The study code read the same files from home-folder
+copies (``~/so101_policy/ckpt``, ``~/so101_r2s_claude``); the files are the same (sha256 in release_manifest.json).
+"""
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parents[3]
+DATA = REPO / "artifacts" / "so101_pick_place"
+CONFIGS = REPO / "configs" / "so101_pick_place"
diff --git a/so101_pick_place/code/src/nedm/so101_policy/ppo.py b/so101_pick_place/code/src/nedm/so101_policy/ppo.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bf08d4ed56b18398deea23b594c8284907498f5
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/ppo.py
@@ -0,0 +1,547 @@
+"""PPO for the SO101 + cube goal pick-and-place policy (``vec_env.PickPlaceVecEnv``; trainer
+``scripts/so101_policy/train_ppo.py``), adapted from the G1 study (worktree t3code-7d8d61fa:
+``src/nedm/g1_policy/ppo_utils.py`` + ``scripts/g1_policy/train_planks_ppo.py`` on RSL-RL 2.2.4; read only, copied
+and changed here):
+
+| Piece | Here | G1 |
+|---|---|---|
+| 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 |
+| optimizer | ``split_optimizer``: Adam, actor + std at the adaptive rate, critic at a fixed rate | ppo_utils.split_optimizer |
+| 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) |
+| 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 |
+| time-out bootstrap | reward += gamma V(final observation) at time-outs (current critic, normaliser not updated) | patch_bootstrap |
+| 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 |
+| 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 |
+| 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 |
+| 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 |
+| 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 |
+
+Policy (``Policy``): actor and critic MLPs (default 512-256-128 ELU, separate), Gaussian on the pre-tanh action (the env
+squashes with tanh; the trigger is a[4] > 0); the actor's last layer x ``actor_out_gain`` and its bias = ``action_bias``
+(default trigger -2: P(trigger) = 2.3 % per decision at std 1). ``act_inference(obs)`` = the deterministic pre-tanh
+mean. Checkpoints (``PPO.save``) hold the policy, its constructor arguments, the optimizer, the learning rate, the
+counters and the RNG states; ``load_policy(path)`` rebuilds the policy for evaluation.
+"""
+from __future__ import annotations
+
+import csv
+import hashlib
+import json
+import math
+import time
+from pathlib import Path
+
+import numpy as np
+import torch
+import torch.nn as nn
+
+from nedm.so101_policy.task import ENDS
+
+LOG2PI = math.log(2 * math.pi)
+# values of the "abort" action group (decoder abort_action) when a train config lists 3 groups only
+ABORT_GROUP = dict(init_std=0.5, std_floor=0.2, std_cap=1.0, std_reset=0.5, bias=-3.0)
+ACT = {"elu": nn.ELU, "relu": nn.ReLU, "tanh": nn.Tanh, "silu": nn.SiLU}
+
+
+def train_cfg_default(seed=1) -> dict:
+ """PPO defaults (G1 train_cfg_default values; gamma per 0.1 s decision)."""
+ return {
+ "algorithm": {"clip_param": 0.2, "desired_kl": 0.01, "entropy_coef": 0.002, "gamma": 0.99, "lam": 0.95,
+ "learning_rate": 3e-4, "max_grad_norm": 1.0, "num_learning_epochs": 5, "num_mini_batches": 8,
+ "schedule": "adaptive", "use_clipped_value_loss": True, "value_loss_coef": 1.0},
+ "policy": {"actor_hidden_dims": [512, 256, 128], "critic_hidden_dims": [512, 256, 128], "activation": "elu",
+ "actor_out_gain": 0.01, "action_bias": [0.0, 0.0, 0.0, 0.0, -2.0, 0.0], "norm_clip": 10.0},
+ "num_steps_per_env": 32,
+ "critic_lr": 3e-4,
+ "init_std": [0.3, 1.0, 0.5], # [move (pre-tanh, review P1-10: <= 0.3), trigger, lift height]
+ "std_floor": [0.15, 0.3, 0.2],
+ "std_cap": [0.3, 2.0, 1.0],
+ "std_reset": [0.3, 1.0, 0.5], # raised to at least this at a curriculum promotion
+ "seed": seed,
+ }
+
+
+def merge(cfg: dict, over: dict | None) -> dict:
+ """Recursive dict update (nested dicts merged, other values replaced)."""
+ for k, v in (over or {}).items():
+ if isinstance(v, dict) and isinstance(cfg.get(k), dict):
+ merge(cfg[k], v)
+ else:
+ cfg[k] = v
+ return cfg
+
+
+def sha256(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for b in iter(lambda: f.read(1 << 22), b""):
+ h.update(b)
+ return h.hexdigest()
+
+
+def write_json(path, obj):
+ Path(path).write_text(json.dumps(obj, indent=1, default=lambda o: o.tolist() if hasattr(o, "tolist") else str(o)))
+
+
+def group_values(values, groups, key):
+ """Per-group values of a train config entry ``key`` for the env's groups: a 3-group list gets the abort group's
+ value (``ABORT_GROUP``) appended when the env has 4 groups."""
+ if isinstance(values, (int, float)) or len(values) == len(groups):
+ return values
+ if len(values) == len(groups) - 1 and len(groups) == 4:
+ return list(values) + [ABORT_GROUP[key]]
+ raise ValueError(f"{key} {values}: need one value per action group {groups}")
+
+
+def action_bias_for(bias, act_dim):
+ """The actor's output bias for act_dim actions (a 6-entry bias + the abort bias for a 7th action)."""
+ if bias is None or len(bias) == act_dim:
+ return bias
+ if len(bias) == 6 and act_dim == 7:
+ return list(bias) + [ABORT_GROUP["bias"]]
+ raise ValueError(f"action_bias {bias} for {act_dim} actions")
+
+
+def per_action(values, groups, device="cpu"):
+ """Per-group values (a number, or one per group) -> per-action tensor [sum(groups)] (float32)."""
+ if isinstance(values, (int, float)):
+ return torch.full((sum(groups),), float(values), device=device)
+ if len(values) != len(groups):
+ raise ValueError(f"{values}: need one value per action group {groups}")
+ return torch.cat([torch.full((n,), float(v), device=device) for v, n in zip(values, groups)])
+
+
+# ---- policy -----------------------------------------------------------------------------------------------------
+class RunningNorm(nn.Module):
+ """Running mean / variance of observations (float64, Chan's parallel update); forward = (x - mean) / (std + eps)
+ clipped to +-clip, float32."""
+
+ def __init__(self, dim, eps=1e-2, clip=10.0):
+ super().__init__()
+ self.eps, self.clip = float(eps), float(clip)
+ self.register_buffer("mean", torch.zeros(dim, dtype=torch.float64))
+ self.register_buffer("var", torch.ones(dim, dtype=torch.float64))
+ self.register_buffer("count", torch.zeros((), dtype=torch.float64))
+
+ @torch.no_grad()
+ def update(self, x):
+ x = x.detach().to(torch.float64).reshape(-1, self.mean.shape[0])
+ n = x.shape[0]
+ m, v = x.mean(0), x.var(0, unbiased=False)
+ tot = self.count + n
+ d = m - self.mean
+ self.mean.add_(d * n / tot)
+ self.var.copy_((self.var * self.count + v * n + d * d * self.count * n / tot) / tot)
+ self.count.copy_(tot)
+
+ def forward(self, x):
+ y = (x.to(torch.float64) - self.mean) / (self.var.sqrt() + self.eps)
+ return y.clamp(-self.clip, self.clip).to(torch.float32)
+
+
+def mlp(n_in, hidden, n_out, act="elu"):
+ layers, k = [], n_in
+ for h in hidden:
+ layers += [nn.Linear(k, h), ACT[act]()]
+ k = h
+ layers.append(nn.Linear(k, n_out))
+ return nn.Sequential(*layers)
+
+
+class Policy(nn.Module):
+ """Observation normaliser + Gaussian actor (pre-tanh mean, per-action std parameter) + critic (module docstring)."""
+
+ def __init__(self, obs_dim, act_dim=6, groups=(4, 1, 1), actor_hidden_dims=(512, 256, 128),
+ critic_hidden_dims=(512, 256, 128), activation="elu", init_std=(0.3, 1.0, 0.5), actor_out_gain=0.01,
+ action_bias=None, norm_clip=10.0, ctx_index=None, ctx_init_std=None):
+ super().__init__()
+ self.kwargs = dict(obs_dim=int(obs_dim), act_dim=int(act_dim), groups=[int(g) for g in groups],
+ actor_hidden_dims=list(actor_hidden_dims), critic_hidden_dims=list(critic_hidden_dims),
+ activation=activation, init_std=list(init_std) if not isinstance(init_std, (int, float)) else init_std,
+ actor_out_gain=float(actor_out_gain),
+ action_bias=None if action_bias is None else [float(x) for x in action_bias],
+ norm_clip=float(norm_clip), ctx_index=None if ctx_index is None else int(ctx_index),
+ ctx_init_std=None if ctx_init_std is None else (list(ctx_init_std) if not isinstance(
+ ctx_init_std, (int, float)) else ctx_init_std))
+ if sum(groups) != act_dim:
+ raise ValueError(f"groups {groups} do not sum to {act_dim}")
+ self.groups = list(groups)
+ self.norm = RunningNorm(obs_dim, clip=norm_clip)
+ self.actor = mlp(obs_dim, actor_hidden_dims, act_dim, activation)
+ self.critic = mlp(obs_dim, critic_hidden_dims, 1, activation)
+ self.std = nn.Parameter(per_action(init_std, self.groups))
+ self.ctx_index = None if ctx_index is None else int(ctx_index)
+ if self.ctx_index is not None: # second std vector where obs[:, ctx_index] > 0.5 (decoder mode hold)
+ self.std_ctx = nn.Parameter(per_action(init_std if ctx_init_std is None else ctx_init_std, self.groups))
+ last = self.actor[-1]
+ with torch.no_grad():
+ last.weight.mul_(float(actor_out_gain))
+ last.bias.zero_()
+ if action_bias is not None:
+ last.bias.copy_(torch.as_tensor(action_bias, dtype=last.bias.dtype))
+
+ def value(self, obs_n):
+ return self.critic(obs_n).squeeze(-1)
+
+ @torch.no_grad()
+ def act_inference(self, obs):
+ """Raw observation [B, D] -> deterministic pre-tanh action [B, A] (the normaliser is not updated)."""
+ return self.actor(self.norm(obs))
+
+ def ctx(self, obs_raw):
+ """[B] bool: rows that use the context std (None without it)."""
+ return None if self.ctx_index is None else obs_raw[:, self.ctx_index] > 0.5
+
+ def std_of(self, ctx):
+ """Per-sample std [B, A] for context flags ctx [B] (or the shared [A] vector without a context std)."""
+ if ctx is None:
+ return self.std
+ return torch.where(ctx[:, None], self.std_ctx, self.std)
+
+ def std_groups(self, ctx=False):
+ out, k = [], 0
+ v = self.std_ctx if ctx else self.std
+ for n in self.groups:
+ out.append(float(v[k:k + n].detach().mean()))
+ k += n
+ return out
+
+
+def log_prob(mu, std, a, mask):
+ """Masked Gaussian log-likelihood [B] (sum over the used dims)."""
+ lp = -0.5 * ((a - mu) / std) ** 2 - torch.log(std) - 0.5 * LOG2PI
+ return (lp * mask).sum(-1)
+
+
+def entropy(std, mask):
+ """Masked Gaussian entropy [B]."""
+ return ((0.5 + 0.5 * LOG2PI + torch.log(std)).expand_as(mask) * mask).sum(-1)
+
+
+def kl_div(mu0, std0, mu1, std1, mask):
+ """Masked KL(old || new) [B] (RSL-RL form)."""
+ k = torch.log(std1 / std0 + 1e-5) + (std0 ** 2 + (mu0 - mu1) ** 2) / (2 * std1 ** 2) - 0.5
+ return (k * mask).sum(-1)
+
+
+def gae(rewards, values, dones, last_values, gamma, lam):
+ """GAE over [T, B] (RSL-RL RolloutStorage.compute_returns): -> (returns, advantages), not normalised."""
+ T = rewards.shape[0]
+ adv = torch.zeros_like(last_values)
+ out = torch.empty_like(rewards)
+ for t in reversed(range(T)):
+ nxt = last_values if t == T - 1 else values[t + 1]
+ nd = 1.0 - dones[t].to(rewards.dtype)
+ delta = rewards[t] + nd * gamma * nxt - values[t]
+ adv = delta + nd * gamma * lam * adv
+ out[t] = adv
+ return out + values, out
+
+
+def split_optimizer(policy: Policy, lr, critic_lr):
+ """Adam: group 0 = actor + std (PPO's adaptive rate), group 1 = critic (fixed critic_lr)."""
+ actor = list(policy.actor.parameters()) + [policy.std] + ([policy.std_ctx] if policy.ctx_index is not None else [])
+ return torch.optim.Adam([{"params": actor, "lr": lr}, {"params": list(policy.critic.parameters()), "lr": critic_lr}])
+
+
+# ---- rollouts and updates -------------------------------------------------------------------------------------------
+class Rollout:
+ def __init__(self, T, B, obs_dim, act_dim, device):
+ f = dict(device=device)
+ self.T, self.B = T, B
+ self.obs = torch.zeros(T, B, obs_dim, **f)
+ self.act = torch.zeros(T, B, act_dim, **f)
+ self.mask = torch.zeros(T, B, act_dim, dtype=torch.bool, **f)
+ self.logp = torch.zeros(T, B, **f)
+ self.mu = torch.zeros(T, B, act_dim, **f)
+ self.std = torch.zeros(T, B, act_dim, **f) # per-sample std of the sampling policy
+ self.ctx = torch.zeros(T, B, dtype=torch.bool, **f) # context std rows (decoder mode hold)
+ self.values = torch.zeros(T, B, **f)
+ self.rewards = torch.zeros(T, B, **f)
+ self.dones = torch.zeros(T, B, dtype=torch.bool, **f)
+
+
+class PPO:
+ """PPO on a ``PickPlaceVecEnv`` (module docstring). cfg = ``train_cfg_default`` layout."""
+
+ def __init__(self, env, policy: Policy, cfg: dict, device=None):
+ self.env, self.policy, self.cfg = env, policy, cfg
+ self.dev = torch.device(device or env.dev)
+ al = cfg["algorithm"]
+ self.al = al
+ self.gamma, self.lam = float(al["gamma"]), float(al["lam"])
+ self.lr = float(al["learning_rate"])
+ self.critic_lr = float(cfg["critic_lr"])
+ self.opt = split_optimizer(policy, self.lr, self.critic_lr)
+ self.groups = policy.groups
+ self.floor = per_action(group_values(cfg["std_floor"], self.groups, "std_floor"), self.groups, self.dev)
+ self.cap = per_action(group_values(cfg["std_cap"], self.groups, "std_cap"), self.groups, self.dev)
+ hs = cfg.get("hold_std") or {}
+ if policy.ctx_index is not None:
+ self.floor_ctx = per_action(group_values(hs.get("floor", cfg["std_floor"]), self.groups, "std_floor"),
+ self.groups, self.dev)
+ self.cap_ctx = per_action(group_values(hs.get("cap", cfg["std_cap"]), self.groups, "std_cap"),
+ self.groups, self.dev)
+ self.clamp_std()
+ self.T = int(cfg["num_steps_per_env"])
+ self.roll = Rollout(self.T, env.num_envs, env.num_obs, env.num_actions, self.dev)
+ self.gen = torch.Generator(self.dev).manual_seed(int(cfg.get("seed", 1)) + 7)
+ self.obs = None
+ self.iteration = 0 # completed iterations
+ self.decisions = 0 # PPO transitions (all envs)
+ self.world_steps = 0 # 20 ms world steps (all envs)
+ self.episodes = 0
+ self.wall = 0.0 # training wall clock (s), summed over resumed jobs
+
+ @torch.no_grad()
+ def clamp_std(self):
+ self.policy.std.copy_(torch.minimum(torch.maximum(self.policy.std, self.floor), self.cap))
+ if self.policy.ctx_index is not None:
+ self.policy.std_ctx.copy_(torch.minimum(torch.maximum(self.policy.std_ctx, self.floor_ctx), self.cap_ctx))
+
+ @torch.no_grad()
+ def set_std(self, values, at_least=False):
+ """The shared std (the context std, if any, is not reset)."""
+ v = per_action(group_values(values, self.groups, "std_reset"), self.groups, self.dev)
+ self.policy.std.copy_(torch.maximum(self.policy.std, v) if at_least else v)
+ self.clamp_std()
+
+ # -- rollout --
+ @torch.no_grad()
+ def collect(self):
+ """num_steps_per_env decisions of every env -> episode / step statistics (GPU tensors)."""
+ env, pol, R = self.env, self.policy, self.roll
+ if self.obs is None:
+ self.obs = env.reset()
+ obs = self.obs
+ B, dev = env.num_envs, self.dev
+ nE = len(ENDS)
+ st = {k: torch.zeros((), dtype=torch.float64, device=dev) for k in
+ ("episodes", "success", "success10", "lifted", "ret", "length", "end_xy_succ", "reward", "time_outs",
+ "grasp_starts", "move_used", "trigger_used")}
+ st["ends"] = torch.zeros(nE, dtype=torch.float64, device=dev)
+ for t in range(self.T):
+ pol.norm.update(obs)
+ on = pol.norm(obs)
+ mu = pol.actor(on)
+ v = pol.value(on)
+ ctx = pol.ctx(obs)
+ std = pol.std_of(ctx).detach().expand_as(mu)
+ a = mu + std * torch.randn(mu.shape, generator=self.gen, device=dev)
+ obs2, r, done, ex = env.step(a)
+ mask = ex["action_mask"]
+ r = r.to(dev)
+ to = ex["time_outs"]
+ vf = pol.value(pol.norm(ex["final_obs"]))
+ r = r + torch.where(to, self.gamma * vf, torch.zeros_like(vf))
+ R.obs[t], R.act[t], R.mask[t], R.mu[t], R.values[t], R.std[t] = on, a, mask, mu, v, std
+ if ctx is not None:
+ R.ctx[t] = ctx
+ R.logp[t] = log_prob(mu, std, a, mask)
+ R.rewards[t], R.dones[t] = r, done
+ ep = ex["episode"]
+ d = done.to(torch.float64)
+ st["episodes"] += d.sum()
+ st["success"] += (ep["success"] & done).sum()
+ st["success10"] += (ep["success10"] & done).sum()
+ st["lifted"] += (ep["lifted"] & done).sum()
+ st["ret"] += (ep["ret"] * d).sum()
+ st["length"] += (ep["length"] * d).sum()
+ st["end_xy_succ"] += torch.where(ep["success"] & done, ep["end_xy"], torch.zeros_like(ep["end_xy"])).sum()
+ st["time_outs"] += to.sum()
+ st["ends"] += (torch.nn.functional.one_hot(ep["end"].clamp(0, nE - 1), nE) * d[:, None]).sum(0)
+ st["reward"] += r.sum()
+ st["grasp_starts"] += mask[:, 5].sum()
+ st["move_used"] += mask[:, 0].sum()
+ st["trigger_used"] += mask[:, 4].sum()
+ for k, v in ex.get("counts", {}).items():
+ key = "count_" + k
+ if key not in st:
+ st[key] = torch.zeros((), dtype=torch.float64, device=dev)
+ st[key] += v.sum()
+ obs = obs2
+ self.obs = obs
+ self.last_values = pol.value(pol.norm(obs))
+ self.decisions += self.T * B
+ self.world_steps += self.T * B * env.steps_per_decision
+ return st
+
+ # -- update --
+ def update(self):
+ al, pol, R = self.al, self.policy, self.roll
+ with torch.no_grad():
+ returns, adv = gae(R.rewards, R.values, R.dones, self.last_values, self.gamma, self.lam)
+ adv = (adv - adv.mean()) / (adv.std() + 1e-8)
+ N = R.T * R.B
+ flat = lambda x: x.reshape(N, *x.shape[2:]) # noqa: E731
+ obs, act, mask, old_lp, old_mu = flat(R.obs), flat(R.act), flat(R.mask).float(), flat(R.logp), flat(R.mu)
+ old_v, ret, adv = flat(R.values), flat(returns), flat(adv)
+ old_std_all, ctx_all = flat(R.std), flat(R.ctx)
+ use_ctx = pol.ctx_index is not None
+ clip = float(al["clip_param"])
+ n_mb = int(al["num_mini_batches"])
+ mb = N // n_mb
+ out = dict(value_loss=0.0, surrogate_loss=0.0, entropy=0.0, kl=0.0, clip_frac=0.0)
+ n_up = 0
+ for _ in range(int(al["num_learning_epochs"])):
+ perm = torch.randperm(N, generator=self.gen, device=self.dev)
+ for k in range(n_mb):
+ i = perm[k * mb:(k + 1) * mb]
+ m = mask[i]
+ mu = pol.actor(obs[i])
+ v = pol.value(obs[i])
+ std = pol.std_of(ctx_all[i] if use_ctx else None)
+ lp = log_prob(mu, std, act[i], m)
+ with torch.no_grad():
+ kl = kl_div(old_mu[i], old_std_all[i], mu, std, m)
+ act_rows = (m.sum(-1) > 0).float()
+ kl_mean = float((kl * act_rows).sum() / act_rows.sum().clamp_min(1.0))
+ if al.get("desired_kl") is not None and al.get("schedule") == "adaptive":
+ if kl_mean > al["desired_kl"] * 2.0:
+ self.lr = max(1e-5, self.lr / 1.5)
+ elif 0.0 < kl_mean < al["desired_kl"] / 2.0:
+ self.lr = min(1e-2, self.lr * 1.5)
+ self.opt.param_groups[0]["lr"] = self.lr
+ self.opt.param_groups[1]["lr"] = self.critic_lr
+ ratio = torch.exp(lp - old_lp[i])
+ a_ = adv[i]
+ surr = torch.max(-a_ * ratio, -a_ * ratio.clamp(1 - clip, 1 + clip)).mean()
+ if al.get("use_clipped_value_loss", True):
+ vc = old_v[i] + (v - old_v[i]).clamp(-clip, clip)
+ vloss = torch.max((v - ret[i]) ** 2, (vc - ret[i]) ** 2).mean()
+ else:
+ vloss = ((v - ret[i]) ** 2).mean()
+ ent = entropy(std, m).mean()
+ loss = surr + float(al["value_loss_coef"]) * vloss - float(al["entropy_coef"]) * ent
+ self.opt.zero_grad()
+ loss.backward()
+ nn.utils.clip_grad_norm_(pol.parameters(), float(al["max_grad_norm"]))
+ self.opt.step()
+ self.clamp_std()
+ with torch.no_grad():
+ out["clip_frac"] += float(((ratio - 1).abs() > clip).float().mean())
+ out["value_loss"] += float(vloss.detach())
+ out["surrogate_loss"] += float(surr.detach())
+ out["entropy"] += float(ent.detach())
+ out["kl"] += kl_mean
+ n_up += 1
+ return {k: v / max(n_up, 1) for k, v in out.items()}
+
+ def iterate(self):
+ """One collect + update -> stats dict (host floats)."""
+ t0 = time.time()
+ st = self.collect()
+ if self.dev.type == "cuda":
+ torch.cuda.synchronize(self.dev)
+ t1 = time.time()
+ up = self.update()
+ t2 = time.time()
+ self.iteration += 1
+ self.wall += t2 - t0
+ s = {k: v.cpu().numpy() for k, v in st.items()}
+ n = float(s["episodes"])
+ B, T, spd = self.env.num_envs, self.T, self.env.steps_per_decision
+ self.episodes += int(n)
+ row = dict(iteration=self.iteration, decisions=self.decisions, world_steps=self.world_steps,
+ wall_s=self.wall, collection_s=t1 - t0, learn_s=t2 - t1,
+ world_steps_per_s=B * T * spd / max(t1 - t0, 1e-9),
+ world_steps_per_s_total=B * T * spd / max(t2 - t0, 1e-9),
+ reward_per_decision=float(s["reward"]) / (B * T),
+ episodes=n, success=float(s["success"]) / n if n else math.nan,
+ success10=float(s["success10"]) / n if n else math.nan,
+ lifted=float(s["lifted"]) / n if n else math.nan,
+ ep_return=float(s["ret"]) / n if n else math.nan,
+ ep_length=float(s["length"]) / n if n else math.nan,
+ end_xy_success_mm=1e3 * float(s["end_xy_succ"]) / max(float(s["success"]), 1.0),
+ grasp_starts_per_episode=float(s["grasp_starts"]) / n if n else math.nan,
+ move_used=float(s["move_used"]) / (B * T), trigger_used=float(s["trigger_used"]) / (B * T),
+ lr=self.lr, critic_lr=self.critic_lr, **up)
+ for k in s:
+ if k.startswith("count_"):
+ row[k[6:] + "_per_episode"] = float(s[k]) / n if n else math.nan
+ for j, g in enumerate(self.policy.std_groups()):
+ row[f"std_{('move', 'trigger', 'lift', 'abort')[j] if j < 4 else j}"] = g
+ if self.policy.ctx_index is not None:
+ for j, g in enumerate(self.policy.std_groups(ctx=True)):
+ row[f"std_hold_{('move', 'trigger', 'lift', 'abort')[j] if j < 4 else j}"] = g
+ for k, name in enumerate(ENDS[1:], start=1):
+ row[f"end_{name}"] = float(s["ends"][k]) / n if n else math.nan
+ if self.dev.type == "cuda":
+ row["gpu_mem_gb"] = torch.cuda.max_memory_allocated(self.dev) / 1e9 # torch allocator peak
+ free, total = torch.cuda.mem_get_info(self.dev)
+ row["gpu_used_gb"] = (total - free) / 1e9 # whole device (other processes and Warp's pool included)
+ return row
+
+ # -- checkpoints --
+ def state(self, extra=None) -> dict:
+ env = self.env
+ return dict(policy=self.policy.state_dict(), policy_kwargs=self.policy.kwargs, optimizer=self.opt.state_dict(),
+ lr=self.lr, iteration=self.iteration, decisions=self.decisions, world_steps=self.world_steps,
+ episodes=self.episodes, wall=self.wall, gen=self.gen.get_state(),
+ env_gen=env.gen.get_state(), extra=extra or {},
+ env=env.resolved() if hasattr(env, "resolved") else None,
+ env_ep_count=env.ep_count.clone().cpu() if hasattr(env, "ep_count") else None)
+
+ def save(self, path, extra=None):
+ tmp = Path(str(path) + ".tmp")
+ torch.save(self.state(extra), tmp)
+ tmp.replace(path)
+
+ def load(self, path, optimizer=True):
+ d = torch.load(path, map_location=self.dev, weights_only=False)
+ self.policy.load_state_dict(d["policy"])
+ if optimizer:
+ self.opt.load_state_dict(d["optimizer"])
+ self.lr = float(d["lr"])
+ self.iteration, self.decisions, self.world_steps = d["iteration"], d["decisions"], d["world_steps"]
+ self.episodes, self.wall = d.get("episodes", 0), d.get("wall", 0.0)
+ self.gen.set_state(d["gen"].cpu())
+ if "env_gen" in d:
+ self.env.gen.set_state(d["env_gen"].cpu())
+ if d.get("env_ep_count") is not None and hasattr(self.env, "ep_count"): # macro-seed streams go on
+ self.env.ep_count.copy_(d["env_ep_count"].to(self.env.ep_count.device))
+ return d
+
+
+def load_policy(path, device="cpu", with_env=False):
+ """A saved checkpoint (``PPO.save``) -> Policy in eval mode on device (with_env: (policy, the checkpoint's
+ ``env`` provenance dict or None for checkpoints written before 2026-10-11 23:00))."""
+ d = torch.load(path, map_location=device, weights_only=False)
+ pol = Policy(**d["policy_kwargs"]).to(device)
+ pol.load_state_dict(d["policy"])
+ return (pol.eval(), d.get("env")) if with_env else pol.eval()
+
+
+class CurveWriter:
+ """learning_curve.csv: one row per iteration; a resumed run appends under the existing header (new keys are
+ dropped, missing ones left empty)."""
+
+ def __init__(self, path):
+ self.path = Path(path)
+ self.header = None
+ if self.path.exists() and self.path.stat().st_size:
+ with open(self.path, newline="") as f:
+ self.header = next(csv.reader(f))
+
+ def write(self, row: dict):
+ new = self.header is None
+ if new:
+ self.header = list(row)
+ with open(self.path, "a", newline="") as f:
+ w = csv.DictWriter(f, fieldnames=self.header, extrasaction="ignore")
+ if new:
+ w.writeheader()
+ w.writerow({k: (f"{v:.6g}" if isinstance(v, float) else v) for k, v in row.items()})
+
+
+def read_curve(path) -> dict:
+ """learning_curve.csv -> {column: numpy array}."""
+ with open(path, newline="") as f:
+ rows = list(csv.DictReader(f))
+ out = {}
+ for k in (rows[0] if rows else {}):
+ try:
+ out[k] = np.array([float(r[k]) if r[k] != "" else np.nan for r in rows])
+ except ValueError:
+ out[k] = np.array([r[k] for r in rows])
+ return out
diff --git a/so101_pick_place/code/src/nedm/so101_policy/table.py b/so101_pick_place/code/src/nedm/so101_policy/table.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8d775740bdd90b347c9238c2fbc04a41a9bee08
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/table.py
@@ -0,0 +1,169 @@
+"""A table that is not at z = 0 (evaluation only; ``~/so101_r2s_claude/table_test/REPORT.md``).
+
+The calibration of the real setup found the real table top lower than the sim table relative to the arm's kinematic
+frame (``calib_v1.json`` ``scene.table_plane``: z = c0 + c1 x + c2 y, m, arm base frame; 12-17 mm lower where the cubes
+are). Training always has the table top at z = 0. This module holds the plane arithmetic used by the CPU MuJoCo
+worlds (``mujoco_env``: the table geom on the plane), the task rules (``task.features``: heights above the plane), the
+action layer (``joint_env.floor_guard``: the floor on a plane) and the joint env (``JointVecEnv.set_table``: task starts
+moved onto the plane). numpy only (the MuJoCo workers import it without torch).
+
+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.
+Heights above the plane are measured along the plane normal n = (-c1, -c2, 1) / |(-c1, -c2, 1)|. A flat offset dz is
+the plane (dz, 0, 0).
+"""
+from __future__ import annotations
+
+import math
+
+import numpy as np
+
+
+def parse(dz=None, plane=None):
+ """CLI values -> plane tuple or None. ``dz`` float (m, negative = lower); ``plane`` "c0,c1,c2" or a sequence."""
+ if plane is not None and plane != "":
+ if isinstance(plane, str):
+ plane = [float(v) for v in plane.split(",")]
+ p = tuple(float(v) for v in plane)
+ if len(p) != 3:
+ raise ValueError(f"table plane needs 3 coefficients c0,c1,c2, got {plane!r}")
+ if dz:
+ p = (p[0] + float(dz), p[1], p[2])
+ elif dz:
+ p = (float(dz), 0.0, 0.0)
+ else:
+ return None
+ return None if not any(p) else p
+
+
+def is_flat(plane) -> bool:
+ return plane is None or (plane[1] == 0.0 and plane[2] == 0.0)
+
+
+def normal(plane):
+ """(unit normal n (3,), offset d) with n . p - d = signed height of p above the plane."""
+ c0, c1, c2 = (float(c) for c in plane)
+ s = math.sqrt(1.0 + c1 * c1 + c2 * c2)
+ return np.array([-c1 / s, -c2 / s, 1.0 / s]), c0 / s
+
+
+def height(plane, xy):
+ """Plane z at xy [..., 2] (vertical)."""
+ c0, c1, c2 = (float(c) for c in plane)
+ xy = np.asarray(xy, np.float64)
+ return c0 + c1 * xy[..., 0] + c2 * xy[..., 1]
+
+
+def above(plane, p):
+ """Signed height (along the normal) of points p [..., 3] above the plane."""
+ n, d = normal(plane)
+ return np.asarray(p, np.float64) @ n - d
+
+
+def tilt_quat(plane):
+ """Unit quaternion w x y z of the shortest turn e_z -> plane normal (identity for a flat plane)."""
+ n, _ = normal(plane)
+ q = np.array([1.0 + n[2], -n[1], n[0], 0.0])
+ return q / np.linalg.norm(q)
+
+
+def qmul(a, b):
+ """Quaternion product a b (w x y z), [..., 4]."""
+ a, b = np.asarray(a, np.float64), np.asarray(b, np.float64)
+ aw, ax, ay, az = np.moveaxis(a, -1, 0)
+ bw, bx, by, bz = np.moveaxis(b, -1, 0)
+ return np.stack((aw * bw - ax * bx - ay * by - az * bz, aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw), -1)
+
+
+def map_cube(plane, pos, quat):
+ """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:
+ xy kept, the centre at the same height along the plane normal (vertical offset height / n_z), the cube turned by
+ the plane's tilt (a cube flat on the sim table lies flat on the plane). pos [..., 3], quat [..., 4] (numpy)."""
+ pos, quat = np.asarray(pos, np.float64), np.asarray(quat, np.float64)
+ if plane is None:
+ return pos.copy(), quat.copy()
+ n, _ = normal(plane)
+ out = pos.copy()
+ out[..., 2] = height(plane, pos[..., :2]) + pos[..., 2] / n[2]
+ q = qmul(np.broadcast_to(tilt_quat(plane), quat.shape), quat)
+ return out, q
+
+
+def table_geom(plane, pos0, quat0=(1.0, 0.0, 0.0, 0.0)):
+ """Pose (pos (3,), quat w x y z) of the collector's table box (centre pos0, top at z = 0, axis-aligned) moved so
+ that its top face lies on the plane: the top centre at (x0, y0, plane(x0, y0)), the box turned by the tilt."""
+ pos0 = np.asarray(pos0, np.float64)
+ if plane is None:
+ return pos0.copy(), np.asarray(quat0, np.float64).copy()
+ n, _ = normal(plane)
+ half_t = -pos0[2] # the box centre is half its thickness below the top (z = 0)
+ top = np.array([pos0[0], pos0[1], float(height(plane, pos0[:2]))])
+ return top - n * half_t, qmul(tilt_quat(plane), np.asarray(quat0, np.float64))
+
+
+def describe(plane) -> str:
+ if plane is None:
+ return "sim table (z = 0)"
+ if is_flat(plane):
+ return f"flat table at z = {plane[0] * 1e3:+.1f} mm"
+ return f"table plane z = {plane[0]:+.5f} {plane[1]:+.5f} x {plane[2]:+.5f} y"
+
+
+def parse_floor(s):
+ """CLI floor value -> "zero" | "table" | float (a flat floor height, m, as the robot script's --table-z)."""
+ if s in (None, "", "zero"):
+ return "zero"
+ if s == "table":
+ return "table"
+ return float(s)
+
+
+def parse_q_offset_deg(s):
+ """ "a,b,c,d,e,f" (deg, sim joint order) -> list of 6 rad, or None."""
+ if not s:
+ return None
+ v = [math.radians(float(x)) for x in s.split(",")]
+ if len(v) != 6:
+ raise ValueError(f"q offset needs 6 values (deg), got {s!r}")
+ return v if any(v) else None
+
+
+def add_cli(q, student=False):
+ """The evaluation options of a lowered / tilted table (``vision_viral.py eval``, ``vision_viral_teacher.py eval``)."""
+ q.add_argument("--table-dz", type=float, default=0.0,
+ help="evaluation only: table top moved by this (m, negative = lower), flat; added to --table-plane")
+ q.add_argument("--table-plane", default="", help="evaluation only: table top on z = c0 + c1 x + c2 y ('c0,c1,c2')")
+ q.add_argument("--floor", default="zero",
+ help="action-layer table floor: 'zero' (z = 0, default, the robot's --table-z 0), 'table' (follows "
+ "the table), or a height in m (a flat floor there, the robot's --table-z)")
+ if student:
+ q.add_argument("--q-offset-deg", default="",
+ help="sim emulation of an extra joint-map offset (6 values, deg): the student's q input and "
+ "the action layer work in q + offset")
+ q.add_argument("--no-render-table", action="store_true",
+ help="with a moved table: render the images with the scene's own table (inconsistent images)")
+ q.add_argument("--log-only-extra", default="",
+ help="evaluation only: task failure rules that only log (comma list, e.g. 'unsupported,release_high' "
+ "= a cube released above the table may drop onto it)")
+
+
+def from_cli(a):
+ """-> (plane, floor, q_offset or None, active)."""
+ plane = parse(a.table_dz, a.table_plane or None)
+ floor = parse_floor(a.floor)
+ qo = parse_q_offset_deg(getattr(a, "q_offset_deg", ""))
+ return plane, floor, qo, plane is not None or floor != "zero" or qo is not None
+
+
+def log_only_extra(env, a):
+ """Add ``--log-only-extra`` rules to the env's task config (evaluation only) -> the tuple added."""
+ from nedm.so101_policy import task as T
+ extra = tuple(r for r in (getattr(a, "log_only_extra", "") or "").split(",") if r)
+ bad = [r for r in extra if r not in T.RULES]
+ if bad:
+ raise ValueError(f"unknown task rules {bad}")
+ if extra:
+ env.tcfg.log_only = tuple(env.tcfg.log_only) + extra
+ if env.task.cfg is not env.tcfg:
+ raise RuntimeError("task config is not the env's")
+ return extra
diff --git a/so101_pick_place/code/src/nedm/so101_policy/table_bias.py b/so101_pick_place/code/src/nedm/so101_policy/table_bias.py
new file mode 100644
index 0000000000000000000000000000000000000000..49c26c15081ccacfb8b37f56a7b7c05fb96cc19e
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/table_bias.py
@@ -0,0 +1,293 @@
+"""Table height / tilt randomisation of the camera student's JOINT INPUT (real2sim v8, 2026-10-23;
+``viral.OnlineConfig.table_bias``, off by default). Ported from the studentlab round C WIP (claude/so101-studentlab
+e8efd92ea, ``table_bias.py``), redone: an exact joint map of every pose instead of one fitted constant offset per
+episode, and a shear of the world instead of a rigid tilt (reasons below).
+
+Why (``~/so101_studentlab_claude/diag/release_ep05``): the robot student reads its descent / stop height from the
+JOINT input and the jaw-open decision from the WRIST image. The real table top is 12-17 mm lower than the sim table
+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
+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).
+The student stops where the sim cube would touch, the real cube stays ~13 mm above the plate, the wrist image never
+shows contact and the jaw stays shut. The training worlds (the learned simulator) have the table fixed at z = 0, so
+the table cannot move in the training physics; the student's JOINT READING moves instead.
+
+Model. A per-world table plane z = c0 + c1 x + c2 y (``table.py`` convention: m, arm base frame; c0 < 0 = lower than
+the sim table). For the true sim joints q the student reads
+
+ q_obs = Phi(q): FK_pos(q_obs) = FK_pos(q) + plane(FK_xy(q)) e_z, FK_rot(q_obs) = FK_rot(q)
+
+= the joints of a real arm whose gripper is at the same place relative to the world (table, cube, plate) when that
+world lies on the plane: under a lower table the reading is LOWER than the true gripper, so at a grasp the student's
+joints are the real joints that reach a cube that much lower (``test_table_bias.py`` checks this against an
+independent top-down IK). Only the three pitch joints change (shoulder_lift, elbow_flex, wrist_flex): their axes are
+parallel and horizontal and the pan axis is vertical, so they move the gripper in the arm's vertical plane and turn
+it only about their common axis; a vertical shift with the same gripper rotation is therefore exact (Gauss-Newton on
+those three joints, ``ITERS`` = 8 iterations). Convergence, measured on 147,001 logged REAL robot states (q_sim of
+``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
+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
+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
+default draws 0.002 % of the rows (a plane HIGHER than the sim table at far x) have no image (residual ~1 mm, true
+reach limit). Pan, wrist roll and the jaw are unchanged.
+
+A SHEAR, not a rigid tilt: horizontal positions are kept, only the height of the world under the gripper changes
+(the plane is evaluated at the grasp point's xy, so the offset follows the gripper over a tilted table). A rigid
+rotation of the world about some pivot (the WIP: about the shoulder) also moves the joint-implied gripper sideways by
+about tilt x (height above the pivot), ~4 mm at 2 deg, a lateral bias that the images contradict; the real cube's xy
+relative to the arm is whatever it is, only its height differs. A 2 deg tilt of the cube itself is ignored.
+
+Online loop (``viral.OnlineDAgger``): per world per episode with probability ``p`` a plane is drawn
+(``TableBiasConfig``: the drop at ``x_ref_m``, slopes in x and y). Everything the student sees or learns from the
+joints is in the observed frame, exactly (``viral.OnlineDAgger.table_frame``, one batched map per decision): its q
+input Phi(q) (+ the ``q_bias`` draw on top; history = earlier inputs), its qdot input J_Phi(q) qdot (``observe_qd``,
+analytic; exactly 0 stays 0), the cmd / last-command inputs Phi(executed targets) - Phi(q); the teacher's labels
+Phi(label) and the buffer's q Phi(q), so the training targets are Phi(label) - Phi(q); the student's chunk is relative
+to its reading, so the applied targets are Phi^-1(Phi(q) + delta) (``to_true``). Physics, the action layer, the
+teacher's observation and its executed targets stay true; images and aux targets too unless ``table_render`` (below).
+One constant offset per decision instead (b = Phi(q) - q for the chunk: applied q + delta, labels label - q) is
+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,
+``test_table_bias``), so the loop maps every pose; worlds without a plane are untouched bit for bit (``shift``
+returns q itself for dz = 0). Near the reach limit
+(arm almost straight) a pose may have no image: a target the student aims ~15 mm "higher" in the sim world than the
+sim arm can reach at that gripper rotation (real robot states: 5.3 % of them have no sim preimage under the
+calibrated plane, all at grasp-point reach >= 0.27 m; the training tasks' cubes and goals lie within 0.27 m).
+Training data are exact: a world whose frame-map rows (q, the image state, labels, last executed targets) are not
+all below ``EXACT`` adds no sample this decision (and a non-exact label does not complete the previous one).
+Acting only: rows above ``TOL`` take the decision's constant offset b(q) (labels / executed targets + b, applied
+targets - b); the loop logs the frame-map and applied-target shares separately (``tb_bad_frame``, ``tb_bad_applied``,
+``tb_skip``; ``viral.OnlineDAgger.log_extra``). Online smoke (S family, init s28, 64 worlds, 400 decisions, the
+consistent images): frame map 0 rows above TOL, 0 samples skipped; applied targets 0.35 % above TOL on average (2.6 %
+in the first 50 decisions, where every episode starts together and s28 reaches 0.30-0.32 m out at 7-17 cm height
+with the gripper pointing down; 0-0.13 % later).
+
+Images (``OnlineConfig.table_render``, off by default): with the plain option the training renders keep the TRUE
+arm and the sim-height world while the student reads Phi(q), a mismatch that never occurs on the robot (there the
+arm in the image IS the reading) and that tells the drop. ``table_render`` draws the arm at the reading (Phi of the
+image state, also with image lag) and the world on the plane (cube sheared by the plane height under it and tilted
+with the plane; plate, floor, mat, walls, strip, ceiling on the plane as ``RealScene.on_plane``; ``SO101Scene``
+``world_plane``), so the training images are the robot's images of a lower / tilted table; the aux cube target is
+then the drawn cube (z + plane height).
+
+Robot: the real joints ARE the observed frame (no offset at deploy). The robot's action-layer floor must follow the
+real table: training keeps the floor 1.5 mm above the TRUE table, i.e. above the plane in the observed frame; the
+robot's ``run_student_real.py --table-z 0`` (default) keeps the lowest gripper point 1.5 mm above z = 0 of the ARM
+frame, ~13 mm above the real table at the cubes, and holds a lower descent up. Deploy a table-trained student with
+``--table-plane calib`` (``hw_lib.ActionLayer(table_plane=)``: the floor and the guard's floor checks above the
+calibrated plane; MuJoCo: ``vision_viral.py eval --floor table``), never with ``--table-z 0``. The robot script does
+this by itself (2026-10-24): ``run_student_real.py --floor-mode auto`` (default) reads ``v8_online.table_bias`` from
+the checkpoint (``hw_lib.student_floor_mode``), and live mode refuses a flat floor for such a student.
+
+Round v12 (2026-10-26, off by default): ``TableBiasConfig.plane`` = one fixed plane in every world (no draw) and
+``viral.OnlineConfig.student_floor`` "observed" = the online env's floor flat in the OBSERVED frame (the robot's flat
+arm-frame floor; in the true frame raised by -plane at the grasp point, ``joint_env.JointEnvConfig.floor_raise``), so
+the student deploys with the robot's flat floor (``hw_lib.student_floor_mode``: v8_online.student_floor observed ->
+flat) and the labelling teacher is the one fine-tuned with the same floor raise.
+"""
+from __future__ import annotations
+
+import math
+from dataclasses import asdict, dataclass
+
+import torch
+
+PITCH = (1, 2, 3) # shoulder_lift, elbow_flex, wrist_flex (sim joint order)
+ITERS = 8 # Gauss-Newton iterations (module docstring: < 2e-16 m on all real robot states; 4 was
+ # not enough at far reach: up to 2 mm)
+W_ROT = 0.1 # m / rad: rotation weight of the fit (the collector's IK weight)
+STEP_MAX = 0.3 # rad: largest change of a joint in one iteration (a guard near the reach limit)
+EXACT = 1e-9 # m (+ 0.1 m / rad): a map row at or below this residual is exact (training data)
+TOL = 5e-4 # m (+ 0.1 m / rad): a map row above this residual has no image (acting: ``viral``
+ # fallback to the decision's constant offset)
+
+
+@dataclass
+class TableBiasConfig:
+ """Per world per episode with probability ``p`` a table plane, else the sim table (b = 0):
+ the table top at x = ``x_ref_m`` (y = 0) ``drop_mm`` ~ U(lo, hi) mm BELOW the sim table (positive = lower), its
+ 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
+ ``slope_y`` (real +18.4; off by default). Plane c = (-drop - slope_x x_ref, slope_x, slope_y) (m, ``table.py``).
+
+ ``plane`` (real2sim round v12, 2026-10-26; () = off): ONE fixed plane (c0, c1, c2) (m, ``table.py``) for every
+ world and episode, no random draw (``sample`` uses no random numbers); ``p`` must then be 1 (the default with a
+ plane) and the ranges must not be given. (0, 0, 0) is allowed: every world on the sim table, the frame map the
+ identity (``shift`` returns q itself)."""
+ p: float = 0.7
+ drop_mm: tuple = (0.0, 20.0)
+ slope_x: tuple = (-40.0, 40.0)
+ slope_y: tuple = (0.0, 0.0)
+ x_ref_m: float = 0.25
+ plane: tuple = ()
+
+ RANGES = ("drop_mm", "slope_x", "slope_y")
+
+ @staticmethod
+ def from_dict(d) -> "TableBiasConfig":
+ d = dict(d or {})
+ bad = sorted(set(d) - set(TableBiasConfig.__dataclass_fields__) - {"note"})
+ if bad:
+ raise ValueError(f"unknown table_bias keys {bad}")
+ d.pop("note", None)
+ pl = d.get("plane")
+ if pl is not None and not (isinstance(pl, (list, tuple)) and len(pl) == 0): # one fixed plane (docstring)
+ if not isinstance(pl, (list, tuple)) or len(pl) != 3 or \
+ any(isinstance(v, bool) or not isinstance(v, (int, float)) for v in pl):
+ raise ValueError(f"table_bias plane {pl!r}: 3 numbers (c0, c1, c2), m")
+ pl = tuple(float(v) + 0.0 for v in pl)
+ 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:
+ raise ValueError(f"table_bias plane {list(pl)}: finite, |c0| <= 0.06 m, |c1|, |c2| <= 0.2 (m per m)")
+ given = sorted(k for k in TableBiasConfig.RANGES if k in d)
+ if given:
+ raise ValueError(f"table_bias plane with {given}: a fixed plane has no ranges")
+ if float(d.get("p", 1.0)) != 1.0:
+ raise ValueError(f"table_bias plane with p {d['p']}: a fixed plane is in every world (p 1)")
+ d["plane"], d["p"] = pl, 1.0
+ else:
+ d.pop("plane", None)
+ for k in TableBiasConfig.RANGES:
+ if k in d:
+ v = tuple(float(x) for x in d[k])
+ if len(v) != 2 or not v[0] <= v[1] or not all(math.isfinite(x) for x in v):
+ raise ValueError(f"table_bias {k} {list(d[k])}: (lo, hi) with lo <= hi")
+ d[k] = v
+ c = TableBiasConfig(**d)
+ if not 0.0 <= float(c.p) <= 1.0:
+ raise ValueError(f"table_bias p {c.p}: a probability in [0, 1]")
+ if max(abs(v) for v in c.drop_mm) > 60.0 or max(abs(v) for k in ("slope_x", "slope_y")
+ for v in getattr(c, k)) > 200.0:
+ raise ValueError(f"table_bias {c.to_dict()}: drop beyond 60 mm or slope beyond 200 mm/m (units: mm, "
+ "mm per m)")
+ return c
+
+ def to_dict(self) -> dict:
+ d = {k: (list(v) if isinstance(v, tuple) else v) for k, v in asdict(self).items()}
+ if not self.plane: # off: the old record
+ d.pop("plane")
+ else: # a fixed plane: no ranges (unused)
+ for k in self.RANGES:
+ d.pop(k)
+ return d
+
+
+def plane_coef(drop_m, slope_x, slope_y, x_ref):
+ """Drop (m, positive = lower) at (x_ref, 0) and slopes (m / m) -> plane coefficients [..., 3] (c0, c1, c2)."""
+ drop_m = torch.as_tensor(drop_m)
+ sx = torch.as_tensor(slope_x, dtype=drop_m.dtype, device=drop_m.device)
+ sy = torch.as_tensor(slope_y, dtype=drop_m.dtype, device=drop_m.device)
+ return torch.stack(torch.broadcast_tensors(-drop_m - sx * float(x_ref), sx, sy), -1)
+
+
+def sample(n, cfg: TableBiasConfig, gen=None, device="cpu"):
+ """n per-world draws -> (plane [n, 3] float64 (zeros where off), on [n] bool). Random numbers (one call each, on
+ ``gen``): on, drop, slope_x, slope_y. A fixed ``cfg.plane``: that plane in every row, on everywhere, no random
+ numbers."""
+ if cfg.plane:
+ pl = torch.tensor(cfg.plane, dtype=torch.float64, device=device)
+ return pl.expand(n, 3).clone(), torch.ones(n, dtype=torch.bool, device=device)
+ f = dict(device=device, generator=gen, dtype=torch.float64)
+ on = torch.rand(n, **f) < float(cfg.p)
+
+ def u(lo_hi, scale):
+ lo, hi = (float(v) * scale for v in lo_hi)
+ return lo + (hi - lo) * torch.rand(n, **f)
+
+ drop, sx, sy = u(cfg.drop_mm, 1e-3), u(cfg.slope_x, 1e-3), u(cfg.slope_y, 1e-3)
+ plane = plane_coef(drop, sx, sy, cfg.x_ref_m)
+ return torch.where(on[:, None], plane, torch.zeros_like(plane)), on
+
+
+def height(plane, xy):
+ """Plane z [...] at xy [..., 2] (torch; plane [..., 3] or [3])."""
+ plane = torch.as_tensor(plane, dtype=xy.dtype, device=xy.device)
+ return plane[..., 0] + plane[..., 1] * xy[..., 0] + plane[..., 2] * xy[..., 1]
+
+
+def shift(kin, q, dz, iters=ITERS, w_rot=W_ROT):
+ """Joints that move the grasp point of poses q [B, 6] by dz [B] (m) along world z with the gripper rotation
+ unchanged: Gauss-Newton on the pitch joints (``PITCH``) from q (pan, roll, jaw kept); the iterate with the lowest
+ residual is returned (q itself included), so where it does not converge (near a straight arm, far outside the
+ task poses) the shift degrades to a partial one (residual <= |dz|) instead of a diverged pose. -> (q' [B, 6] in
+ q's dtype, residual [B]: |position error| (m) + w_rot |rotation error| (rad) of exact FK). Rows with dz = 0 (and
+ rows with a non-finite q or dz) return q itself, bit for bit, residual 0."""
+ from nedm.so101_policy.kin import rotvec_fast
+ dt = q.dtype
+ dz = torch.as_tensor(dz, dtype=kin.dtype, device=q.device).expand(q.shape[0])
+ keep = (dz == 0) | ~torch.isfinite(dz) | ~torch.isfinite(q).all(-1)
+ x = torch.where(keep[:, None], torch.zeros_like(q), q).to(kin.dtype)
+ dz = torch.where(keep, torch.zeros_like(dz), dz)
+ p0, r0 = kin.fk(x)
+ tgt = p0 + torch.stack((torch.zeros_like(dz), torch.zeros_like(dz), dz), -1)
+
+ def resid(y):
+ p, r = kin.fk(y)
+ e = (tgt - p).norm(dim=-1) + w_rot * rotvec_fast(r0 @ r.transpose(-1, -2)).norm(dim=-1)
+ return torch.where(torch.isfinite(e), e, torch.full_like(e, math.inf))
+
+ def step(y, d):
+ return torch.cat((y[:, :1], y[:, 1:4] + d, y[:, 4:]), -1)
+
+ J = list(PITCH)
+ eye = torch.eye(len(J), dtype=kin.dtype, device=x.device)
+ best, err = x, dz.abs() # q itself: residual |dz|
+ for _ in range(int(iters)):
+ jp, jr, p, r = kin.jacobian(x)
+ a = torch.cat((jp[..., J], w_rot * jr[..., J]), -2) # [B, 6, 3]
+ rhs = torch.cat((tgt - p, w_rot * rotvec_fast(r0 @ r.transpose(-1, -2))), -1)[..., None]
+ at = a.transpose(-1, -2)
+ dx = torch.linalg.solve_ex(at @ a + 1e-12 * eye, at @ rhs, check_errors=False)[0][..., 0]
+ dx = torch.where(torch.isfinite(dx), dx, torch.zeros_like(dx)).clamp(-STEP_MAX, STEP_MAX)
+ x = step(x, dx)
+ e = resid(x)
+ better = e < err # keep the best iterate
+ best, err = torch.where(better[:, None], x, best), torch.where(better, e, err)
+ return torch.where(keep[:, None], q, best.to(dt)), torch.where(keep, torch.zeros_like(err), err)
+
+
+def observe(kin, q, plane):
+ """The student's reading q_obs = Phi(q) of true poses q [B, 6] in worlds whose table lies on ``plane`` [B, 3]
+ (module docstring): the grasp point moved by the plane height under it, same rotation. -> (q_obs, residual)."""
+ p, _ = kin.fk(q.to(kin.dtype))
+ return shift(kin, q, height(torch.as_tensor(plane, dtype=kin.dtype, device=p.device), p[..., :2]))
+
+
+def to_true(kin, u_obs, plane):
+ """Exact inverse of ``observe``: the true joints whose reading is u_obs [B, 6] (a vertical shift keeps xy, so the
+ plane is evaluated at FK_xy(u_obs)). -> (u, residual): the applied targets of the online loop."""
+ p, _ = kin.fk(u_obs.to(kin.dtype))
+ return shift(kin, u_obs, -height(torch.as_tensor(plane, dtype=kin.dtype, device=p.device), p[..., :2]))
+
+
+def observe_qd(kin, q, qd, plane, q_obs=None):
+ """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
+ derivative of the map's definition, module docstring): Phi keeps pan, roll and the jaw, so their rates stay; the
+ pitch rates d [B, 3] solve (least squares with the map's rotation weight; the system is consistent, so exact where
+ ``q_obs`` = Phi(q) is)
+
+ 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
+ J_r,pitch(Phi(q)) d = J_r(q) qd - J_r,other(Phi(q)) qd_other
+
+ (grasp-point velocity plus the plane's slope under the moving gripper; the gripper's angular velocity unchanged).
+ ``q_obs``: Phi(q) if known (else computed). qd = 0 gives exactly 0. float64."""
+ q, qd = q.to(kin.dtype), qd.to(kin.dtype)
+ n = q.shape[0]
+ pl = torch.as_tensor(plane, dtype=kin.dtype, device=q.device).expand(n, 3)
+ if q_obs is None:
+ q_obs = observe(kin, q, pl)[0]
+ jp, jr, _, _ = kin.jacobian(q)
+ jpo, jro, _, _ = kin.jacobian(q_obs.to(kin.dtype))
+ J, O = list(PITCH), [0, 4] # pitch joints, the other arm joints (pan, roll)
+ v = (jp @ qd[:, :5, None])[..., 0] # grasp-point velocity [B, 3]
+ w = (jr @ qd[:, :5, None])[..., 0] # gripper angular velocity [B, 3]
+ vz = pl[:, 1] * v[:, 0] + pl[:, 2] * v[:, 1] # the plane height's rate under the gripper
+ v = v + torch.stack((torch.zeros_like(vz), torch.zeros_like(vz), vz), -1)
+ qo = qd[:, O, None]
+ a = torch.cat((jpo[..., J], W_ROT * jro[..., J]), -2) # [B, 6, 3]
+ rhs = torch.cat((v - (jpo[..., O] @ qo)[..., 0], W_ROT * (w - (jro[..., O] @ qo)[..., 0])), -1)[..., None]
+ at = a.transpose(-1, -2)
+ eye = torch.eye(len(J), dtype=kin.dtype, device=q.device)
+ d = torch.linalg.solve_ex(at @ a + 1e-15 * eye, at @ rhs, check_errors=False)[0][..., 0]
+ out = torch.cat((qd[:, :1], d, qd[:, 4:]), -1)
+ return torch.where((qd == 0).all(-1, keepdim=True), torch.zeros_like(out), out)
+
+
+def is_on(d) -> bool:
+ """``OnlineConfig.table_bias`` dict -> on? (empty or only a ``note``: off)."""
+ return bool(set(dict(d or {})) - {"note"})
diff --git a/so101_pick_place/code/src/nedm/so101_policy/task.py b/so101_pick_place/code/src/nedm/so101_policy/task.py
new file mode 100644
index 0000000000000000000000000000000000000000..67f773be32c7e3cdf2a6d913478d5ed8694fde07
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/task.py
@@ -0,0 +1,1117 @@
+"""Goal-conditioned pick-and-place task of the SO101 + cube policy study: goals, geometric success / failure / validity
+rules, observation and reward (spec_v1 2.6 as changed by spec_v2 B2; rules of review_spec_feasibility sec. 4,
+P0-5..8, P1-11, P1-13, P1-14). Every rule is a pure function of the ``WorldState`` (true state), the decoder's macro
+phase and the kinematics (``kin.SO101Kin`` + ``TaskGeometry``), batched torch, the same code on CPU and GPU. No rule,
+reward or observation reads a contact switch (``WorldState.contact`` is never used).
+
+Frames and units: world = arm base frame (z up, table top z = 0), m, rad, s. Grasp frame = the gripper body frame moved
+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
+cube below the TCP has z < 0); ``cube_in_grasp`` = the collector's ``Scene.cube_in_gripper``. Cube tilt = angle of
+the most vertical cube axis from the world z; cube yaw = yaw of a side axis after the smallest rotation that makes the
+cube flat, mod 90 deg (``cube_yaw_tilt``; both exactly invariant under the 24 cube rotations, so the same with and
+without the NRD's canonical relabelling).
+
+Task (one episode, HORIZON 400 steps of 20 ms = 8 s): start = a resting cube and an arm pose (``load_start_bank``: the
+first recorded states of task-family episodes; tests use fresh collector starts, spec_v2 B4); goal = cube centre
+(x, y) on the workspace annulus (r 0.15-0.27 m about the pan axis, angle +-75 deg, the collector's ``sample_cube``
+rule), 6-30 cm from the start, goal yaw = start yaw + U(-30, 30) deg (mod 90), clipped so that the total cube turn
+from the grasp stays <= 0.6 rad (``sample_goals``; the C3-b goal change passes the turn made so far).
+
+Per step (``PickPlaceTask.step``) the rules below run in this order; the first that fires sets the end code
+(``ENDS``). Thresholds: ``TaskConfig`` (calibrated on validation records by ``scripts/so101_policy/calibrate_rules.py``,
+values and false-fire / detection table in ~/so101_policy/docs/build2_task.md).
+
+| End code | Rule (state after the step) |
+|---|---|
+| world_invalid / world_arm_table | the world's own flags (NRD: non-finite, cube off the table, guard; MuJoCo: real ends) |
+| lowest_point | lowest point of all arm collision geoms (the collector's ``Scene.lowest`` set) < ``lowest_min`` |
+| link_overlap | a non-jaw link collision box overlaps the cube by > ``link_depth`` (exact box-box separating-axis depth) |
+| 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) |
+| base_zone | the cube enters the bounding cylinder of the arm base |
+| 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 |
+| keep_out | outside a macro, TCP z < ``keep_out_z`` while within ``keep_out_r`` (xy) of a resting cube |
+| release_high | the cube is not held and its lowest corner is > ``release_z`` above the table while falling (v_z <= ``fall_vz``) |
+| unsupported | same, not falling, for ``unsupported_steps`` steps (phantom support: the NRD exploit "cube on one jaw / near-miss lift") |
+| hold_cap | held in the air (held and lowest corner > ``air_z``) for more than ``hold_cap_s`` in one run |
+| 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 |
+| cube_tilted | the cube on the table, not held, tilt > ``tilt_fail`` for ``tilt_steps`` steps |
+| 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) |
+| 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 |
+| 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 |
+| timeout | t = horizon (truncation; bootstrap) |
+
+"Held" = cube centre inside the held box of the grasp frame and the jaw angle inside the firm-grip band. "On the table" =
+lowest cube corner < ``table_z``.
+
+Reward (P1-14): progress shaping, not exp(-D). Potential phi = -(w_reach d_reach (until the first firm lift; frozen during
+a GRASP macro) + w_goal d_goal), d_reach = |TCP xy - cube xy| + |TCP z - (cube z + pre_h)| + k_yaw |grasp yaw error|,
+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 =
+phi' - phi + lift bonus (once) + success bonus - time cost; a failure end adds -fail and the discounted time cost of the
+remaining steps (charge_remaining). Success ends the episode; timeout is a truncation.
+
+Observation (``observation``, the same function for every world, no contact flags, P1-11): q, qd, TCP position, gripper
+rotation (2 columns), cube position, sin / cos of 4 x cube yaw, cube tilt, cube v and w (optional, ``obs_rates``), cube in
+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,
+lifted flag, held-in-air time / cap, one-hot macro phase, and the decoder's own state vector (``dec_obs``).
+
+Macro phases (decoder v2 contract, spec_v2 B1): ``MACROS``; a decoder without macros passes ``macro=None`` (all free;
+the grasp-box rule then fires at a geometric close start: the jaw closing through ``close_jaw`` with the cube within
+4 cm of the TCP).
+"""
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from pathlib import Path
+
+import torch
+
+from nedm.so101_policy.kin import BODIES, GRIPPER, PAN_AXIS_XY, SO101Kin, quat_mat, wrap, yaw_of
+from nedm.so101_policy.world import CONTROL_DT, WorldState
+
+CUBE_HALF = 0.015
+CUBE_REST_Z = 0.014993 # resting cube centre height in the data (m)
+QUARTER = math.pi / 2
+HORIZON = 400
+SELF_RULE_DEFAULT = True # review F1 / F9 rules (calibration: ~/so101_policy/docs/build3_fixes.md)
+GHOST_RULE_DEFAULT = True
+ANNULUS_R = (0.15, 0.27) # m about the pan axis (collector sample_cube)
+ANNULUS_DEG = (-75.0, 75.0)
+GOAL_DIST = (0.06, 0.30) # m from the start cube centre
+GOAL_TURN_DEG = 30.0
+MAX_TURN = 0.6 # rad, total cube (= gripper) yaw turn from the grasp
+TASK_FAMILIES = tuple(range(7)) # nominal .. push: the task-family starts of the grasp data
+MACROS = ("free", "grasp_descend", "grasp_close", "grasp_grip", "grasp_lift", "place_lower", "place_open",
+ "place_retreat")
+MC = {n: k for k, n in enumerate(MACROS)}
+GRASP_MACROS = (1, 2, 3, 4)
+PLACE_MACROS = (5, 6, 7)
+# collector phases (so101_grasp.PHASES) -> macro codes, for calibration on recorded data
+COLLECTOR_MACRO = {"descend": "grasp_descend", "close": "grasp_close", "grip": "grasp_grip", "lift": "grasp_lift",
+ "lower": "place_lower", "release": "place_open", "retreat": "place_retreat"}
+ENDS = ("running", "success", "timeout", "world_invalid", "world_arm_table", "lowest_point", "link_overlap",
+ "jaw_overlap", "base_zone", "grasp_box", "keep_out", "release_high", "unsupported", "hold_cap", "cube_slide",
+ "cube_tilted", "arm_self", "moved_untouched") # last two: review F1, F9 (appended: old codes keep values)
+EC = {n: k for k, n in enumerate(ENDS)}
+RULES = ENDS[3:]
+
+
+@dataclass
+class TaskConfig:
+ """Thresholds (m, rad, s). Values marked [cal] come from the validation calibration (build2_task.md)."""
+ horizon: int = HORIZON
+ # success
+ tol_xy: float = 0.015
+ tol_yaw: float = math.radians(15.0)
+ tol2_xy: float = 0.010 # secondary success level, reported only
+ tol2_yaw: float = math.radians(10.0)
+ rest_speed: float = 0.005 # m/s, |cube_v|
+ flat_tilt: float = math.radians(5.0)
+ open_jaw: float = 0.4 # rad
+ tcp_clear: float = 0.03 # TCP above the cube top
+ lift_z: float = 0.02 # firm lift: lowest corner (m) ...
+ lift_steps: int = 10 # ... held for 0.2 s
+ # geometry of the grasp [cal]
+ box_x: float = 0.0055 # grasp box at the GRASP trigger / close start: |x| (closing axis)
+ box_y: float = 0.0125 # |y| (jaw width)
+ box_z: tuple = (-0.0125, 0.0015) # z of the cube centre in the grasp frame (cube below the TCP: z < 0)
+ box_yaw: float = math.radians(4.0) # |gripper yaw - cube face yaw| (mod 90) at the trigger (tilted gripper) [cal]
+ close_yaw: float = math.radians(3.0) # ... at the close start (top-down gripper) [cal]
+ held_x: float = 0.012 # held box (hold, carry): |x| (MuJoCo grips <= 5.4 mm; the NRD's held
+ # cube drifts along the closing axis in carries: 7 mm ends 9.8 % of
+ # nominal NRD replays, 12 mm 0.9 %), |y|, z range [cal]
+ held_y: float = 0.015 # off-centre grips reach 14.6 mm, near misses start at 15 mm
+ held_z: tuple = (-0.015, 0.005)
+ firm_jaw: tuple = (0.13, 0.185) # rad, jaw angle band of a firm grip [cal]
+ close_jaw: float = 0.35 # rad, geometric close start without macros
+ # failure rules [cal]
+ lowest_min: float = 0.0 # m, lowest arm collision point
+ link_depth: float = 0.0 # m (any overlap; nominal / off-centre max -30 mm) [cal]
+ jaw_depth: float = 0.0002 # m; the collector ends at 1 mm of its measure, ours reads lower (no
+ # cube-points-in-mesh test): 0.2 mm detects 97.8 % of its ends [cal]
+ keep_out_z: float = 0.04 # TCP height (m) ...
+ keep_out_r: float = 0.05 # ... within this xy distance of a resting cube
+ table_z: float = 0.002 # lowest cube corner below this = on the table
+ release_z: float = 0.005
+ fall_vz: float = -0.2 # m/s
+ unsupported_steps: int = 2
+ air_z: float = 0.002
+ hold_cap_s: float = 3.5
+ slide_v: float = 0.03 # m/s
+ slide_grace_s: float = 0.3
+ slide_steps: int = 2
+ tilt_fail: float = math.radians(15.0)
+ tilt_steps: int = 10
+ self_rule: bool = SELF_RULE_DEFAULT # arm self-contact (review F1): TaskGeometry.self_depth > -self_margin
+ self_margin: float = 0.0002 # m [cal]: 18 / 19 MuJoCo arm_self ends of the v2 gate (46 / 49 all
+ # configs) at their end state, 0 of 10,360 MuJoCo successes, 0 validation
+ # records
+ ghost_rule: bool = GHOST_RULE_DEFAULT # cube moved on the table with no gripper / jaw point near it (review F9)
+ touch_d: float = 0.02 # m, gripper / jaw collision geoms within this of the cube = near
+ # (TaskGeometry.jaw_clearance) [cal]
+ ghost_d: float = 0.002 # m, cube centre moved in xy since the last near / held / airborne step
+ # [cal]
+ ghost_dz: float = 0.003 # m, or in z (the NRD lifts a resting cube by up to 1.8 mm in the first
+ # step after a reset, then puts it back; sunk cubes: 4-7 mm) [cal]
+ ghost_yaw: float = math.radians(5.0) # rad, or its yaw (mod 90) turned [cal]
+ log_only: tuple = () # rule names that only log (MuJoCo evaluation: ("grasp_box",))
+ # reward (P1-14)
+ w_reach: float = 10.0 # per m
+ w_goal: float = 10.0 # per m
+ k_yaw: float = 0.05 # m per rad
+ pre_h: float = 0.05 # m, reach target height above the cube centre
+ sat_xy: float = 0.005
+ sat_yaw: float = math.radians(5.0)
+ lift_bonus: float = 1.0
+ success_bonus: float = 5.0
+ fail_cost: float = 2.0
+ time_cost: float = 0.002 # per step; charged for the remaining steps at a failure end
+ gamma: float = 0.99 # discount of the remaining-step charge
+ # observation
+ obs_rates: bool = True # cube v, w in the observation (P1-11 ablation: False)
+
+ @staticmethod
+ def evaluation(**kw) -> "TaskConfig":
+ """MuJoCo evaluation: the grasp-box rule only logs (spec_v2 B2)."""
+ return TaskConfig(log_only=("grasp_box",), **kw)
+
+
+# ---- small geometry helpers ----------------------------------------------------------------------------------------
+def wrap90(a):
+ """Angle -> (-45, 45] deg equivalent under the cube's 90 deg symmetry."""
+ return -(torch.remainder(-a + QUARTER / 2, QUARTER) - QUARTER / 2)
+
+
+def cube_yaw_tilt(quat):
+ """Cube orientation (w x y z) [B, 4] -> (yaw mod 90 deg in [0, pi/2), tilt rad). The cube axis nearest the world
+ vertical is 'up' (sign: pointing up); tilt = its angle from the vertical; the cube is turned flat by the smallest
+ rotation taking 'up' to the vertical, and yaw = the yaw of a side axis then (exactly the same for all 24
+ relabellings of the cube's symmetry, also when tilted)."""
+ r = quat_mat(quat)
+ zr = r[:, 2, :] # world z of the 3 cube axes
+ up = zr.abs().argmax(-1)
+ u = r.gather(-1, up[:, None, None].expand(-1, 3, 1))[..., 0]
+ u = u * torch.where(u[:, 2:] < 0, -1.0, 1.0)
+ tilt = torch.acos(u[:, 2].clamp(max=1.0))
+ side = torch.remainder(up + 1, 3)
+ sv = r.gather(-1, side[:, None, None].expand(-1, 3, 1))[..., 0]
+ # R = I + [w]x + [w]x^2 / (1 + c), w = u x e_z, c = u_z (> 0.57): R u = e_z
+ w = torch.stack((u[:, 1], -u[:, 0], torch.zeros_like(u[:, 0])), -1)
+ wx = torch.cross(w, sv, dim=-1)
+ flat = sv + wx + torch.cross(w, wx, dim=-1) / (1 + u[:, 2:])
+ return torch.remainder(torch.atan2(flat[:, 1], flat[:, 0]), QUARTER), tilt
+
+
+def cube_bottom(pos, rot, half=CUBE_HALF):
+ """Lowest cube corner z [B] (m) of a cube at pos [B, 3] with rotation rot [B, 3, 3]."""
+ return pos[:, 2] - half * rot[:, 2, :].abs().sum(-1)
+
+
+def mm3(a, b):
+ """a @ b for small matrices [..., 3, 3] by broadcasting (no batched GEMM launch)."""
+ return (a[..., :, :, None] * b[..., None, :, :]).sum(-2)
+
+
+def mv3(a, v):
+ """a @ v [..., 3]."""
+ return (a * v[..., None, :]).sum(-1)
+
+
+def mtv3(a, v):
+ """a^T @ v [..., 3]."""
+ return (a * v[..., :, None]).sum(-2)
+
+
+def box_sdf(p, half):
+ """Signed distance [...] of points p [..., 3] (cube frame) to an axis-aligned box of half size ``half`` (< 0 inside)."""
+ q = p.abs() - half
+ return q.clamp_min(0).norm(dim=-1) + q.amax(-1).clamp_max(0)
+
+
+def sat_depth(c1, r1, h1, c2, r2, h2):
+ """Exact overlap depth of two boxes by the separating-axis test (15 axes; the classic OBB form in the frame of box
+ 1): centres c [..., 3], rotations r [..., 3, 3] (columns = box axes), half sizes h [..., 3] -> [...] (m; > 0 =
+ overlap by that depth, <= 0 = separated)."""
+ R = mm3(r1.transpose(-1, -2), r2) # box-2 axes in the box-1 frame
+ t = mtv3(r1, c2 - c1)
+ A = R.abs()
+ ov = [h1 + (A * h2[..., None, :]).sum(-1) - t.abs(), # axes of box 1
+ (A * h1[..., :, None]).sum(-2) + h2 - (t[..., :, None] * R).sum(-2).abs()] # axes of box 2
+ i1, i2 = torch.tensor([1, 2, 0]), torch.tensor([2, 0, 1]) # (i + 1) % 3, (i + 2) % 3
+ # 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];
+ # d = |t[i2] R[i1, j] - t[i1] R[i2, j]|; length sqrt(1 - R[i, j]^2)
+ ra = h1[..., i1, None] * A[..., i2, :] + h1[..., i2, None] * A[..., i1, :]
+ rb = h2[..., None, i1] * A[..., :, i2] + h2[..., None, i2] * A[..., :, i1]
+ d = (t[..., i2, None] * R[..., i1, :] - t[..., i1, None] * R[..., i2, :]).abs()
+ n = (1 - R * R).clamp_min(0).sqrt()
+ ov.append(torch.where(n > 1e-6, (ra + rb - d) / n.clamp_min(1e-6), torch.full_like(n, math.inf)).flatten(-2))
+ return torch.cat(ov, -1).amin(-1)
+
+
+# ---- arm geometry from the collector scene --------------------------------------------------------------------------
+class TaskGeometry:
+ """Collision and visual geometry of the collector's SO101 for the kinematic rules (body frames of ``kin.BODIES``).
+
+ - ``low_*``: points and radii of the collector's arm collision geoms (``Scene.arm_geoms``: gripper, moving jaw and
+ link geoms, shoulder excluded) -> lowest point (``Scene.lowest``).
+ - ``link_*``: the non-jaw link collision boxes (classes LINK incl. the shoulder and the camera mount; all are boxes).
+ - per jaw body (gripper = fixed jaw, moving jaw): collision boxes, round geoms (spheres / capsules as segments + radius)
+ and convex-hull vertices of collision meshes; visual mesh surface points (vertices + points ``spacing`` apart on
+ large triangles, one per ``cell``), as the collector's ``VisualOverlap`` builds them.
+ - base cylinder (radius, top z) bounding the base collision hulls.
+ Built from MuJoCo (``from_mujoco``, needs mujoco + the vendor Menagerie model) or loaded from ``save``'s .npz."""
+
+ JAWS = ("gripper", "moving_jaw_so101_v1")
+
+ def __init__(self, arrays: dict, device="cpu", dtype=torch.float64):
+ self.arrays = arrays
+ f = dict(device=torch.device(device), dtype=dtype)
+ t = lambda k: torch.as_tensor(arrays[k], **f) # noqa: E731
+ li = lambda k: torch.as_tensor(arrays[k], dtype=torch.long, device=f["device"]) # noqa: E731
+ self.device, self.dtype = f["device"], dtype
+ self.low_body, self.low_pts, self.low_rad = li("low_body"), t("low_pts"), t("low_rad")
+ self.low_groups = [(int(b), self.low_pts[self.low_body == b], self.low_rad[self.low_body == b])
+ for b in torch.unique(self.low_body).tolist()]
+ self.link_body, self.link_pos, self.link_rot, self.link_half = (li("link_body"), t("link_pos"), t("link_rot"),
+ t("link_half"))
+ self.jaw = []
+ for j in range(2):
+ p = f"jaw{j}_"
+ self.jaw.append(dict(
+ body=BODIES.index(self.JAWS[j]),
+ box_pos=t(p + "box_pos"), box_rot=t(p + "box_rot"), box_half=t(p + "box_half"),
+ seg_a=t(p + "seg_a"), seg_b=t(p + "seg_b"), seg_r=t(p + "seg_r"),
+ hull=t(p + "hull"), vis=t(p + "vis"),
+ vis32=torch.as_tensor(arrays[p + "vis"], dtype=torch.float32, device=f["device"])))
+ w = torch.linspace(0, 1, 5, **f)[:, None, None] # 5 points per segment
+ J = self.jaw[-1]
+ J["seg5"] = (J["seg_a"] * (1 - w) + J["seg_b"] * w).reshape(-1, 3)
+ J["seg5_r"] = J["seg_r"].repeat(5)
+ self.base_r, self.base_z = float(arrays["base_r"]), float(arrays["base_z"])
+ if "self_pairs" not in arrays: # a geometry file written before the self-contact rule (review F1)
+ arrays.update(_self_arrays_cached())
+ self.self_body, self.self_pos = li("self_body"), t("self_pos")
+ self.self_rot, self.self_half = t("self_rot"), t("self_half")
+ self.self_pairs = li("self_pairs")
+ self.self_hull_body, self.self_hull = li("self_hull_body"), t("self_hull")
+ self.self_hull_planes, self.self_hull_pairs = t("self_hull_planes"), li("self_hull_pairs")
+
+ @staticmethod
+ def build_self_arrays(scene=None, samples=20000, reach=0.01, seed=0) -> dict:
+ """Arm self-contact geometry (review F1; the collector's ``Scene.clearance`` self test = MuJoCo contacts of kind
+ 'arm self' at a joint state): the collision BOXES of the arm links, the gripper (with the camera mount) and the
+ moving jaw in their body frames, and every box pair of different bodies that MuJoCo's body filter lets
+ collide (same weld body, parent-child weld bodies and the model's excludes are skipped, as in
+ mj_collision); plus the pairs of a box with a non-base convex hull (gripper_collision1, moving-jaw hulls).
+ Only pairs that come within ``reach`` of each other (MuJoCo distance) in ``samples`` random joint states
+ (uniform in the applied target range, numpy seed ``seed``) are kept: the others cannot touch. Not included:
+ the base hulls and the jaw tip spheres / capsule (none came within 5 mm of another arm geom in the 1.57 M gate
+ and data states of ~/so101_policy/docs/build3_fixes.md)."""
+ import mujoco
+ import numpy as np
+
+ from nedm.contact_nrd.collect import so101_grasp as g
+ s = scene or g.Scene(g.load_config())
+ m = s.m
+ kidx = {m.body(n).id: k for k, n in enumerate(BODIES)}
+ sig = {(int(x) >> 16, int(x) & 0xFFFF) for x in m.exclude_signature[: m.nexclude]}
+ dsbl = bool(m.opt.disableflags & mujoco.mjtDisableBit.mjDSBL_FILTERPARENT)
+
+ def filtered(b1, b2): # mj_collision's body-pair filter
+ w1, w2 = m.body_weldid[b1], m.body_weldid[b2]
+ if w1 == w2:
+ return True
+ p1, p2 = m.body_weldid[m.body_parentid[w1]], m.body_weldid[m.body_parentid[w2]]
+ if not dsbl and w1 != 0 and w2 != 0 and (w1 == p2 or w2 == p1):
+ return True
+ return (b1, b2) in sig or (b2, b1) in sig
+
+ def geom_rot(gid):
+ r = np.zeros(9)
+ mujoco.mju_quat2Mat(r, m.geom_quat[gid])
+ return r.reshape(3, 3)
+
+ arm = [gid for gid in range(m.ngeom) if s.cls[gid] in (g.LINK, g.FIXED, g.MOVING)]
+ boxes = [gid for gid in arm if m.geom_type[gid] == mujoco.mjtGeom.mjGEOM_BOX]
+ hulls = [gid for gid in arm if m.geom_type[gid] == mujoco.mjtGeom.mjGEOM_MESH]
+ def ok(a, b): # an arm-self pair that mj_collision would test
+ return (s.kind[s.cls[a], s.cls[b]] == 5 and not filtered(m.geom_bodyid[a], m.geom_bodyid[b])
+ and bool(m.geom_contype[a] & m.geom_conaffinity[b] or m.geom_contype[b] & m.geom_conaffinity[a]))
+ # pairs that can come within reach (sampled with MuJoCo on a copy of the model with that margin)
+ near = set()
+ if samples:
+ from nedm.so101_policy.kin import THI, TLO
+ mm = s.m.__copy__()
+ mm.geom_margin[np.isin(s.cls, (g.LINK, g.FIXED, g.MOVING))] = reach
+ dd = mujoco.MjData(mm)
+ q = np.asarray(TLO) + (np.asarray(THI) - np.asarray(TLO)) * np.random.default_rng(seed).random((samples, 6))
+ for qq in q:
+ dd.qpos[:6] = qq
+ mujoco.mj_kinematics(mm, dd)
+ mujoco.mj_collision(mm, dd)
+ for k in range(dd.ncon):
+ a, b = int(dd.contact.geom1[k]), int(dd.contact.geom2[k])
+ near.add((min(a, b), max(a, b)))
+ close = lambda a, b: not samples or (min(a, b), max(a, b)) in near # noqa: E731
+ pairs = [(i, j) for i in range(len(boxes)) for j in range(i + 1, len(boxes))
+ if ok(boxes[i], boxes[j]) and close(boxes[i], boxes[j])]
+ hv, hp, hb, hpairs = [], [], [], []
+ for k, gid in enumerate(hulls):
+ mi = m.geom_dataid[gid]
+ a = m.mesh_graphadr[mi]
+ nv, nf = m.mesh_graph[a], m.mesh_graph[a + 1]
+ ids = m.mesh_graph[a + 2 + nv: a + 2 + 2 * nv]
+ faces = m.mesh_graph[a + 2 + 3 * nv + 3 * nf: a + 2 + 3 * nv + 6 * nf].reshape(nf, 3)
+ R, P = geom_rot(gid), m.geom_pos[gid]
+ mv = m.mesh_vert[m.mesh_vertadr[mi]: m.mesh_vertadr[mi] + m.mesh_vertnum[mi]].astype(float) @ R.T + P
+ v = mv[ids]
+ n = np.cross(mv[faces[:, 1]] - mv[faces[:, 0]], mv[faces[:, 2]] - mv[faces[:, 0]])
+ n /= np.linalg.norm(n, axis=1, keepdims=True).clip(1e-30)
+ d = -(n * mv[faces[:, 0]]).sum(1)
+ flip = (v.mean(0) @ n.T + d) > 0
+ n[flip], d[flip] = -n[flip], -d[flip]
+ hv.append(v), hp.append(np.concatenate((n, d[:, None]), 1)), hb.append(kidx[m.geom_bodyid[gid]])
+ hpairs += [(k, i) for i, b in enumerate(boxes) if ok(gid, b) and close(gid, b)]
+ V, F = max(len(x) for x in hv), max(len(x) for x in hp)
+ pad = lambda x, n: np.concatenate((x, np.repeat(x[:1], n - len(x), 0))) # noqa: E731
+ return dict(self_body=np.array([kidx[m.geom_bodyid[gid]] for gid in boxes]),
+ self_pos=np.array([m.geom_pos[gid] for gid in boxes]),
+ self_rot=np.array([geom_rot(gid) for gid in boxes]),
+ self_half=np.array([m.geom_size[gid] for gid in boxes]),
+ self_names=np.array([m.geom(gid).name for gid in boxes]),
+ self_pairs=np.array(pairs, np.int64).reshape(-1, 2),
+ self_hull_body=np.array(hb), self_hull=np.stack([pad(x, V) for x in hv]),
+ self_hull_planes=np.stack([pad(x, F) for x in hp]),
+ self_hull_names=np.array([m.geom(gid).name for gid in hulls]),
+ self_hull_pairs=np.array(hpairs, np.int64).reshape(-1, 2))
+
+ @staticmethod
+ def build_arrays(spacing=0.002, cell=0.002) -> dict:
+ import mujoco
+ import numpy as np
+
+ from nedm.contact_nrd.collect import so101_grasp as g
+ s = g.Scene(g.load_config())
+ m = s.m
+ kidx = {m.body(n).id: k for k, n in enumerate(BODIES)}
+
+ def geom_rot(gid):
+ r = np.zeros(9)
+ mujoco.mju_quat2Mat(r, m.geom_quat[gid])
+ return r.reshape(3, 3)
+
+ out = {}
+ # lowest point: Scene.arm_geoms / Scene.points in body frames
+ lb, lp, lr = [], [], []
+ for gid, (p, rad) in zip(s.arm_geoms, s.points):
+ pts = p @ geom_rot(gid).T + m.geom_pos[gid]
+ lb += [kidx[m.geom_bodyid[gid]]] * len(pts)
+ lp.append(pts)
+ lr += [rad] * len(pts)
+ out.update(low_body=np.array(lb), low_pts=np.concatenate(lp), low_rad=np.array(lr))
+ # link boxes
+ link = [gid for gid in range(m.ngeom) if s.cls[gid] == g.LINK]
+ if any(m.geom_type[gid] != mujoco.mjtGeom.mjGEOM_BOX for gid in link):
+ raise ValueError("expected boxes only for the non-jaw link collision geoms")
+ out.update(link_body=np.array([kidx[m.geom_bodyid[gid]] for gid in link]),
+ link_pos=np.array([m.geom_pos[gid] for gid in link]),
+ link_rot=np.array([geom_rot(gid) for gid in link]),
+ link_half=np.array([m.geom_size[gid] for gid in link]),
+ link_names=np.array([m.geom(gid).name for gid in link]))
+ # jaw bodies
+ for j, name in enumerate(TaskGeometry.JAWS):
+ b = m.body(name).id
+ cls = g.FIXED if j == 0 else g.MOVING
+ boxes, segs, hull = [], [], []
+ for gid in np.flatnonzero((m.geom_bodyid == b) & (s.cls == cls)):
+ t, size, R, P = int(m.geom_type[gid]), m.geom_size[gid], geom_rot(gid), m.geom_pos[gid]
+ if t == mujoco.mjtGeom.mjGEOM_BOX:
+ boxes.append((P, R, size.copy()))
+ elif t == mujoco.mjtGeom.mjGEOM_SPHERE:
+ segs.append((P, P, size[0]))
+ elif t == mujoco.mjtGeom.mjGEOM_CAPSULE:
+ segs.append((P - R[:, 2] * size[1], P + R[:, 2] * size[1], size[0]))
+ elif t == mujoco.mjtGeom.mjGEOM_MESH:
+ k = m.geom_dataid[gid]
+ a = m.mesh_graphadr[k]
+ if a < 0:
+ raise ValueError(f"collision mesh {m.geom(gid).name} has no convex hull graph")
+ nv, nf = m.mesh_graph[a], m.mesh_graph[a + 1]
+ ids = m.mesh_graph[a + 2 + nv: a + 2 + 2 * nv] # vert_globalid
+ fo = a + 2 + 3 * nv + 3 * nf # face_globalid
+ faces = m.mesh_graph[fo: fo + 3 * nf].reshape(nf, 3)
+ mv = m.mesh_vert[m.mesh_vertadr[k]: m.mesh_vertadr[k] + m.mesh_vertnum[k]].astype(float) @ R.T + P
+ v = mv[ids]
+ n = np.cross(mv[faces[:, 1]] - mv[faces[:, 0]], mv[faces[:, 2]] - mv[faces[:, 0]])
+ n /= np.linalg.norm(n, axis=1, keepdims=True).clip(1e-30)
+ d = -(n * mv[faces[:, 0]]).sum(1)
+ flip = (v.mean(0) @ n.T + d) > 0 # outward normals: centroid inside
+ n[flip], d[flip] = -n[flip], -d[flip]
+ hull.append((v, np.concatenate((n, d[:, None]), 1)))
+ else:
+ raise ValueError(f"geom type {t}")
+ out[f"jaw{j}_box_pos"] = np.array([x[0] for x in boxes]).reshape(-1, 3)
+ out[f"jaw{j}_box_rot"] = np.array([x[1] for x in boxes]).reshape(-1, 3, 3)
+ out[f"jaw{j}_box_half"] = np.array([x[2] for x in boxes]).reshape(-1, 3)
+ out[f"jaw{j}_seg_a"] = np.array([x[0] for x in segs]).reshape(-1, 3)
+ out[f"jaw{j}_seg_b"] = np.array([x[1] for x in segs]).reshape(-1, 3)
+ out[f"jaw{j}_seg_r"] = np.array([x[2] for x in segs]).reshape(-1)
+ out[f"jaw{j}_hull"] = np.concatenate([h[0] for h in hull]).reshape(-1, 3) if hull else np.zeros((0, 3))
+ vis = [gid for gid in np.flatnonzero(m.geom_bodyid == b)
+ if m.geom_type[gid] == mujoco.mjtGeom.mjGEOM_MESH and not (m.geom_contype[gid] or m.geom_conaffinity[gid])]
+ pts = g.surface_points(np.concatenate([g.mesh_triangles(m, gid) for gid in vis]), spacing)
+ _, keep = np.unique(np.floor(pts / cell).astype(np.int64), axis=0, return_index=True)
+ pts = pts[np.sort(keep)]
+ # a visual point inside a collision geom of its body can never be deeper in the cube than that geom's
+ # penetration (a ball of radius e around it lies inside the geom): such points cannot fire, drop them
+ inside = np.zeros(len(pts), bool)
+ for P, R, h in boxes:
+ inside |= (np.abs((pts - P) @ R) <= h).all(1)
+ for a_, b_, r in segs:
+ ab = b_ - a_
+ u = np.clip(((pts - a_) @ ab) / max(float(ab @ ab), 1e-30), 0, 1)
+ inside |= np.linalg.norm(pts - (a_ + u[:, None] * ab), axis=1) <= r
+ for _, planes in hull:
+ inside |= (pts @ planes[:, :3].T + planes[:, 3] <= 0).all(1)
+ out[f"jaw{j}_vis"] = pts[~inside]
+ out[f"jaw{j}_vis_all"] = np.int64(len(pts))
+ # base cylinder
+ bv = []
+ for gid in np.flatnonzero(s.cls == g.BASE):
+ k = m.geom_dataid[gid]
+ v = m.mesh_vert[m.mesh_vertadr[k]: m.mesh_vertadr[k] + m.mesh_vertnum[k]].astype(float)
+ bv.append(v @ geom_rot(gid).T + m.geom_pos[gid])
+ bv = np.concatenate(bv) # base body = world
+ out.update(base_r=np.float64(np.linalg.norm(bv[:, :2], axis=1).max()), base_z=np.float64(bv[:, 2].max()),
+ spacing=np.float64(spacing), cell=np.float64(cell))
+ out.update(TaskGeometry.build_self_arrays(s))
+ return out
+
+ @classmethod
+ def from_mujoco(cls, device="cpu", dtype=torch.float64, spacing=0.002, cell=0.002):
+ key = (spacing, cell)
+ if key not in _GEOM_CACHE:
+ _GEOM_CACHE[key] = cls.build_arrays(spacing, cell)
+ return cls(_GEOM_CACHE[key], device, dtype)
+
+ @classmethod
+ def load(cls, path, device="cpu", dtype=torch.float64):
+ import numpy as np
+ f = np.load(path)
+ return cls({k: f[k] for k in f.files}, device, dtype)
+
+ @classmethod
+ def default(cls, device="cpu", dtype=torch.float64, path=None):
+ """From ``path`` if it exists, else from MuJoCo (and written to ``path`` when given)."""
+ if path is not None and Path(path).exists():
+ return cls.load(path, device, dtype)
+ geom = cls.from_mujoco(device, dtype)
+ if path is not None:
+ geom.save(path)
+ return geom
+
+ def save(self, path):
+ import numpy as np
+ np.savez(path, **self.arrays)
+
+ # -- per-state measures (bpos [B, 8, 3], brot [B, 8, 3, 3] = kin.body_poses; c [B, 3], rc [B, 3, 3] = the cube) --
+ def lowest(self, bpos, brot, plane=None):
+ """Lowest world z [B] of the arm collision geoms (Scene.lowest), per body one matrix product. ``plane``
+ (c0, c1, c2): the lowest signed height above the plane z = c0 + c1 x + c2 y instead (``table.py``)."""
+ if plane is not None:
+ from nedm.so101_policy import table as TB
+ n_np, off = TB.normal(plane)
+ nv = torch.as_tensor(n_np, dtype=bpos.dtype, device=bpos.device)
+ z = []
+ for b, p, r in self.low_groups:
+ u = torch.einsum("k,bkj->bj", nv, brot[:, b])
+ z.append((bpos[:, b] @ nv - off)[:, None] + u @ p.T.to(u) - r)
+ return torch.stack([v.amin(-1) for v in z], -1).amin(-1)
+ 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]
+ - r).amin(-1) for b, p, r in self.low_groups]
+ return torch.stack(z, -1).amin(-1)
+
+ def link_depth(self, bpos, brot, c, rc):
+ """Deepest overlap [B] (m) of a non-jaw link collision box with the cube (> 0 = overlap)."""
+ R = brot[:, self.link_body] # [B, G, 3, 3]
+ pc = bpos[:, self.link_body] + mv3(R, self.link_pos)
+ h = torch.full_like(self.link_half, CUBE_HALF)
+ d = sat_depth(c[:, None], rc[:, None], h, pc, mm3(R, self.link_rot), self.link_half)
+ return d.amax(-1)
+
+ def jaw_depths(self, bpos, brot, c, rc, chunk=4096):
+ """Per jaw body (gripper, moving jaw) -> (visual depth [B, 2], collision depth [B, 2]) (m): the deepest visual
+ mesh point inside the cube, and the deepest penetration of that body's collision geoms into the cube (boxes:
+ separating-axis depth; spheres / capsules: radius minus the signed distance of 5 points of the segment; hull
+ meshes: the deepest hull vertex)."""
+ B = c.shape[0]
+ vis, col = torch.empty(B, 2, dtype=c.dtype, device=c.device), torch.empty(B, 2, dtype=c.dtype, device=c.device)
+ half = torch.full((3,), CUBE_HALF, dtype=c.dtype, device=c.device)
+ for j, J in enumerate(self.jaw):
+ Rb, pb = brot[:, J["body"]], bpos[:, J["body"]]
+ M = mm3(rc.transpose(-1, -2), Rb) # body -> cube frame
+ t = mtv3(rc, pb - c)
+ v32, M32, t32 = J["vis32"], M.float(), t.float()
+ for s in range(0, B, chunk):
+ m_, t_ = M32[s: s + chunk, None], t32[s: s + chunk, None] # [b, 1, 3, 3], [b, 1, 3]
+ inf = None
+ for a in range(3): # L-inf norm in the cube frame
+ pa = (t_[..., a] + v32[:, 0] * m_[..., a, 0] + v32[:, 1] * m_[..., a, 1]
+ + v32[:, 2] * m_[..., a, 2]).abs()
+ inf = pa if inf is None else torch.maximum(inf, pa)
+ vis[s: s + chunk, j] = CUBE_HALF - inf.amin(-1).to(c.dtype) # the deepest point
+ parts = []
+ for pts, rad in ((J["hull"], None), (J["seg5"], J["seg5_r"])):
+ if len(pts):
+ p = mv3(M[:, None], pts) + t[:, None]
+ parts.append(((0 if rad is None else rad) - box_sdf(p, half)).amax(-1))
+ if len(J["box_half"]):
+ parts.append(sat_depth(c[:, None], rc[:, None], half, pb[:, None] + mv3(Rb[:, None], J["box_pos"]),
+ mm3(Rb[:, None], J["box_rot"]), J["box_half"]).amax(-1))
+ col[:, j] = torch.stack(parts, -1).amax(-1)
+ return vis, col
+
+ def jaw_clearance(self, bpos, brot, c, rc):
+ """Smallest clearance [B] (m) between the cube and the collision geoms of the gripper (with the fixed jaw) and
+ the moving jaw: minus the deepest penetration of ``jaw_depths``' collision part (boxes: separating-axis gap, a
+ lower bound of the distance; hull vertices and sphere / capsule points: their distance to the cube box)."""
+ half = torch.full((3,), CUBE_HALF, dtype=c.dtype, device=c.device)
+ out = []
+ for J in self.jaw:
+ Rb, pb = brot[:, J["body"]], bpos[:, J["body"]]
+ M = mm3(rc.transpose(-1, -2), Rb)
+ t = mtv3(rc, pb - c)
+ for pts, rad in ((J["hull"], None), (J["seg5"], J["seg5_r"])):
+ if len(pts):
+ sdf = box_sdf(mv3(M[:, None], pts) + t[:, None], half)
+ out.append((sdf - (0 if rad is None else rad)).amin(-1))
+ if len(J["box_half"]):
+ out.append(-sat_depth(c[:, None], rc[:, None], half, pb[:, None] + mv3(Rb[:, None], J["box_pos"]),
+ mm3(Rb[:, None], J["box_rot"]), J["box_half"]).amax(-1))
+ return torch.stack(out, -1).amin(-1)
+
+ def jaw_overlap(self, bpos, brot, c, rc, chunk=4096):
+ """The collector's VisualOverlap measure [B] (m): max over the 2 jaw bodies of the visual depth minus the
+ body's collision penetration (if > 0), at least 0."""
+ vis, col = self.jaw_depths(bpos, brot, c, rc, chunk)
+ return (vis - col.clamp_min(0)).amax(-1).clamp_min(0)
+
+ def self_depth(self, bpos, brot, cap=0.005):
+ """Deepest arm self-overlap [B] (m; > 0 = two arm collision geoms overlap, <= 0 = separated): exact
+ separating-axis depth of every box pair (``build_self_arrays``), and for a box against a convex hull the
+ deepest vertex of either inside the other (vertex-face only: an edge-edge crossing reads as separated). Pairs
+ whose bounding spheres are more than ``cap`` apart are not tested (they read minus that gap)."""
+ B = bpos.shape[0]
+ G = brot[:, self.self_body] # [B, G, 3, 3]
+ cw = bpos[:, self.self_body] + mv3(G, self.self_pos) # box centres, world
+ i, j = self.self_pairs[:, 0], self.self_pairs[:, 1]
+ rad = self.self_half.norm(dim=-1)
+ gap = (cw[:, i] - cw[:, j]).norm(dim=-1) - rad[i] - rad[j] # [B, P] sphere gap
+ far = lambda x: torch.where(x >= cap, -x, torch.full_like(x, -math.inf)) # noqa: E731
+ best = far(gap).amax(-1) if gap.shape[1] else torch.full((B,), -math.inf, dtype=bpos.dtype, device=bpos.device)
+ w, k = (gap < cap).nonzero(as_tuple=True)
+ if len(w):
+ rw = mm3(G[w[:, None], torch.stack((i[k], j[k]), -1)], self.self_rot[torch.stack((i[k], j[k]), -1)])
+ 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]])
+ best = best.scatter_reduce(0, w, d, reduce="amax")
+ if len(self.self_hull_pairs):
+ hk, bk = self.self_hull_pairs[:, 0], self.self_hull_pairs[:, 1]
+ hb = self.self_hull_body[hk]
+ hc = self.self_hull.mean(1) # hull centre, body frame
+ hr = (self.self_hull - hc[:, None]).norm(dim=-1).amax(-1)
+ Rh, Ph = brot[:, hb], bpos[:, hb] # [B, H, 3, 3], [B, H, 3]
+ hcw = Ph + mv3(Rh, hc[hk])
+ gap = (hcw - cw[:, bk]).norm(dim=-1) - hr[hk] - rad[bk]
+ best = torch.maximum(best, far(gap).amax(-1))
+ w, k = (gap < cap).nonzero(as_tuple=True)
+ if len(w):
+ Rk, Pk = Rh[w, k], Ph[w, k] # [n, 3, 3], [n, 3]
+ vw = Pk[:, None] + mv3(Rk[:, None], self.self_hull[hk[k]]) # hull vertices, world [n, V, 3]
+ bb = bk[k]
+ rb = mm3(G[w, bb], self.self_rot[bb])
+ cb, hh = cw[w, bb], self.self_half[bb]
+ dv = (-box_sdf(mtv3(rb[:, None], vw - cb[:, None]), hh[:, None])).amax(-1) # hull vertex in the box
+ sg = torch.tensor([-1.0, 1.0], dtype=bpos.dtype, device=bpos.device)
+ corner = torch.stack(torch.meshgrid(sg, sg, sg, indexing="ij"), -1).reshape(8, 3)
+ cl = mtv3(Rk[:, None], cb[:, None] + mv3(rb[:, None], corner * hh[:, None]) - Pk[:, None]) # [n, 8, 3]
+ pl = self.self_hull_planes[hk[k]] # [n, F, 4]
+ dc = (-(torch.einsum("nkc,nfc->nkf", cl, pl[..., :3]) + pl[:, None, :, 3]).amax(-1)).amax(-1)
+ best = best.scatter_reduce(0, w, torch.maximum(dv, dc), reduce="amax")
+ return best
+
+ def in_base_zone(self, c, bottom):
+ """The cube's bounding circle enters the base cylinder [B] bool."""
+ return (c[:, :2].norm(dim=-1) - CUBE_HALF * math.sqrt(2) < self.base_r) & (bottom < self.base_z)
+
+
+_GEOM_CACHE: dict = {}
+_SELF_CACHE: dict = {}
+
+
+def _self_arrays_cached() -> dict:
+ """``TaskGeometry.build_self_arrays`` once per process (needs mujoco and the vendor SO101 model)."""
+ if not _SELF_CACHE:
+ try:
+ _SELF_CACHE.update(TaskGeometry.build_self_arrays())
+ except ImportError as e:
+ raise ImportError("this TaskGeometry file has no self-contact arrays (review F1) and mujoco is not "
+ "importable to build them: use a geometry file written by TaskGeometry.save after "
+ "2026-10-11 21:00 (e.g. ~/so101_policy/ckpt/task_geom_v2.npz)") from e
+ return _SELF_CACHE
+
+
+# ---- per-step features (pure functions of the state) ---------------------------------------------------------------
+def features(state: WorldState, kin: SO101Kin, geom: TaskGeometry | None, cfg: TaskConfig, overlap=True,
+ plane=None) -> dict:
+ """Geometric quantities of one batch of states used by every rule, the reward and the observation (float64).
+ ``plane`` (c0, c1, c2): the table top is the plane z = c0 + c1 x + c2 y (``table.py``, evaluation of a lowered
+ table): ``bottom`` (on the table, lift, release, air) and ``lowest`` (arm lowest point) are heights above the plane
+ (along its normal); the base zone keeps the world bottom; the observation is unchanged (world = arm frame)."""
+ f64 = dict(dtype=kin.dtype)
+ q = state.q.to(**f64)
+ c = state.cube_pos.to(**f64)
+ quat = state.cube_quat.to(**f64)
+ quat = quat / quat.norm(dim=-1, keepdim=True)
+ rc = quat_mat(quat)
+ if geom is not None:
+ bpos, brot = kin.body_poses(q)
+ rg = brot[:, GRIPPER]
+ tcp = bpos[:, GRIPPER] + mv3(rg, kin.point)
+ else:
+ tcp, rg = kin.fk(q)
+ xg = mtv3(rg, c - tcp) # cube centre in the grasp frame
+ gyaw = yaw_of(rg)
+ cyaw, tilt = cube_yaw_tilt(quat)
+ bottom = cube_bottom(c, rc)
+ bottom_w = bottom
+ if plane is not None: # lowest cube corner above the plane, along its normal
+ from nedm.so101_policy import table as TB
+ n_np, off = TB.normal(plane)
+ nv = torch.as_tensor(n_np, **f64, device=c.device)
+ bottom = c @ nv - off - CUBE_HALF * torch.einsum("k,bkj->bj", nv, rc).abs().sum(-1)
+ v = state.cube_v.to(**f64)
+ jaw = q[:, 5]
+ near_jaws = ((xg[:, 0].abs() <= cfg.held_x) & (xg[:, 1].abs() <= cfg.held_y) & (xg[:, 2] >= cfg.held_z[0])
+ & (xg[:, 2] <= cfg.held_z[1]))
+ firm = (jaw >= cfg.firm_jaw[0]) & (jaw <= cfg.firm_jaw[1])
+ in_box = ((xg[:, 0].abs() <= cfg.box_x) & (xg[:, 1].abs() <= cfg.box_y) & (xg[:, 2] >= cfg.box_z[0])
+ & (xg[:, 2] <= cfg.box_z[1]))
+ # horizontal offset of the cube from the TCP in the gripper yaw frame (trigger box; the descent is vertical)
+ d = c[:, :2] - tcp[:, :2]
+ cy, sy = torch.cos(gyaw), torch.sin(gyaw)
+ hx, hy = cy * d[:, 0] + sy * d[:, 1], -sy * d[:, 0] + cy * d[:, 1]
+ 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,
+ v=v, w=state.cube_w.to(**f64), speed=v.norm(dim=-1), vxy=v[:, :2].norm(dim=-1), jaw=jaw,
+ held=near_jaws & firm, near_jaws=near_jaws, in_box=in_box, firm=firm, hx=hx, hy=hy, dxy=d.norm(dim=-1),
+ yaw_mis=wrap90(gyaw - cyaw).abs(), on_table=bottom < cfg.table_z,
+ finite=torch.isfinite(q).all(-1) & torch.isfinite(c).all(-1) & torch.isfinite(quat).all(-1))
+ if geom is not None:
+ out["lowest"] = geom.lowest(bpos, brot) if plane is None else geom.lowest(bpos, brot, plane)
+ out["base_zone"] = geom.in_base_zone(c, bottom_w)
+ if cfg.self_rule:
+ out["self_depth"] = geom.self_depth(bpos, brot)
+ if cfg.ghost_rule and not overlap:
+ out["touch"] = geom.jaw_clearance(bpos, brot, c, rc)
+ if overlap:
+ out["link_depth"] = geom.link_depth(bpos, brot, c, rc)
+ vis, col = geom.jaw_depths(bpos, brot, c, rc) # (= jaw_overlap, jaw_clearance)
+ out["jaw_overlap"] = (vis - col.clamp_min(0)).amax(-1).clamp_min(0)
+ if cfg.ghost_rule:
+ out["touch"] = -col.amax(-1)
+ return out
+
+
+def goal_errors(F, goal_xy, goal_yaw):
+ """(xy error [B] m, yaw error [B] rad mod 90) of the cube against the goal."""
+ return (F["c"][:, :2] - goal_xy).norm(dim=-1), wrap90(F["cyaw"] - goal_yaw).abs()
+
+
+def trigger_box_ok(F, cfg: TaskConfig):
+ """Grasp box at the GRASP trigger: horizontal offset in the gripper yaw frame and yaw misalignment [B] bool."""
+ return (F["hx"].abs() <= cfg.box_x) & (F["hy"].abs() <= cfg.box_y) & (F["yaw_mis"] <= cfg.box_yaw)
+
+
+def goal_box_ok(F, cfg: TaskConfig, macro_goal):
+ """Grasp box at the GRASP trigger against the decoder's planned descent end macro_goal [B, 4] (TCP x, y, z, yaw):
+ cube centre in that pose's yaw frame within the box (x, y, z) and its yaw within ``close_yaw`` of the cube's
+ (the commanded yaw is not tilted) [B] bool."""
+ g = macro_goal.to(F["c"])
+ d = F["c"] - g[:, :3]
+ cy, sy = torch.cos(g[:, 3]), torch.sin(g[:, 3])
+ x, y = cy * d[:, 0] + sy * d[:, 1], -sy * d[:, 0] + cy * d[:, 1]
+ return ((x.abs() <= cfg.box_x) & (y.abs() <= cfg.box_y) & (d[:, 2] >= cfg.box_z[0]) & (d[:, 2] <= cfg.box_z[1])
+ & (wrap90(g[:, 3] - F["cyaw"]).abs() <= cfg.close_yaw))
+
+
+def close_box_ok(F, cfg: TaskConfig):
+ """Grasp box at the close start: cube centre in the grasp frame and yaw misalignment [B] bool."""
+ return F["in_box"] & (F["yaw_mis"] <= cfg.close_yaw)
+
+
+def keep_out(F, cfg: TaskConfig, free):
+ """Outside a macro (free [B] bool), TCP below keep_out_z within keep_out_r (xy) of a resting cube [B] bool."""
+ resting = F["on_table"] & ~F["held"]
+ return free & resting & (F["dxy"] < cfg.keep_out_r) & (F["tcp"][:, 2] < cfg.keep_out_z)
+
+
+def success_now(F, cfg: TaskConfig, goal_xy, goal_yaw, lifted, tol_xy=None, tol_yaw=None):
+ """Geometric success [B] bool (spec_v2 B2)."""
+ ex, ey = goal_errors(F, goal_xy, goal_yaw)
+ tol_xy = cfg.tol_xy if tol_xy is None else tol_xy
+ tol_yaw = cfg.tol_yaw if tol_yaw is None else tol_yaw
+ return (lifted & ~F["held"] & F["on_table"] & (F["tilt"] <= cfg.flat_tilt) & (F["speed"] < cfg.rest_speed)
+ & (ex <= tol_xy) & (ey <= tol_yaw) & (F["jaw"] >= cfg.open_jaw)
+ & (F["tcp"][:, 2] >= F["c"][:, 2] + CUBE_HALF + cfg.tcp_clear))
+
+
+def potential(F, cfg: TaskConfig, goal_xy, goal_yaw):
+ """(d_reach [B], d_goal [B]) of the progress shaping (m)."""
+ ex, ey = goal_errors(F, goal_xy, goal_yaw)
+ d_goal = ex.clamp_min(cfg.sat_xy) + cfg.k_yaw * ey.clamp_min(cfg.sat_yaw)
+ d_reach = (F["dxy"] + (F["tcp"][:, 2] - (F["c"][:, 2] + cfg.pre_h)).abs() + cfg.k_yaw * F["yaw_mis"])
+ return d_reach, d_goal
+
+
+# ---- the task ------------------------------------------------------------------------------------------------------
+@dataclass
+class Tracker:
+ """Per-world episode state of the task (tensors [B])."""
+ t: torch.Tensor
+ lifted: torch.Tensor # a firm lift happened
+ lift_run: torch.Tensor # consecutive steps held with the lowest corner >= lift_z
+ air_run: torch.Tensor # consecutive steps held in the air
+ unsup_run: torch.Tensor
+ tilt_run: torch.Tensor
+ slide_run: torch.Tensor
+ since_release: torch.Tensor # steps since the cube was last held (large = never)
+ prev_held: torch.Tensor
+ prev_macro: torch.Tensor
+ d_reach: torch.Tensor
+ d_goal: torch.Tensor
+ end: torch.Tensor # ENDS code (0 running)
+ box_log: torch.Tensor # a grasp-box violation was logged (log_only)
+ anchor_xy: torch.Tensor # cube centre / yaw at the last step the gripper or jaw was near it (or it was held
+ anchor_yaw: torch.Tensor # or off the table): the moved_untouched rule (anchor_xy [B, 3]: x, y, z)
+ success10: torch.Tensor # latched at the end: the secondary success level (10 mm / 10 deg) also held
+ end_xy: torch.Tensor # latched at the end: xy error (m) and yaw error (rad) of the cube to the goal
+ end_yaw: torch.Tensor
+
+
+class PickPlaceTask:
+ """Batched task state over B worlds on one device. ``reset(idx, state, goal_xy, goal_yaw)``;
+ ``step(state, macro=None) -> (reward [B], terminated [B], truncated [B], info)`` for every world (worlds that have
+ already ended keep their end code until reset; their reward is 0); ``observation(state, dec_obs, macro)``."""
+
+ def __init__(self, num_envs, device="cpu", kin: SO101Kin | None = None, geom: TaskGeometry | None = None,
+ cfg: TaskConfig | None = None, overlap_rules=True):
+ self.B, self.dev = int(num_envs), torch.device(device)
+ self.cfg = cfg or TaskConfig()
+ self.kin = kin or SO101Kin(self.dev)
+ self.geom = geom if geom is not None else TaskGeometry.from_mujoco(self.dev, self.kin.dtype)
+ self.overlap_rules = overlap_rules
+ f, li = dict(dtype=self.kin.dtype, device=self.dev), dict(dtype=torch.long, device=self.dev)
+ self.goal_xy = torch.zeros(self.B, 2, **f)
+ self.goal_yaw = torch.zeros(self.B, **f)
+ z = lambda **k: torch.zeros(self.B, **k) # noqa: E731
+ self.tr = Tracker(t=z(**li), lifted=z(dtype=torch.bool, device=self.dev), lift_run=z(**li), air_run=z(**li),
+ unsup_run=z(**li), tilt_run=z(**li), slide_run=z(**li), since_release=z(**li) + 10 ** 6,
+ prev_held=z(dtype=torch.bool, device=self.dev), prev_macro=z(**li), d_reach=z(**f),
+ d_goal=z(**f), end=z(**li), box_log=z(dtype=torch.bool, device=self.dev),
+ anchor_xy=torch.zeros(self.B, 3, **f), anchor_yaw=z(**f),
+ success10=z(dtype=torch.bool, device=self.dev), end_xy=z(**f) + math.nan,
+ end_yaw=z(**f) + math.nan)
+ self.prev_jaw = torch.zeros(self.B, **f) # jaw angle of the last step (geometric close start)
+ self.grasp_yaw = torch.zeros(self.B, **f) # cube yaw at the first firm lift (continuous reference)
+ self.turned = torch.zeros(self.B, **f) # cube yaw turned since the first firm lift (rad)
+ self.F = None
+ self.table_plane = None # (c0, c1, c2): the table top is that plane (``features``; evaluation only)
+
+ # -- episode control --
+ def reset(self, idx, state: WorldState, goal_xy, goal_yaw):
+ """Worlds idx (long [n] or bool [B]) start: state = their start states (WorldState [n]), goals [n, 2], [n]."""
+ F = features(state, self.kin, None, self.cfg)
+ gx = torch.as_tensor(goal_xy, dtype=self.kin.dtype, device=self.dev)
+ gy = torch.as_tensor(goal_yaw, dtype=self.kin.dtype, device=self.dev)
+ self.goal_xy[idx], self.goal_yaw[idx] = gx, gy
+ dr, dg = potential(F, self.cfg, gx, gy)
+ tr = self.tr
+ for k in ("t", "lift_run", "air_run", "unsup_run", "tilt_run", "slide_run", "prev_macro", "end"):
+ getattr(tr, k)[idx] = 0
+ for k in ("lifted", "prev_held", "box_log", "success10"):
+ getattr(tr, k)[idx] = False
+ tr.end_xy[idx], tr.end_yaw[idx] = math.nan, math.nan
+ tr.since_release[idx] = 10 ** 6
+ tr.d_reach[idx], tr.d_goal[idx] = dr, dg
+ tr.anchor_xy[idx], tr.anchor_yaw[idx] = F["c"], F["cyaw"]
+ self.grasp_yaw[idx], self.turned[idx], self.prev_jaw[idx] = F["cyaw"], 0.0, F["jaw"]
+
+ def set_goal(self, idx, goal_xy, goal_yaw):
+ """Change the goal of worlds idx (C3-b); the shaping potential is re-based (no reward jump)."""
+ self.goal_xy[idx] = torch.as_tensor(goal_xy, dtype=self.kin.dtype, device=self.dev)
+ self.goal_yaw[idx] = torch.as_tensor(goal_yaw, dtype=self.kin.dtype, device=self.dev)
+ if self.F is not None:
+ _, dg = potential({k: v[idx] for k, v in self.F.items()}, self.cfg, self.goal_xy[idx], self.goal_yaw[idx])
+ self.tr.d_goal[idx] = dg
+
+ @torch.no_grad()
+ def step(self, state: WorldState, macro=None, macro_goal=None):
+ """Apply the rules to the states after one world step. macro: long [B] (MACROS codes) of the decoder for the
+ step just taken (``DecoderV2.macro()``), or None (no macros); macro_goal: [B, 4] the decoder's planned end of
+ the GRASP descent (TCP x, y, z, yaw; ``DecoderV2.macro_goal``), used by the grasp-box rule at the trigger
+ (None: the measured TCP pose, horizontal offset and yaw only). Returns reward [B] float, terminated [B] bool
+ (success or failure this step), truncated [B] bool (time-out this step), info dict: end (ENDS code, latched),
+ success / fail / timeout (this step), flags [B, len(RULES)] (rules that fired this step, also log-only ones),
+ xy_err / yaw_err (now), success10 / end_xy_err / end_yaw_err (latched at the end; nan while running), lifted,
+ held, grasp_box_log, turned (cube yaw turned since the first firm lift), t (steps)."""
+ cfg, tr = self.cfg, self.tr
+ F = features(state, self.kin, self.geom, cfg, overlap=self.overlap_rules, plane=self.table_plane)
+ self.F = F
+ B, dev = self.B, self.dev
+ live = tr.end == 0
+ use_macros = macro is not None
+ macro = torch.zeros(B, dtype=torch.long, device=dev) if macro is None else macro.to(dev).long()
+ free = macro == 0
+ in_grasp = (macro >= GRASP_MACROS[0]) & (macro <= GRASP_MACROS[-1])
+ tr.t = tr.t + live.long()
+ fire = {}
+ fire["world_invalid"] = state.invalid.to(dev).bool() | ~F["finite"]
+ fire["world_arm_table"] = state.arm_table.to(dev).bool()
+ fire["lowest_point"] = F["lowest"] < cfg.lowest_min
+ zero = torch.zeros(B, dtype=torch.bool, device=dev)
+ fire["link_overlap"] = F["link_depth"] > cfg.link_depth if self.overlap_rules else zero
+ fire["jaw_overlap"] = F["jaw_overlap"] > cfg.jaw_depth if self.overlap_rules else zero
+ fire["base_zone"] = F["base_zone"]
+ # grasp box: at the trigger and at the close start
+ trig = (tr.prev_macro == 0) & (macro == MC["grasp_descend"])
+ close = (tr.prev_macro != MC["grasp_close"]) & (macro == MC["grasp_close"])
+ if not use_macros: # no macros: geometric close start
+ close = (F["jaw"] < cfg.close_jaw) & (self.prev_jaw >= cfg.close_jaw) & (F["xg"].norm(dim=-1) < 0.04)
+ self.prev_jaw = F["jaw"].clone()
+ trig_ok = trigger_box_ok(F, cfg) if macro_goal is None else goal_box_ok(F, cfg, macro_goal)
+ fire["grasp_box"] = (trig & ~trig_ok) | (close & ~close_box_ok(F, cfg))
+ fire["keep_out"] = keep_out(F, cfg, free)
+ # support: the cube in the air without being held
+ air_free = ~F["held"] & (F["bottom"] > cfg.release_z)
+ falling = F["v"][:, 2] <= cfg.fall_vz
+ fire["release_high"] = air_free & falling
+ tr.unsup_run = torch.where(air_free & ~falling, tr.unsup_run + 1, 0)
+ fire["unsupported"] = tr.unsup_run >= cfg.unsupported_steps
+ tr.air_run = torch.where(F["held"] & (F["bottom"] > cfg.air_z), tr.air_run + 1, 0)
+ fire["hold_cap"] = tr.air_run * CONTROL_DT > cfg.hold_cap_s + 1e-9
+ tr.since_release = torch.where(F["held"], 0, tr.since_release + 1)
+ tr.slide_run = torch.where(free & F["on_table"] & ~F["near_jaws"] & (F["vxy"] > cfg.slide_v)
+ & (tr.since_release * CONTROL_DT > cfg.slide_grace_s + 1e-9), tr.slide_run + 1, 0)
+ fire["cube_slide"] = tr.slide_run >= cfg.slide_steps
+ tr.tilt_run = torch.where(F["on_table"] & ~F["held"] & (F["tilt"] > cfg.tilt_fail), tr.tilt_run + 1, 0)
+ fire["cube_tilted"] = tr.tilt_run >= cfg.tilt_steps
+ fire["arm_self"] = F["self_depth"] > -cfg.self_margin if cfg.self_rule else zero
+ if cfg.ghost_rule: # no touch, no motion: the cube on the table moved since a gripper / jaw point was near
+ near = F["touch"] < cfg.touch_d
+ anchor = near | F["held"] | ~F["on_table"]
+ tr.anchor_xy = torch.where(anchor[:, None], F["c"], tr.anchor_xy)
+ tr.anchor_yaw = torch.where(anchor, F["cyaw"], tr.anchor_yaw)
+ dc = F["c"] - tr.anchor_xy
+ moved = ((dc[:, :2].norm(dim=-1) > cfg.ghost_d) | (dc[:, 2].abs() > cfg.ghost_dz)
+ | (wrap90(F["cyaw"] - tr.anchor_yaw).abs() > cfg.ghost_yaw))
+ fire["moved_untouched"] = F["on_table"] & ~near & moved
+ else:
+ fire["moved_untouched"] = zero
+ # firm lift (success precondition)
+ tr.lift_run = torch.where(F["held"] & (F["bottom"] >= cfg.lift_z), tr.lift_run + 1, 0)
+ new_lift = ~tr.lifted & (tr.lift_run >= cfg.lift_steps) & live
+ self.grasp_yaw = torch.where(new_lift, F["cyaw"], self.grasp_yaw)
+ tr.lifted = tr.lifted | new_lift
+ self.turned = torch.where(tr.lifted & F["held"], wrap90(F["cyaw"] - self.grasp_yaw), self.turned)
+ # end codes (rule order = priority)
+ fail = torch.zeros(B, dtype=torch.bool, device=dev)
+ code = torch.zeros(B, dtype=torch.long, device=dev)
+ flags = torch.stack([fire[r] for r in RULES], -1) & live[:, None]
+ for r in RULES:
+ if r in cfg.log_only:
+ continue
+ new = fire[r] & live & ~fail
+ code = torch.where(new, EC[r], code)
+ fail = fail | new
+ tr.box_log = tr.box_log | (fire["grasp_box"] & live)
+ ok15 = success_now(F, cfg, self.goal_xy, self.goal_yaw, tr.lifted)
+ ok10 = success_now(F, cfg, self.goal_xy, self.goal_yaw, tr.lifted, cfg.tol2_xy, cfg.tol2_yaw)
+ succ = ok15 & live & ~fail
+ code = torch.where(succ, EC["success"], code)
+ timeout = live & ~fail & ~succ & (tr.t >= cfg.horizon)
+ code = torch.where(timeout, EC["timeout"], code)
+ # reward
+ d_reach, d_goal = potential(F, cfg, self.goal_xy, self.goal_yaw)
+ d_reach = torch.where(in_grasp, tr.d_reach, d_reach) # frozen in a GRASP macro
+ phi0 = -(cfg.w_reach * tr.d_reach * (~tr.lifted | new_lift) + cfg.w_goal * tr.d_goal)
+ phi1 = -(cfg.w_reach * d_reach * ~tr.lifted + cfg.w_goal * d_goal)
+ rew = phi1 - phi0 - cfg.time_cost + cfg.lift_bonus * new_lift + cfg.success_bonus * succ
+ n_left = (cfg.horizon - tr.t).clamp_min(0).to(rew.dtype)
+ charge = cfg.time_cost * (1 - cfg.gamma ** n_left) / (1 - cfg.gamma) if cfg.gamma < 1 else cfg.time_cost * n_left
+ rew = rew - fail * (cfg.fail_cost + charge)
+ rew = torch.where(live, rew, torch.zeros_like(rew))
+ rew = torch.where(torch.isfinite(rew), rew, torch.full_like(rew, -cfg.fail_cost))
+ tr.d_reach, tr.d_goal = torch.where(live, d_reach, tr.d_reach), torch.where(live, d_goal, tr.d_goal)
+ tr.end = torch.where(live, code, tr.end)
+ tr.prev_macro, tr.prev_held = macro, F["held"]
+ ex, ey = goal_errors(F, self.goal_xy, self.goal_yaw)
+ ended = live & (code != 0)
+ tr.success10 = tr.success10 | (succ & ok10)
+ tr.end_xy = torch.where(ended, ex, tr.end_xy)
+ tr.end_yaw = torch.where(ended, ey, tr.end_yaw)
+ info = dict(end=tr.end.clone(), success=succ, fail=fail, timeout=timeout, flags=flags, xy_err=ex, yaw_err=ey,
+ success10=tr.success10.clone(), end_xy_err=tr.end_xy.clone(), end_yaw_err=tr.end_yaw.clone(),
+ lifted=tr.lifted.clone(), held=F["held"], grasp_box_log=tr.box_log.clone(),
+ turned=self.turned.clone(), t=tr.t.clone())
+ return rew, (fail | succ), timeout, info
+
+ # -- observation --
+ def observation(self, state: WorldState, dec_obs=None, macro=None, F=None):
+ """Policy observation [B, D] float32 (module docstring). F: features of ``state`` if already computed."""
+ F = F if F is not None else features(state, self.kin, None, self.cfg)
+ return observation(F, self.goal_xy, self.goal_yaw, self.tr.lifted, self.tr.air_run, self.cfg, dec_obs, macro)
+
+
+def observation(F, goal_xy, goal_yaw, lifted, air_run, cfg: TaskConfig, dec_obs=None, macro=None):
+ """The observation as a pure function (see the module docstring); float32 [B, D]."""
+ B = F["q"].shape[0]
+ ex, _ = goal_errors(F, goal_xy, goal_yaw)
+ rel_yaw = 4 * (F["cyaw"] - F["gyaw"])
+ parts = [F["q"], F["qd"], F["tcp"],
+ F["rg"][:, :, 0], F["rg"][:, :, 2], F["c"], torch.sin(4 * F["cyaw"])[:, None],
+ torch.cos(4 * F["cyaw"])[:, None], F["tilt"][:, None]]
+ if cfg.obs_rates:
+ parts += [F["v"], F["w"]]
+ parts += [F["xg"], torch.sin(rel_yaw)[:, None], torch.cos(rel_yaw)[:, None], goal_xy,
+ torch.sin(4 * goal_yaw)[:, None], torch.cos(4 * goal_yaw)[:, None], goal_xy - F["c"][:, :2],
+ wrap90(goal_yaw - F["cyaw"])[:, None], lifted.to(F["q"].dtype)[:, None],
+ (air_run.to(F["q"].dtype) * CONTROL_DT / cfg.hold_cap_s).clamp(0, 1)[:, None]]
+ m = torch.zeros(B, dtype=torch.long, device=F["q"].device) if macro is None else macro.long()
+ parts.append(torch.nn.functional.one_hot(m.clamp(0, len(MACROS) - 1), len(MACROS)).to(F["q"].dtype))
+ if dec_obs is not None:
+ parts.append(dec_obs.to(F["q"].dtype))
+ return torch.cat(parts, -1).float()
+
+
+def obs_dim(cfg: TaskConfig | None = None, dec_dim: int = 0) -> int:
+ cfg = cfg or TaskConfig()
+ 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
+
+
+# ---- goals and starts ------------------------------------------------------------------------------------------------
+def sample_annulus(n, gen=None, device="cpu", dtype=torch.float64):
+ """n points (x, y) [n, 2] of the workspace annulus by the collector's sample_cube rule (r and angle uniform)."""
+ u = torch.rand(n, 2, generator=gen, device=device, dtype=dtype)
+ r = ANNULUS_R[0] + (ANNULUS_R[1] - ANNULUS_R[0]) * u[:, 0]
+ a = torch.deg2rad(ANNULUS_DEG[0] + (ANNULUS_DEG[1] - ANNULUS_DEG[0]) * u[:, 1])
+ return torch.stack((PAN_AXIS_XY[0] + r * torch.cos(a), PAN_AXIS_XY[1] + r * torch.sin(a)), -1)
+
+
+def sample_goals(cube_xy, cube_yaw, gen=None, turned=None, dist=GOAL_DIST, turn_deg=GOAL_TURN_DEG, max_turn=MAX_TURN,
+ tries=64):
+ """Goals for cubes at cube_xy [B, 2] with yaw cube_yaw [B] (mod 90): goal xy on the annulus at distance dist from
+ the cube (rejection sampling, ``tries`` candidates per round), goal yaw = cube yaw + U(lo, hi) mod 90 with
+ [lo, hi] = [-turn, turn] intersected with [-max_turn - turned, max_turn - turned] (turned [B]: the cube turn made
+ since the grasp, rad; None = 0). -> (goal_xy [B, 2], goal_yaw [B] in [0, pi/2)). Draws on the generator's device."""
+ dev = cube_xy.device if gen is None else gen.device
+ dt = cube_xy.dtype
+ xy0 = cube_xy.to(dev)
+ B = xy0.shape[0]
+ goal = torch.full((B, 2), math.nan, dtype=dt, device=dev)
+ todo = torch.ones(B, dtype=torch.bool, device=dev)
+ for _ in range(100):
+ cand = sample_annulus(B * tries, gen, dev, dt).reshape(B, tries, 2)
+ d = (cand - xy0[:, None]).norm(dim=-1)
+ ok = (d >= dist[0]) & (d <= dist[1])
+ first = ok.float().argmax(-1)
+ pick = cand[torch.arange(B, device=dev), first]
+ new = todo & ok.any(-1)
+ goal = torch.where(new[:, None], pick, goal)
+ todo = todo & ~new
+ if not bool(todo.any()):
+ break
+ else:
+ raise RuntimeError("no goal on the annulus at the requested distance")
+ t0 = torch.zeros(B, dtype=dt, device=dev) if turned is None else turned.to(dev, dt)
+ lo = torch.clamp(-max_turn - t0, min=-math.radians(turn_deg))
+ hi = torch.clamp(max_turn - t0, max=math.radians(turn_deg))
+ u = torch.rand(B, generator=gen, device=dev, dtype=dt)
+ yaw = torch.remainder(cube_yaw.to(dev, dt) + lo + (hi - lo) * u, QUARTER)
+ return goal.to(cube_xy.device), yaw.to(cube_xy.device)
+
+
+def load_start_bank(data_dir, split=0, families=TASK_FAMILIES, device="cpu", limit=None):
+ """First recorded states of the task-family episodes of one split of a grasp dataset (unified_data.npz) ->
+ dict of float64 tensors q [N, 6], qd [N, 6] (the recorded rates; zero at a resting start), cube_pos [N, 3],
+ cube_quat [N, 4], cube_v, cube_w [N, 3], plus rows (long [N], episode rows) and family. NEVER the sealed test."""
+ import numpy as np
+
+ from nedm.so101_policy.npz_rows import npz_members
+ if "test_sealed" in str(data_dir):
+ raise ValueError("the sealed test data must not be used for task starts")
+ f = npz_members(Path(data_dir) / "unified_data.npz")
+ fam, sp = np.asarray(f["family"]), np.asarray(f["splits"])
+ rows = np.flatnonzero((sp == split) & np.isin(fam, list(families)))
+ if limit is not None:
+ rows = rows[:limit]
+ arm = np.asarray(f["arm"][:, 0])[rows].astype(np.float64)
+ cube = np.asarray(f["cube"][:, 0])[rows].astype(np.float64)
+ t = lambda x: torch.as_tensor(x, dtype=torch.float64, device=device) # noqa: E731
+ return dict(q=t(arm[:, :6]), qd=t(arm[:, 6:]), cube_pos=t(cube[:, :3]), cube_quat=t(cube[:, 3:7]),
+ cube_v=t(cube[:, 7:10]), cube_w=t(cube[:, 10:13]),
+ rows=torch.as_tensor(rows, dtype=torch.long, device=device),
+ family=torch.as_tensor(fam[rows].astype(np.int64), device=device))
+
+
+def make_tasks(bank: dict, n, gen=None):
+ """n tasks from a start bank: (start index [n] into the bank, goal_xy [n, 2], goal_yaw [n])."""
+ N = bank["q"].shape[0]
+ dev = bank["q"].device if gen is None else gen.device
+ i = torch.randint(N, (n,), generator=gen, device=dev).to(bank["q"].device)
+ yaw, _ = cube_yaw_tilt(bank["cube_quat"][i])
+ gxy, gyaw = sample_goals(bank["cube_pos"][i, :2], yaw, gen)
+ return i, gxy, gyaw
+
+
+def start_state(bank: dict, i) -> WorldState:
+ """WorldState [n] of the bank starts i (at rest: qd, v, w as recorded; contact / flags False)."""
+ n = len(i)
+ dev = bank["q"].device
+ 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
+ return WorldState(q=bank["q"][i], qd=bank["qd"][i], cube_pos=bank["cube_pos"][i], cube_quat=bank["cube_quat"][i],
+ cube_v=bank["cube_v"][i], cube_w=bank["cube_w"][i], contact=fb(3), arm_table=fb(0),
+ invalid=fb(0))
+
+
+
+# ---- recorded data on the 20 ms grid ---------------------------------------------------------------------------------
+def grid_from_records(arm, cube, stride=2, dt=CONTROL_DT):
+ """Recorded collector states (arm [N, T, 12], cube [N, T, 13], 10 ms records) -> the WorldState fields on the
+ 20 ms control grid (records 0, stride, 2 stride, ...) with the data's step-average rates (``data.step_average_rates``:
+ pose difference over one control step, quaternion as the world-frame rotation vector of q1 conj(q0); the first
+ grid point keeps the recorded rates). -> dict of float64 tensors [N, J, ...]: q, qd, cube_pos, cube_quat, cube_v,
+ cube_w."""
+ arm = torch.as_tensor(arm, dtype=torch.float64)[:, ::stride]
+ cube = torch.as_tensor(cube, dtype=torch.float64)[:, ::stride]
+ q, pos, quat = arm[..., :6], cube[..., :3], cube[..., 3:7]
+ qd, v, w = arm[..., 6:].clone(), cube[..., 7:10].clone(), cube[..., 10:13].clone()
+ qd[:, 1:] = (q[:, 1:] - q[:, :-1]) / dt
+ v[:, 1:] = (pos[:, 1:] - pos[:, :-1]) / dt
+ q1, q0 = quat[:, 1:], quat[:, :-1]
+ w0, v0 = q0[..., :1], -q0[..., 1:]
+ w1, v1 = q1[..., :1], q1[..., 1:]
+ ww = w1 * w0 - (v1 * v0).sum(-1, keepdim=True)
+ vv = w1 * v0 + w0 * v1 + torch.cross(v1, v0, dim=-1)
+ sign = torch.where(ww < 0, -1.0, 1.0)
+ ww, vv = ww * sign, vv * sign
+ n = vv.norm(dim=-1, keepdim=True)
+ w[:, 1:] = torch.where(n > 1e-12, vv / n.clamp_min(1e-12) * 2 * torch.atan2(n, ww), 2 * vv) / dt
+ return dict(q=q, qd=qd, cube_pos=pos, cube_quat=quat, cube_v=v, cube_w=w)
+
+
+def grid_state(grid: dict, j, device=None) -> WorldState:
+ """WorldState [N] of grid point j of ``grid_from_records`` (contact / flags False)."""
+ g = {k: v[:, j].to(device) if device is not None else v[:, j] for k, v in grid.items()}
+ n, dev = g["q"].shape[0], g["q"].device
+ return WorldState(contact=torch.zeros(n, 3, dtype=torch.bool, device=dev),
+ arm_table=torch.zeros(n, dtype=torch.bool, device=dev),
+ invalid=torch.zeros(n, dtype=torch.bool, device=dev), **g)
diff --git a/so101_pick_place/code/src/nedm/so101_policy/vec_env.py b/so101_pick_place/code/src/nedm/so101_policy/vec_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..512d4eaf369598c19d2fa77b9d1da46747d4ed3b
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/vec_env.py
@@ -0,0 +1,661 @@
+"""Batched goal pick-and-place task env of the SO101 + cube policy study: world + DecoderV2 + PickPlaceTask +
+observation + reward, one policy decision per 0.1 s (spec_v2 B1-B4). The same class trains PPO in every world and
+evaluates any policy in every world, CPU MuJoCo included (``scripts/so101_policy/train_ppo.py``, ``eval_policy.py``).
+
+Worlds (``WORLDS``; all take 6 joint targets per 20 ms and return a ``world.WorldState``):
+
+| kind | class | device | training starts (``EnvConfig.starts``) |
+|---|---|---|---|
+| nrd | ``nrd_sim.GraspNrdSim`` (checkpoints ``ckpts``, ``members``) | CUDA (CPU works) | bank, exact resting history |
+| mujoco | ``mujoco_env.MujocoWorlds`` (CPU MuJoCo, the ground truth; ``mj_workers`` processes) | CPU | evaluation only (tasks with the collector warm-up) |
+
+One ``step(actions)`` = one decision:
+
+1. ``a = tanh(actions)`` (the policy's Gaussian lives in pre-tanh space; ``squashed=True`` passes a in [-1, 1] as it
+ is, e.g. the FSM expert), ``DecoderV2.decide(a, state)``. Action (``decoder`` module docstring): a[0:3] TCP target
+ displacement (x 35 mm), a[3] yaw change (x 0.2 rad), a[4] GRASP / PLACE trigger (> 0), a[5] GRASP lift height
+ (3-12 cm). Action groups for the std (``ACTION_GROUPS``): move (4), trigger (1), lift (1).
+2. ``decision_steps`` (5) x [``DecoderV2.step(q)`` -> joint targets, world step, ``PickPlaceTask.step(state, macro,
+ macro_goal)``]. The decision reward = the sum of the 5 task rewards (worlds that ended inside the decision get 0 for
+ the rest of it; their world keeps stepping until the reset at the decision end).
+3. Done = the task ended in this decision (success, a failure rule, or the time-out at ``horizon`` = 400 steps = 80
+ decisions); ``extras["time_outs"]`` marks time-outs (value bootstrap) and ``extras["final_obs"]`` holds the
+ observation of the last state before the reset (all worlds; it equals ``obs`` for worlds that did not end).
+4. ``auto_reset``: ended worlds get a new task from the task pool and a new decoder macro seed, then the observation.
+ ``reset()`` staggers the first episodes (``stagger``: random start of the episode clock), so the 80-decision
+ time-outs of all worlds do not fall in the same PPO iteration.
+
+Reward (``task.PickPlaceTask``, P1-14): progress shaping, lift bonus, success bonus (terminal), time cost, failure =
+``fail_cost`` + the discounted time cost of the remaining steps (``charge_remaining``). The task discounts that charge
+per 20 ms step with ``TaskConfig.gamma``; the env sets it to ``gamma ** (1 / decision_steps)`` (``EnvConfig.gamma`` =
+PPO's per-decision discount), so the charge equals PPO's discounted time cost of the remaining decisions to 0.5 %.
+
+Action mask (``extras["action_mask"]`` [B, 6] bool; PPO drops the unused dims from the log-likelihood, review P1-10):
+move dims where the decision drove free motion (decoder free / hold, or a GRASP abort; not on a trigger decision,
+whose free motion is the brake), the trigger where it was read (free / hold, and the GRASP descent before the close,
+where a[4] <= 0 aborts), the lift height where a GRASP started. Inside the other macro phases no dim is used. With
+the decoder's CARRY macro (``decoder.carry_macro``, option b2): in mode hold at rest a[0:2] and a[3] set the CARRY
+line (a[2] unused), during a CARRY line only a[5] (its abort) is read.
+
+Observation: ``task.observation`` (the same function for every world; no contact flags) with the decoder state
+(``DecoderV2.observation``, 24): ``task.obs_dim(cfg, 24)`` = 79 (73 with ``task.obs_rates`` False). Optional
+Gaussian noise on the cube v / w entries (review F11; ``obs_rate_noise`` = (m/s, rad/s), training only).
+
+Starts and goals (spec_v2 B4; written down here):
+
+- ``starts`` = a start bank: the first recorded states of the task-family episodes of one split of a grasp dataset
+ (``task.load_start_bank``: production_plus split 0 = 25,197 starts, cube flat at rest, z = 14.993 mm; never the
+ sealed test), or an .npz from ``train_ppo.py bank`` (the same rows) or ``train_ppo.py starts`` (fresh collector
+ starts: ``mujoco_env.sample_starts`` on new seeds, settled by the collector's 0.3 s warm-up; seeds 200000+ by
+ default, never the validation 1000-2023, the test 900000+ or a collector seed). Both are the collector's task start
+ distribution (arm at a top-down pose, cube on the annulus r 0.15-0.27 m, +-75 deg), so the two choices are
+ comparable; the data bank is the default for ALL training worlds (NRD, kinematic, MuJoCo Warp: its exact reset of a
+ recorded post-warm-up state), which keeps the arms on identical starts.
+- Task pool: ``pool_size`` (start index, goal) pairs drawn once on the env's device (``task.sample_goals``: annulus,
+ 6-30 cm from the start cube, yaw +-30 deg; generator ``seed``), ``refresh_pool()`` draws a new pool (the trainer
+ calls it between iterations: no host sync inside ``step``). A reset picks pool entries uniformly on the device.
+- Decoder macro seeds (review F5): world slot i, its k-th episode -> ``(seed * 0x9E3779B1 + k * B + i) mod 2^32``,
+ so durations differ between the episodes of a slot. Evaluation (``reset_tasks``) passes the task seed (the gate's
+ rule: identical macro durations in every world).
+
+Grasp assist (``grasp_assist``, off by default; a curriculum hook, NOT the study's rule set): a GRASP trigger whose
+descent end (``brake_stop`` = ``DecoderV2.macro_goal`` before the decision, the decoder's own brake rule) would put
+the cube outside the training grasp box (|x| <= ``box_x``, |y| <= ``box_y``, yaw <= ``close_yaw``, x 0.98) is
+ignored (a[4] := -1) and charged ``grasp_assist_cost``, instead of ending the episode by the grasp-box rule; and a
+started GRASP is not aborted (a[4] := +1 in g_brake / g_descend / g_settle; the trigger dim is then unused). Purpose:
+PPO finds lifts. With the rule alone every early trigger fails and the policy stops triggering; with the box part alone
+every in-box GRASP is aborted at the next decision by the random trigger (measured 2026-10-11 21:35, build3_ppo.md).
+A later stage turns the assist off (review P0-8 keeps the rule as a termination for the final policy, and the policy
+must then hold the trigger itself). ``extras["counts"]`` holds per-decision event flags (assist_blocked, assist_held,
+grasp_started, place_started, aborted) for the learning curve.
+
+Decoder PPO options (``decoder`` overrides, ``decoder.DecoderV2Config``; build4_ppo2.md): ``grasp_gate`` (a GRASP
+trigger outside the gate box is ignored at no cost: the permanent rule that replaces the grasp assist),
+``grasp_latch`` (a started GRASP is not aborted by a[4]) and ``abort_action`` (a 7th action column a[6], the explicit
+abort of a pre-close GRASP and of a CARRY line; action group "abort"). ``action_groups(cfg)`` gives the groups of an
+env config; the action mask covers a[6] where it is read.
+
+Grasp-pose shaping (``grasp_shaping``, off by default; build4_ppo2.md): a potential-based term on top of the task
+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) +
+w_yaw min(|yaw|, yaw_max)), (x, y, yaw) = the cube centre and yaw in the frame of the brake rest point
+(``DecoderV2.brake_stop``: where a GRASP started now would descend), while the decoder is in mode free and before the
+first firm lift; frozen during a GRASP macro (as the task freezes its reach term), 0 after the first lift and at a
+terminal state (a time-out keeps Phi of its last state: truncation).
+
+Provenance (review_code_v2 R1 / R6): ``resolved()`` = the env config, the resolved TaskConfig and DecoderV2Config (all
+fields); the trainer writes it into every checkpoint and run directory, and the evaluation rebuilds the decoder and
+the observation from it.
+
+Host syncs per decision: one ``nonzero`` for the reset indices (plus the decoder's and the worlds' own ``.any()``
+checks). Everything else stays on the env's device.
+"""
+from __future__ import annotations
+
+import copy
+import math
+from dataclasses import asdict, dataclass, field, fields, replace
+from pathlib import Path
+
+import torch
+
+from nedm.so101_policy import task as T
+from nedm.so101_policy.decoder import DecoderV2, DecoderV2Config, M
+from nedm.so101_policy.kin import SO101Kin
+from nedm.so101_policy.paths import DATA
+from nedm.so101_policy.world import WorldState
+
+WORLDS = ("nrd", "mujoco") # the study's kin and mjwarp worlds are not part of this release (so101-pick-place-study)
+ACTION_DIM = 6
+ACTION_GROUPS = (("move", 4), ("trigger", 1), ("lift", 1)) # + ("abort", 1) with decoder abort_action
+GEOM_NPZ = DATA / "rl_inputs" / "geometry" / "task_geom_v2.npz" # with the self-contact arrays (no MuJoCo)
+PP_DATA = DATA / "nrd_data" / "production_plus"
+KIN_POINTS = DATA / "rl_inputs" / "geometry" / "kin_points_v1.npz" # kin.save_points (no MuJoCo at run time)
+_M32 = 0xFFFFFFFF
+EP_KEYS = ("end", "success", "success10", "lifted", "end_xy", "end_yaw", "ret", "length", "steps")
+# seeds that must never be training starts (validation / gate 1000-2023, gate2 400000-499999, test 900000+; review R9)
+RESERVED_SEEDS = ((1000, 2023), (400000, 499999), (900000, 2 ** 62))
+
+
+def reserved_seed_hits(seeds) -> int:
+ """Number of seeds in the reserved (validation / test) ranges."""
+ import numpy as np
+ s = np.asarray(seeds).astype(np.int64).ravel()
+ return int(sum(((s >= lo) & (s <= hi)).sum() for lo, hi in RESERVED_SEEDS))
+
+
+@dataclass
+class EnvConfig:
+ world: str = "nrd"
+ num_envs: int = 4096
+ device: str = "cuda"
+ seed: int = 0 # task pool, decoder macro seeds, observation noise
+ ckpts: list = field(default_factory=list) # NRD checkpoints (paths)
+ members: object = "split" # GraspNrdSim members
+ nrd_cuda_graph: bool = True # capture the NRD step in a CUDA graph (CUDA only)
+ starts: str = str(PP_DATA) # data dir (unified_data.npz) or .npz start bank (module docstring)
+ start_split: int = 0
+ pool_size: int = 65536
+ gamma: float = 0.99 # PPO discount per decision (task charge per step = gamma ** (1 / 5))
+ task: dict = field(default_factory=dict) # TaskConfig overrides
+ eval_rules: bool = False # TaskConfig.evaluation(): the grasp-box rule logs only
+ overlap_rules: object = None # None: on, except in CPU MuJoCo (real contacts + the collector's overlap end)
+ decoder: dict = field(default_factory=dict) # DecoderV2Config overrides
+ obs_rate_noise: tuple = (0.0, 0.0) # std of Gaussian noise on the observed cube v (m/s) and w (rad/s)
+ auto_reset: bool = True
+ stagger: bool = True # reset(): episode clocks start at random decisions (spread the time-outs)
+ grasp_assist: bool = False # exploration aid (curriculum, module docstring): out-of-box GRASP triggers ignored
+ grasp_assist_cost: float = 0.05 # reward charged for an ignored trigger
+ grasp_shaping: dict = field(default_factory=dict) # grasp-pose shaping (module docstring): w_x, w_y, w_yaw (per m,
+ # per rad), x_max, y_max, yaw_max (m, rad); {} = off
+ geom_path: str = str(GEOM_NPZ) # TaskGeometry .npz (machines without the vendor model); missing -> MuJoCo
+ kin_points: str = str(KIN_POINTS) # SO101Kin collision points .npz (kin.save_points); missing -> MuJoCo
+ mj_workers: int = 0 # CPU MuJoCo worker processes
+ mj_python: object = None # interpreter of the CPU MuJoCo workers (luffy: conda nrdsim has scipy)
+ mjwarp: dict = field(default_factory=dict) # MjwarpWorlds kwargs (nconmax, njmax, graph, opt)
+
+ @staticmethod
+ def from_dict(d: dict | None) -> "EnvConfig":
+ d = dict(d or {})
+ known = {f.name for f in fields(EnvConfig)}
+ bad = sorted(set(d) - known - {"note", "notes"})
+ if bad:
+ raise ValueError(f"unknown env config keys {bad}")
+ return EnvConfig(**{k: v for k, v in d.items() if k in known})
+
+ def to_dict(self) -> dict:
+ return copy.deepcopy(asdict(self))
+
+
+def decoder_config(cfg: EnvConfig) -> DecoderV2Config:
+ return replace(DecoderV2Config(), **cfg.decoder)
+
+
+def action_groups(cfg: EnvConfig | dict) -> tuple:
+ """Action groups (name, size) of an env config: ACTION_GROUPS, + ("abort", 1) with the decoder's abort_action."""
+ d = (cfg.decoder if isinstance(cfg, EnvConfig) else (cfg or {}).get("decoder", {})) or {}
+ return ACTION_GROUPS + ((("abort", 1),) if d.get("abort_action", False) else ())
+
+
+def task_config(cfg: EnvConfig) -> T.TaskConfig:
+ """The env's TaskConfig: training rules (or evaluation rules), the overrides, and the per-step charge discount."""
+ over = dict(cfg.task)
+ if "log_only" in over:
+ over["log_only"] = tuple(over["log_only"])
+ dec_steps = decoder_config(cfg).decision_steps
+ over.setdefault("gamma", float(cfg.gamma) ** (1.0 / dec_steps))
+ return T.TaskConfig.evaluation(**over) if cfg.eval_rules else T.TaskConfig(**over)
+
+
+def obs_layout(tcfg: T.TaskConfig, dec_dim: int = DecoderV2.OBS_DIM) -> dict:
+ """name -> slice of ``task.observation`` (same order as there)."""
+ parts = [("q", 6), ("qd", 6), ("tcp", 3), ("grip_x", 3), ("grip_z", 3), ("cube_pos", 3), ("cube_yaw4", 2),
+ ("cube_tilt", 1)]
+ if tcfg.obs_rates:
+ parts += [("cube_v", 3), ("cube_w", 3)]
+ parts += [("cube_in_grasp", 3), ("rel_yaw4", 2), ("goal_xy", 2), ("goal_yaw4", 2), ("goal_minus_cube", 2),
+ ("yaw_err", 1), ("lifted", 1), ("hold_time", 1), ("macro", len(T.MACROS)), ("decoder", dec_dim)]
+ out, k = {}, 0
+ for n, w in parts:
+ out[n] = slice(k, k + w)
+ k += w
+ return out
+
+
+def kinematics(points_path, device) -> SO101Kin:
+ """SO101Kin with the collision points of ``points_path`` (identical arrays to ``kin.collision_points``) or, if that
+ file is missing, from MuJoCo."""
+ from nedm.so101_policy.kin import load_points
+ p = Path(points_path).expanduser() if points_path else None
+ return SO101Kin(device, points=load_points(p) if p is not None and p.exists() else None)
+
+
+def task_geometry(path, device):
+ path = Path(path).expanduser() if path else None
+ return T.TaskGeometry.load(path, device) if path is not None and path.exists() else T.TaskGeometry.from_mujoco(device)
+
+
+def load_starts(spec, split=0, device="cpu", allow_eval=False) -> dict:
+ """Start bank -> dict of float64 tensors q, qd, cube_pos, cube_quat, cube_v, cube_w [N, ...] on device. spec: a
+ grasp data directory (``task.load_start_bank``, task families of ``split``), an .npz with these keys (``train_ppo.py
+ bank`` / ``starts``), or a gate tasks file (``state_*`` keys). Refuses the sealed test always and, unless
+ ``allow_eval`` (evaluation only), any validation / test start (review R9): a file whose ``seeds`` / ``seed`` array
+ holds a reserved seed (``RESERVED_SEEDS``), a gate tasks file, a data directory named gate* / val* or a split other
+ than 0."""
+ import numpy as np
+ p = Path(str(spec)).expanduser()
+ if "test_sealed" in str(p):
+ raise ValueError("the sealed test data must not be used for starts")
+ keys = ("q", "qd", "cube_pos", "cube_quat", "cube_v", "cube_w")
+ if p.is_dir():
+ if not allow_eval and (split != 0 or p.name.startswith(("gate", "val"))):
+ raise ValueError(f"{p} (split {split}): validation data are not training starts")
+ b = T.load_start_bank(p, split=split, device=device)
+ return {k: b[k] for k in keys}
+ f = np.load(p)
+ if not allow_eval:
+ hits = sum(reserved_seed_hits(f[k]) for k in ("seeds", "seed") if k in f.files)
+ if hits or "goal_xy" in f.files:
+ raise ValueError(f"{p}: {hits} reserved (validation / test) seeds or a task file: not training starts")
+ pre = "state_" if f"state_q" in f.files else ""
+ return {k: torch.as_tensor(f[pre + k], dtype=torch.float64, device=device) for k in keys}
+
+
+def start_rows(bank: dict, i) -> WorldState:
+ """WorldState of the bank rows i (flags False)."""
+ n, dev = len(i), bank["q"].device
+ z = torch.zeros(n, dtype=torch.bool, device=dev)
+ return WorldState(q=bank["q"][i], qd=bank["qd"][i], cube_pos=bank["cube_pos"][i], cube_quat=bank["cube_quat"][i],
+ cube_v=bank["cube_v"][i], cube_w=bank["cube_w"][i], contact=torch.zeros(n, 3, dtype=torch.bool, device=dev),
+ arm_table=z, invalid=z.clone())
+
+
+def make_world(cfg: EnvConfig, B: int, device, kin=None, geom=None, share=None):
+ """World of kind cfg.world with B worlds. share: another env whose NRD models (loaded once) are reused."""
+ kind = cfg.world
+ if kind == "nrd":
+ from nedm.so101_policy.nrd_sim import GraspNrdSim
+ if share is not None and share.cfg.world == "nrd":
+ ck = dict(zip(share.world.member_names, share.world.models))
+ members = share.cfg.members # the training env's model mix (review R10)
+ else:
+ if not cfg.ckpts:
+ raise ValueError("world nrd needs ckpts")
+ ck = {Path(p).stem: str(Path(p).expanduser()) for p in cfg.ckpts}
+ members = cfg.members
+ return GraspNrdSim(ck, num_envs=B, device=device, members=members,
+ cuda_graph=bool(cfg.nrd_cuda_graph) and torch.device(device).type == "cuda")
+ if kind in ("kin", "mjwarp"):
+ raise ValueError(f"world {kind!r} is not part of this release (study branch so101-pick-place-study)")
+ if kind == "mujoco":
+ from nedm.so101_policy.mujoco_env import MujocoWorlds
+ return MujocoWorlds(B, workers=cfg.mj_workers, python=cfg.mj_python)
+ raise ValueError(f"world {kind!r}: one of {WORLDS}")
+
+
+def brake_stop(dec: DecoderV2):
+ """Where a GRASP / PLACE trigger at the next decision stops the decoder target: -> (xy [B, 2] m, yaw [B] rad) =
+ ``macro_goal`` x, y, yaw of a GRASP started now, for every blend (``DecoderV2.brake_stop``, review R4)."""
+ p, yaw = dec.brake_stop()
+ return p[:, :2], yaw
+
+
+class PickPlaceVecEnv:
+ """B task worlds on one device (module docstring). ``reset() -> obs``; ``step(actions) -> (obs, reward, done,
+ extras)``; ``reset_tasks(idx, starts, goal_xy, goal_yaw, seeds)`` for fixed evaluation tasks; ``set_tolerance``
+ (curriculum). share: an env whose kinematics, geometry, start bank and NRD models are reused (validation env)."""
+
+ def __init__(self, cfg: EnvConfig | dict, share: "PickPlaceVecEnv | None" = None, record: bool = False):
+ self.cfg = cfg = EnvConfig.from_dict(cfg) if isinstance(cfg, dict) else cfg
+ if cfg.world not in WORLDS:
+ raise ValueError(f"world {cfg.world!r}: one of {WORLDS}")
+ self.dev = dev = torch.device("cpu" if cfg.world == "mujoco" else cfg.device)
+ self.B = B = int(cfg.num_envs)
+ groups = action_groups(cfg)
+ self.num_envs, self.num_actions = B, sum(n for _, n in groups)
+ self.action_groups = [n for _, n in groups] # sizes (ppo.Policy groups)
+ self.action_group_names = [g for g, _ in groups]
+ self.kin = share.kin if share is not None else kinematics(cfg.kin_points, dev)
+ self.geom = share.geom if share is not None else task_geometry(cfg.geom_path, dev)
+ self.tcfg = task_config(cfg)
+ ov = cfg.overlap_rules if cfg.overlap_rules is not None else cfg.world != "mujoco"
+ self.world = make_world(cfg, B, dev, self.kin, self.geom, share)
+ self.dec = DecoderV2(B, dev, kin=self.kin, cfg=decoder_config(cfg), seed=cfg.seed)
+ if self.dec.action_dim != self.num_actions:
+ raise RuntimeError(f"action groups {groups} vs decoder action dim {self.dec.action_dim}")
+ self.task = T.PickPlaceTask(B, dev, kin=self.kin, geom=self.geom, cfg=self.tcfg, overlap_rules=bool(ov))
+ self.steps_per_decision = self.dec.cfg.decision_steps
+ self.max_episode_length = math.ceil(self.tcfg.horizon / self.steps_per_decision) # decisions
+ self.layout = obs_layout(self.tcfg, DecoderV2.OBS_DIM)
+ self.num_obs = T.obs_dim(self.tcfg, DecoderV2.OBS_DIM)
+ # observation entry of the decoder's mode-hold flag (DecoderV2.observation: 11 entries, then the mode one-hot):
+ # the context of ppo.Policy's hold-mode std
+ self.hold_obs_index = self.layout["decoder"].start + 11 + M["hold"]
+ self.gen = torch.Generator(dev).manual_seed(int(cfg.seed))
+ if share is not None:
+ self.bank = share.bank
+ else: # no bank for evaluation envs (starts "") and CPU MuJoCo (fixed tasks only)
+ self.bank = load_starts(cfg.starts, cfg.start_split, dev) if cfg.starts and cfg.world != "mujoco" else None
+ self.pool = None
+ f, li = dict(dtype=torch.float64, device=dev), dict(dtype=torch.long, device=dev)
+ self.ep_count = torch.zeros(B, **li)
+ self.ep_ret = torch.zeros(B, **f)
+ self.ep_len = torch.zeros(B, **li)
+ self.task_seed = torch.zeros(B, **li)
+ self.ws = None
+ self.obs = None
+ self.record = record
+ self.rec = None
+ self.world_steps = 0 # world (20 ms) steps of all worlds since construction
+ self.decisions = 0
+ gs = dict(cfg.grasp_shaping or {})
+ bad = sorted(set(gs) - {"w_x", "w_y", "w_yaw", "x_max", "y_max", "yaw_max"})
+ if bad:
+ raise ValueError(f"grasp_shaping keys {bad}")
+ self.shape_w = gs
+ self.phi = torch.zeros(B, dtype=torch.float64, device=dev) # grasp-pose potential of the current state
+
+ def resolved(self) -> dict:
+ """The env config and the resolved TaskConfig / DecoderV2Config (every field; review R1 / R6)."""
+ return dict(env=self.cfg.to_dict(), task=asdict(self.tcfg), decoder=asdict(self.dec.cfg),
+ num_obs=self.num_obs, num_actions=self.num_actions, action_groups=list(zip(self.action_group_names,
+ self.action_groups)))
+
+ # ---- tasks -------------------------------------------------------------------------------------------------
+ def refresh_pool(self, n=None):
+ """A new pool of (start index, goal_xy, goal_yaw) on the device (host syncs here, not in step)."""
+ if self.bank is None:
+ raise RuntimeError("no start bank (world mujoco: use reset_tasks)")
+ n = int(n or self.cfg.pool_size)
+ N = self.bank["q"].shape[0]
+ i = torch.randint(N, (n,), generator=self.gen, device=self.dev)
+ yaw, _ = T.cube_yaw_tilt(self.bank["cube_quat"][i])
+ gxy, gyaw = T.sample_goals(self.bank["cube_pos"][i, :2], yaw, self.gen)
+ self.pool = dict(i=i, goal_xy=gxy, goal_yaw=gyaw)
+
+ def set_tolerance(self, tol_xy=None, tol_yaw=None):
+ """Curriculum hook (tolerance ladder, review P1-13): success tolerance of the running and future episodes."""
+ if tol_xy is not None:
+ self.tcfg.tol_xy = float(tol_xy)
+ if tol_yaw is not None:
+ self.tcfg.tol_yaw = float(tol_yaw)
+
+ def set_grasp_assist(self, on: bool, cost=None):
+ """Curriculum hook: the grasp assist on / off (module docstring)."""
+ self.cfg.grasp_assist = bool(on)
+ if cost is not None:
+ self.cfg.grasp_assist_cost = float(cost)
+
+ def _assist(self, a):
+ """Grasp assist: [B] bool of the GRASP triggers this decision that would fail the training grasp box."""
+ dec, tc = self.dec, self.tcfg
+ free = dec.mode == M["free"]
+ jaw_ready = (dec.jaw_k >= dec.jaw_n) & ((dec.jaw_to - dec.cfg.jaw_open).abs() < 1e-9)
+ trig = free & dec.armed & jaw_ready & (a[:, 4] > dec.cfg.trigger_thr)
+ sxy, syaw = brake_stop(dec)
+ cyaw, _ = T.cube_yaw_tilt(self.ws.cube_quat.to(torch.float64))
+ d = self.ws.cube_pos[:, :2].to(torch.float64) - sxy
+ c, s_ = torch.cos(syaw), torch.sin(syaw)
+ x, y = c * d[:, 0] + s_ * d[:, 1], -s_ * d[:, 0] + c * d[:, 1]
+ 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)
+ return trig & ~ok
+
+ def _grasp_phi(self, frozen=None):
+ """Grasp-pose potential [B] of the current state (module docstring; 0 without ``grasp_shaping``). frozen: [B]
+ bool, worlds whose potential stays (GRASP macro)."""
+ w = self.shape_w
+ if not w:
+ return self.phi
+ dec = self.dec
+ sp, syaw = dec.brake_stop()
+ cube = self.ws.cube_pos.to(torch.float64)
+ cyaw, _ = T.cube_yaw_tilt(self.ws.cube_quat.to(torch.float64))
+ d = cube[:, :2] - sp[:, :2]
+ c, s_ = torch.cos(syaw), torch.sin(syaw)
+ x, y = c * d[:, 0] + s_ * d[:, 1], -s_ * d[:, 0] + c * d[:, 1]
+ yaw = T.wrap90(syaw - cyaw).abs()
+ phi = -(w.get("w_x", 0.0) * x.abs().clamp_max(w.get("x_max", 0.05))
+ + w.get("w_y", 0.0) * y.abs().clamp_max(w.get("y_max", 0.05))
+ + w.get("w_yaw", 0.0) * yaw.clamp_max(w.get("yaw_max", math.radians(45))))
+ on = (dec.mode == M["free"]) & ~self.task.tr.lifted
+ phi = torch.where(on, phi, torch.zeros_like(phi))
+ if frozen is not None:
+ phi = torch.where(frozen & ~self.task.tr.lifted, self.phi, phi)
+ return phi
+
+ def _episode_seeds(self, idx):
+ s = (int(self.cfg.seed) * 0x9E3779B1 + self.ep_count[idx] * self.B + idx) & _M32
+ self.ep_count[idx] += 1
+ return s
+
+ # ---- resets ------------------------------------------------------------------------------------------------
+ def _reset_rows(self, idx, start: WorldState, goal_xy, goal_yaw, seeds, mj_start=None):
+ """World, decoder and task reset of worlds idx (long [n]); returns nothing (self.ws updated)."""
+ if self.cfg.world == "mujoco":
+ ws = self.world.reset(idx.cpu(), mj_start, warmup=True)
+ elif self.cfg.world == "mjwarp":
+ ws = self.world.reset(idx, start, warmup=False)
+ else:
+ ws = self.world.reset(idx, start)
+ self.ws = ws.to(self.dev)
+ rows = self.ws.index(idx)
+ self.dec.reset(idx, rows.q, seed=seeds)
+ self.task.reset(idx, rows, goal_xy, goal_yaw)
+ self.task_seed[idx] = seeds
+ self.ep_ret[idx], self.ep_len[idx] = 0.0, 0
+
+ def _pool_reset(self, idx):
+ if self.pool is None:
+ self.refresh_pool()
+ k = torch.randint(len(self.pool["i"]), (len(idx),), generator=self.gen, device=self.dev)
+ i = self.pool["i"][k]
+ self._reset_rows(idx, start_rows(self.bank, i), self.pool["goal_xy"][k], self.pool["goal_yaw"][k],
+ self._episode_seeds(idx))
+
+ def reset(self):
+ """Every world gets a pool task; with ``stagger`` its episode clock starts at a random decision in
+ [0, horizon) (the task's step counter, a multiple of decision_steps: the first episodes are shorter, so the
+ time-outs of all worlds do not fall on the same decision; RSL-RL's init_at_random_ep_len). -> observation
+ [B, D] float32."""
+ idx = torch.arange(self.B, device=self.dev)
+ self._pool_reset(idx)
+ if self.cfg.stagger and self.cfg.auto_reset:
+ k = torch.randint(self.max_episode_length, (self.B,), generator=self.gen, device=self.dev)
+ self.task.tr.t.copy_(k * self.steps_per_decision)
+ self.phi = self._grasp_phi()
+ self.obs = self._observe()
+ self._rec_init()
+ return self.obs
+
+ def reset_tasks(self, idx, starts: WorldState, goal_xy, goal_yaw, seeds, mj_start=None, check_tol=1e-6):
+ """Fixed tasks (evaluation): worlds idx (long [n]) start at the settled states ``starts`` with the goals and
+ decoder seeds given. World mujoco: ``mj_start`` (dict q, cube_pos, cube_quat before the warm-up, as
+ ``sample_starts``) is reset with the collector warm-up and must reproduce ``starts`` to ``check_tol``.
+ -> observation [B, D]."""
+ idx = torch.as_tensor(idx, dtype=torch.long, device=self.dev)
+ st = starts.to(self.dev)
+ self._reset_rows(idx, st, torch.as_tensor(goal_xy, dtype=torch.float64, device=self.dev),
+ torch.as_tensor(goal_yaw, dtype=torch.float64, device=self.dev),
+ torch.as_tensor(seeds, dtype=torch.long, device=self.dev), mj_start)
+ if self.cfg.world == "mujoco" and check_tol is not None:
+ got = self.ws.index(idx)
+ dq = float((got.q - st.q).abs().max())
+ dc = float((got.cube_pos - st.cube_pos).abs().max())
+ if dq > check_tol or dc > check_tol:
+ raise RuntimeError(f"MuJoCo warm-up start differs from the stored settled state ({dq:.2e}, {dc:.2e})")
+ self.phi = self._grasp_phi()
+ self.obs = self._observe()
+ self._rec_init()
+ return self.obs
+
+ # ---- observation ---------------------------------------------------------------------------------------------
+ def _observe(self, F=None, idx=None):
+ """Observation of all worlds (F: task features of self.ws, else computed) or of the rows idx."""
+ ws = self.ws if idx is None else self.ws.index(idx)
+ if F is None:
+ F = T.features(ws, self.kin, None, self.tcfg)
+ sel = (lambda x: x) if idx is None else (lambda x: x[idx])
+ obs = T.observation(F, sel(self.task.goal_xy), sel(self.task.goal_yaw), sel(self.task.tr.lifted),
+ sel(self.task.tr.air_run), self.tcfg, sel(self.dec.observation()), sel(self.dec.macro()))
+ nv, nw = self.cfg.obs_rate_noise
+ if (nv > 0 or nw > 0) and self.tcfg.obs_rates:
+ n = obs.shape[0]
+ obs[:, self.layout["cube_v"]] += float(nv) * torch.randn(n, 3, generator=self.gen, device=self.dev)
+ obs[:, self.layout["cube_w"]] += float(nw) * torch.randn(n, 3, generator=self.gen, device=self.dev)
+ return obs
+
+ def get_observations(self):
+ return self.obs
+
+ # ---- one decision --------------------------------------------------------------------------------------------
+ @torch.no_grad()
+ def step(self, actions, squashed=False):
+ """actions [B, A] (A = num_actions: 6, or 7 with the decoder's abort_action; pre-tanh; squashed=True: already
+ in [-1, 1]) -> (obs [B, D] float32, reward [B] float32, done [B] bool, extras): time_outs [B] bool, final_obs
+ [B, D], action_mask [B, A] bool, episode (dict of [B] tensors, valid where done: end code, success, success10,
+ lifted, end_xy, end_yaw (m, rad), ret (decision reward sum), length (decisions), steps (20 ms steps)), counts
+ (per-decision event flags), world_steps (int)."""
+ dec, task, B = self.dec, self.task, self.B
+ dc = dec.cfg
+ live0 = task.tr.end == 0 # running at the decision start
+ a = actions.to(device=self.dev, dtype=torch.float64)
+ a = a.clamp(-1.0, 1.0) if squashed else torch.tanh(a)
+ A = a.shape[1]
+ blocked = torch.zeros(B, dtype=torch.bool, device=self.dev)
+ held = torch.zeros(B, dtype=torch.bool, device=self.dev)
+ mode0 = dec.mode
+ pre0 = (mode0 == M["g_brake"]) | (mode0 == M["g_descend"]) | (mode0 == M["g_settle"])
+ if self.cfg.grasp_assist:
+ blocked = self._assist(a) & live0
+ held = pre0
+ a = a.clone()
+ a[:, 4] = torch.where(blocked, -1.0, torch.where(held, 1.0, a[:, 4])) # no GRASP abort while assisted
+ if A > 6:
+ a[:, 6] = torch.where(held, -1.0, a[:, 6])
+ free0, hold0 = mode0 == M["free"], mode0 == M["hold"]
+ carry = bool(dc.carry_macro) # decoder option b2 (CARRY macro in mode hold)
+ carry_on0 = dec.carry_on.clone() if carry else torch.zeros_like(hold0)
+ moving0 = hold0 & (carry_on0 | dec.carry_brk) if carry else torch.zeros_like(hold0)
+ latch, a7 = bool(dc.grasp_latch), bool(dc.abort_action) and A > 6
+ pre_ph = self.phi
+ dinfo = dec.decide(a, self.ws)
+ started = dinfo["grasp_started"] | dinfo["place_started"]
+ take_free = (free0 | dinfo["aborted"]) & ~started
+ take_hold = hold0 & ~moving0 & ~started
+ move = take_free | take_hold # x, y, yaw (CARRY: the line's end and turn)
+ move_z = take_free | (take_hold if not carry else torch.zeros_like(take_hold))
+ read4 = free0 | hold0 | ((pre0 & ~held) if not latch else torch.zeros_like(pre0))
+ line_abort = hold0 & carry_on0 # a running CARRY line reads its abort
+ cols = [move, move, move_z, move, read4, dinfo["grasp_started"] | (line_abort & ~torch.full_like(hold0, a7))]
+ if A > 6: # a[6]: the explicit abort (decoder abort_action)
+ cols.append(((pre0 & ~held) & torch.full_like(pre0, latch) | line_abort) & torch.full_like(pre0, a7))
+ mask = torch.stack(cols, -1)
+ rew = torch.zeros(B, dtype=torch.float64, device=self.dev)
+ info = None
+ for _ in range(self.steps_per_decision):
+ u, _ = dec.step(self.ws.q)
+ ws = self.world.step(u)
+ self.ws = ws if self.cfg.world != "mujoco" else ws.to(self.dev)
+ r, _, _, info = task.step(self.ws, dec.macro(), dec.macro_goal)
+ rew += r
+ if self.rec is not None:
+ self._rec_step(u, info)
+ if self.cfg.grasp_assist:
+ rew = rew - self.cfg.grasp_assist_cost * blocked.to(rew.dtype)
+ self.world_steps += B * self.steps_per_decision
+ self.decisions += B
+ end = info["end"]
+ done = live0 & (end != 0) # ended in this decision
+ time_out = done & (end == T.EC["timeout"])
+ if self.shape_w: # grasp-pose shaping: gamma Phi(s') - Phi(s), Phi(terminal) = 0
+ in_grasp = (dec.mode >= M["g_brake"]) & (dec.mode <= M["g_lift"])
+ ph1 = self._grasp_phi(frozen=in_grasp)
+ ph1 = torch.where(done & ~time_out, torch.zeros_like(ph1), ph1)
+ rew = rew + torch.where(live0, self.cfg.gamma * ph1 - pre_ph, torch.zeros_like(ph1))
+ self.phi = ph1
+ self.ep_ret += rew
+ self.ep_len += live0.long()
+ ep = dict(end=end.clone(), success=end == T.EC["success"], success10=info["success10"].clone(),
+ lifted=info["lifted"].clone(), end_xy=info["end_xy_err"].clone(), end_yaw=info["end_yaw_err"].clone(),
+ ret=self.ep_ret.clone(), length=self.ep_len.clone(), steps=info["t"].clone())
+ obs = self._observe(task.F)
+ final_obs = obs
+ if self.cfg.auto_reset:
+ idx = done.nonzero().flatten()
+ if len(idx):
+ obs = obs.clone()
+ self._pool_reset(idx)
+ obs[idx] = self._observe(idx=idx)
+ if self.shape_w:
+ self.phi[idx] = self._grasp_phi()[idx]
+ self.obs = obs
+ counts = dict(assist_blocked=blocked, assist_held=held & live0, grasp_started=dinfo["grasp_started"] & live0,
+ place_started=dinfo["place_started"] & live0, aborted=dinfo["aborted"] & live0,
+ gate_blocked=dinfo.get("gate_blocked", torch.zeros_like(live0)) & live0)
+ extras = dict(time_outs=time_out, final_obs=final_obs, action_mask=mask, episode=ep, counts=counts,
+ world_steps=B * self.steps_per_decision)
+ return obs, rew.float(), done, extras
+
+ # ---- per-step records (evaluation) -------------------------------------------------------------------------
+ def _rec_init(self):
+ if not self.record:
+ return
+ B, dev = self.B, self.dev
+ self.rec = dict(q=[], cube=[], xg=[], u=[], mode=[], macro=[])
+ self.rec_first_fire = torch.full((B, len(T.RULES)), -1, dtype=torch.long, device=dev)
+ self.rec_lift_step = torch.full((B,), -1, dtype=torch.long, device=dev)
+ self.rec_close_x = torch.full((B, 4), math.nan, dtype=torch.float64, device=dev)
+ self.rec_mj_reason = torch.zeros(B, dtype=torch.long)
+ self.rec_t = 0
+
+ def _rec_step(self, u, info):
+ t = self.rec_t
+ live_before = info["t"] == t + 1
+ F = self.task.F
+ self.rec_first_fire = torch.where((self.rec_first_fire < 0) & info["flags"] & live_before[:, None], t,
+ self.rec_first_fire)
+ self.rec_lift_step = torch.where((self.rec_lift_step < 0) & info["lifted"], t, self.rec_lift_step)
+ macro = self.dec.macro()
+ cstart = (macro == T.MC["grasp_close"]) & torch.isnan(self.rec_close_x[:, 0]) & live_before
+ self.rec_close_x = torch.where(cstart[:, None], torch.cat((F["xg"], F["yaw_mis"][:, None]), -1), self.rec_close_x)
+ if self.cfg.world == "mujoco":
+ new_end = (live_before & (info["end"] != 0)).cpu()
+ self.rec_mj_reason = torch.where(new_end, self.world.end_reason.long(), self.rec_mj_reason)
+ ws = self.ws
+ self.rec["q"].append(ws.q.float().cpu())
+ self.rec["cube"].append(torch.cat((ws.cube_pos, ws.cube_quat), -1).float().cpu())
+ self.rec["xg"].append(F["xg"].float().cpu())
+ self.rec["u"].append(u.float().cpu())
+ self.rec["mode"].append(self.dec.mode.to(torch.int8).cpu())
+ self.rec["macro"].append(macro.to(torch.int8).cpu())
+ self.rec_t += 1
+
+ def records(self) -> dict:
+ """Per-step arrays [B, T, ...] (numpy) and per-episode markers of a recorded run (gate_expert run format)."""
+ out = {k: torch.stack(v, 1).numpy() for k, v in self.rec.items()}
+ out.update(first_fire=self.rec_first_fire.cpu().numpy(), lift_step=self.rec_lift_step.cpu().numpy(),
+ close_x=self.rec_close_x.cpu().numpy(), mj_reason=self.rec_mj_reason.numpy())
+ return out
+
+ def close(self):
+ if hasattr(self.world, "close"):
+ self.world.close()
+
+
+# ---- fixed-task episodes (validation, evaluation) ---------------------------------------------------------------------
+def policy_act_fn(policy):
+ """A ``ppo.Policy`` -> act_fn: deterministic pre-tanh mean (the env applies tanh)."""
+ def act(obs, env):
+ return policy.act_inference(obs.to(next(policy.parameters()).device)).to(env.dev), False
+ return act
+
+
+@torch.no_grad()
+def run_episodes(env: PickPlaceVecEnv, act_fn, starts: WorldState, goal_xy, goal_yaw, seeds, mj_start=None,
+ reset_hook=None, log=None) -> dict:
+ """One episode per world on fixed tasks (env.num_envs of them; auto_reset must be off): act_fn(obs, env) ->
+ (actions [B, 6], squashed) once per decision until every world has ended (the task horizon ends the rest).
+ reset_hook(env): called after the reset (e.g. the expert's own reset). -> dict of numpy arrays [B]: end, success,
+ success10, lifted, end_xy, end_yaw, ret, length (decisions), steps (20 ms steps, = task t at the end), seeds."""
+ import numpy as np
+ if env.cfg.auto_reset:
+ raise ValueError("run_episodes needs an env with auto_reset off")
+ obs = env.reset_tasks(torch.arange(env.B, device=env.dev), starts, goal_xy, goal_yaw, seeds, mj_start)
+ if reset_hook is not None:
+ reset_hook(env)
+ keep = None
+ for k in range(env.max_episode_length + 1):
+ a, sq = act_fn(obs, env)
+ obs, _, done, ex = env.step(a, squashed=sq)
+ ep = ex["episode"]
+ if keep is None:
+ keep = {n: v.clone() for n, v in ep.items()}
+ else:
+ for n, v in ep.items():
+ keep[n] = torch.where(done, v, keep[n])
+ if log is not None and k % 20 == 19:
+ log(f" decision {k + 1}: ended {int((env.task.tr.end != 0).sum())}/{env.B}")
+ if bool((env.task.tr.end != 0).all()):
+ break
+ out = {n: v.cpu().numpy() for n, v in keep.items()}
+ out["seeds"] = np.asarray(torch.as_tensor(seeds).cpu())
+ return out
diff --git a/so101_pick_place/code/src/nedm/so101_policy/vision/__init__.py b/so101_pick_place/code/src/nedm/so101_policy/vision/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..650bff97b6f838393d03edc3e224261a2b9c979f
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/vision/__init__.py
@@ -0,0 +1,3 @@
+"""Camera-policy pipeline of the SO101 + cube study (claim C2, spec_v2 B6 / B7): expert demonstrations stored as states
+(``demos``), on-the-fly rendering with the batch renderer (``dataset``), the ACT student (``student``, LeRobot's ACT as a
+library) and its closed-loop evaluation in any world (``rollout``). Report: ~/so101_policy/docs/build4_vision.md."""
diff --git a/so101_pick_place/code/src/nedm/so101_policy/vision/dataset.py b/so101_pick_place/code/src/nedm/so101_policy/vision/dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..31e7dc6895ade08de4e45ed09226c03e720e91b1
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/vision/dataset.py
@@ -0,0 +1,222 @@
+"""Demo states -> training batches of the camera student, with the images drawn on the fly by the batch renderer.
+
+Inputs of one sample (decision k of an episode; ``demos`` module docstring for the stored keys):
+
+| input | shape | content |
+|---|---|---|
+| images | [C, 3, H, W] | ``CAMERAS`` (top, wrist) drawn from (q, cube pose with the TRUE orientation, goal plate) |
+| state ("proprio") | [30] | measured joint angles q (6) + ``DecoderV2.observation()`` (24): known to the robot's own controller |
+| goal | [4] | goal cube centre x, y (m), sin 4 psi, cos 4 psi (psi = goal yaw; the cube's 90 deg symmetry) |
+| target | [chunk, 6] | the expert's decoder actions of decisions k .. k + chunk - 1 (after the episode end: padded, masked) |
+
+Cameras (written down here, build4_vision.md sec. 2): ``top`` lowered to 0.48 m above the table over (0.19, 0) and the
+MJCF wrist camera, 288 x 288 px both (one renderer has one resolution and one 61 deg field of view for all its cameras;
+non-square Madrona images were not centred in a probe, so square only). The top view covers |y| <= 0.283 m at the
+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
+(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
+gate runs, so the camera stays 16 cm above it. The goal plate (``SO101Renderer`` goal "plate") is drawn too.
+
+Images enter the network as float, ImageNet mean / std normalised (the ResNet18 backbone is ImageNet-pretrained).
+Augmentation (``shift_px``): DrQ-style random shift of each image by up to +-shift_px pixels (edge padding), the same
+shift for all cameras of a sample is NOT assumed (independent per camera); 0 = off.
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+
+from nedm.so101_policy.vision import demos as D
+
+CAMERAS = ("top", "wrist")
+RES = 288
+TOP_EYE = (0.19, 0.0, 0.48)
+TOP_TARGET = (0.19, 0.0, 0.0)
+IMAGENET_MEAN = (0.485, 0.456, 0.406)
+IMAGENET_STD = (0.229, 0.224, 0.225)
+STATE_DIM, GOAL_DIM, ACTION_DIM = 30, 4, 6
+PRIV_DIM = 5 # privileged cube state (ablation): cube centre x, y, z (m), sin 4 yaw, cos 4 yaw
+
+
+def cube_vec(cube_pos, cube_quat):
+ """PRIVILEGED (ablation only: a camera policy must not see it): [n, 5] float32 = cube x, y, z, sin 4 yaw, cos 4 yaw
+ (yaw = ``task.cube_yaw_tilt``)."""
+ from nedm.so101_policy.task import cube_yaw_tilt
+ yaw, _ = cube_yaw_tilt(torch.as_tensor(cube_quat).to(torch.float64))
+ return torch.cat((torch.as_tensor(cube_pos).to(yaw), torch.sin(4 * yaw)[:, None], torch.cos(4 * yaw)[:, None]), -1).float()
+
+
+def goal_vec(goal_xy, goal_yaw):
+ """[n, 2], [n] -> [n, 4] float32: x, y, sin 4 psi, cos 4 psi."""
+ gy = torch.as_tensor(goal_yaw, dtype=torch.float64)
+ gxy = torch.as_tensor(goal_xy, dtype=torch.float64)
+ return torch.cat((gxy, torch.sin(4 * gy)[:, None], torch.cos(4 * gy)[:, None]), -1).float()
+
+
+def proprio(q, dec_obs):
+ """[n, 6], [n, 24] -> [n, 30] float32."""
+ return torch.cat((torch.as_tensor(q).float(), torch.as_tensor(dec_obs).float()), -1)
+
+
+class Views:
+ """The student's cameras: ``SO101Renderer`` (Newton backend; the study's Madrona default is not part of this
+ release) for up to num_worlds states per call. ``render(q, cube_pos, cube_quat, goal_pose[n, 3]) -> uint8
+ [n, C, H, W, 3]`` on cuda."""
+
+ def __init__(self, num_worlds, res=RES, cameras=CAMERAS, backend="newton", top_eye=TOP_EYE, top_target=TOP_TARGET,
+ shadows=True, goal="plate"):
+ from nedm.render.so101 import SO101Renderer
+ self.r = SO101Renderer(int(num_worlds), width=int(res), height=int(res), backend=backend, cameras=tuple(cameras),
+ top_eye=tuple(top_eye), top_target=tuple(top_target), shadows=shadows, goal=goal)
+ self.num_worlds, self.res, self.cameras = int(num_worlds), int(res), tuple(cameras)
+ self.calls, self.views, self.seconds = 0, 0, 0.0
+
+ @torch.no_grad()
+ def render(self, q, cube_pos, cube_quat, goal_pose):
+ import time
+ t0 = time.time()
+ out = []
+ for s in range(0, q.shape[0], self.num_worlds):
+ e = s + self.num_worlds
+ out.append(self.r.render(q[s:e], cube_pos[s:e], cube_quat[s:e], goal_pose[s:e]))
+ rgb = torch.cat(out) if len(out) > 1 else out[0]
+ self.calls += 1
+ self.views += q.shape[0] * len(self.cameras)
+ self.seconds += time.time() - t0
+ return rgb
+
+
+def to_input(rgb, shift_px=0, gen=None):
+ """uint8 [n, C, H, W, 3] -> float [n, C, 3, H, W], ImageNet-normalised; optional random shift (training only)."""
+ x = rgb.permute(0, 1, 4, 2, 3).float().div_(255.0)
+ n, C, _, H, W = x.shape
+ if shift_px:
+ x = random_shift(x.reshape(n * C, 3, H, W), shift_px, gen).reshape(n, C, 3, H, W)
+ m = torch.tensor(IMAGENET_MEAN, device=x.device).view(1, 1, 3, 1, 1)
+ s = torch.tensor(IMAGENET_STD, device=x.device).view(1, 1, 3, 1, 1)
+ return (x - m) / s
+
+
+def random_shift(x, pad, gen=None):
+ """DrQ random shift: replicate-pad by ``pad`` and crop back at a random integer offset per image ([N, 3, H, W])."""
+ N, _, H, W = x.shape
+ xp = F.pad(x, (pad, pad, pad, pad), mode="replicate")
+ ox = torch.randint(0, 2 * pad + 1, (N,), device=x.device, generator=gen)
+ oy = torch.randint(0, 2 * pad + 1, (N,), device=x.device, generator=gen)
+ iy = (oy[:, None] + torch.arange(H, device=x.device)[None]).clamp_max(H + 2 * pad - 1) # [N, H]
+ ix = (ox[:, None] + torch.arange(W, device=x.device)[None]).clamp_max(W + 2 * pad - 1) # [N, W]
+ b = torch.arange(N, device=x.device)[:, None, None]
+ return xp.permute(0, 2, 3, 1)[b, iy[:, :, None], ix[:, None, :]].permute(0, 3, 1, 2)
+
+
+def sustain_place_labels(d):
+ """Training targets with the PLACE trigger held through the CARRY line that precedes it: for every decision in mode
+ hold with a[4] > 0 (the expert's PLACE trigger, taken at rest), the contiguous earlier decisions of the same
+ episode in mode hold with a moving decoder target (|target velocity| or |yaw rate| > 1e-6: a CARRY line runs)
+ get a[4] = +1. The decoder does not read a[4] while a CARRY line runs (no PLACE, no arming change from a value
+ > 0), so the expert's executed episode is unchanged; the label no longer flips between the line's last decision
+ (target speed p50 13 mm/s, p10 0.8 mm/s in the MuJoCo demos) and the first decision at rest (0), which the
+ student cannot tell apart (measured 2026-10-11: the v1 student never triggered a PLACE). -> action array copy."""
+ from nedm.so101_policy.decoder import M
+ a = np.array(d["action"], copy=True)
+ mode = d["mode"].astype(np.int64)
+ dec = d["dec_obs"]
+ moving = (mode == M["hold"]) & ((np.linalg.norm(dec[:, 5:8], axis=1) > 1e-6) | (np.abs(dec[:, 8]) > 1e-6))
+ trig = np.flatnonzero((mode == M["hold"]) & (a[:, 4] > 0))
+ ep = d["ep_index"]
+ for k in trig:
+ j = k - 1
+ while j >= 0 and ep[j] == ep[k] and moving[j]:
+ a[j, 4] = 1.0
+ j -= 1
+ return a
+
+
+class DemoSet:
+ """Demo files (``demos.collect`` output) on one device: the successful episodes (``success_only``), split by episode
+ into train / validation (``val_frac``, seeded), at most ``max_episodes`` (the first ones after a seeded shuffle);
+ plus every episode of DAgger files (meta ``dagger``; training only). ``sustain_place``: ``sustain_place_labels``."""
+
+ def __init__(self, paths, device="cuda", chunk=20, success_only=True, max_episodes=0, val_frac=0.05, seed=0,
+ sustain_place=False, privileged=False):
+ if isinstance(paths, (str, Path)):
+ paths = [paths]
+ files = [D.load(p) for p in paths]
+ self.meta = [f["meta"] for f in files]
+ decs = {json.dumps(m.get("decoder_cfg", {}), sort_keys=True) for m in self.meta}
+ if len(decs) > 1:
+ raise ValueError(f"demo files with different decoder configs: {decs}")
+ self.decoder_cfg = self.meta[0].get("decoder_cfg", {})
+ keys = set.intersection(*[set(f) for f in files]) - {"meta"}
+ d = D.concat([{k: v for k, v in f.items() if k in keys} for f in files])
+ E = len(d["ep_end"])
+ # DAgger files (meta "dagger"): every episode (expert labels on the student's states); demo files: successes
+ dag = np.concatenate([np.full(len(f["ep_end"]), bool(f["meta"].get("dagger", False))) for f in files])
+ keep = d["ep_success"].astype(bool) if success_only else np.ones(E, bool)
+ self.dagger_eps = int(dag.sum())
+ # expert-demo episodes: seeded shuffle, the first max_episodes, val_frac of them for validation; DAgger
+ # episodes: all of them, training only (so the demo split is the same in every DAgger round)
+ ep_ids = np.flatnonzero(keep & ~dag)
+ rng = np.random.default_rng(int(seed))
+ ep_ids = ep_ids[rng.permutation(len(ep_ids))]
+ if max_episodes:
+ ep_ids = ep_ids[: int(max_episodes)]
+ n_val = int(round(val_frac * len(ep_ids)))
+ self.val_eps = np.sort(ep_ids[:n_val])
+ self.train_eps = np.sort(np.concatenate([ep_ids[n_val:], np.flatnonzero(dag)]))
+ self.chunk, self.dev = int(chunk), torch.device(device)
+ t = lambda x, dt=torch.float32: torch.as_tensor(np.ascontiguousarray(x), dtype=dt, device=self.dev) # noqa
+ self.q, self.cube_pos, self.cube_quat = t(d["q"]), t(d["cube_pos"]), t(d["cube_quat"])
+ self.state = proprio(self.q, t(d["dec_obs"]))
+ act = sustain_place_labels(d) if sustain_place else d["action"]
+ self.relabelled = int((act[:, 4] != d["action"][:, 4]).sum())
+ self.action = t(act)
+ self.ep_index = t(d["ep_index"], torch.long)
+ self.t = t(d["t"], torch.long)
+ self.ep_start = t(d["ep_start"], torch.long)
+ self.ep_len = t(d["ep_length"], torch.long)
+ self.goal_pose = torch.cat((t(d["ep_goal_xy"]), t(d["ep_goal_yaw"])[:, None]), -1) # [E, 3]
+ self.goal = goal_vec(d["ep_goal_xy"], d["ep_goal_yaw"]).to(self.dev) # [E, 4]
+ self.privileged = bool(privileged) # ablation: the goal vector also holds the true cube state
+ self.priv = cube_vec(self.cube_pos, self.cube_quat).to(self.dev) if self.privileged else None
+ rows = lambda eps: np.concatenate([np.arange(d["ep_start"][e], d["ep_start"][e] + d["ep_length"][e]) # noqa
+ for e in eps]) if len(eps) else np.zeros(0, np.int64)
+ self.train_rows = t(rows(self.train_eps), torch.long)
+ self.val_rows = t(rows(self.val_eps), torch.long)
+ self.n_train_eps, self.n_val_eps = len(self.train_eps), len(self.val_eps)
+
+ def stats(self, state_floor=1e-2, action_floor=5e-2):
+ """Mean / std of state, goal and action over the training rows (std floored)."""
+ r = self.train_rows
+ out = {}
+ g = self.goal[self.ep_index[r]]
+ if self.privileged:
+ g = torch.cat((g, self.priv[r]), -1)
+ for k, x, fl in (("state", self.state[r], state_floor), ("goal", g, state_floor),
+ ("action", self.action[r], action_floor)):
+ out[f"{k}_mean"] = x.mean(0).cpu()
+ out[f"{k}_std"] = x.std(0).clamp_min(fl).cpu()
+ return out
+
+ def sample(self, n, gen=None, split="train"):
+ rows = self.train_rows if split == "train" else self.val_rows
+ return rows[torch.randint(len(rows), (int(n),), device=self.dev, generator=gen)]
+
+ def batch(self, rows):
+ """Rows [n] -> dict: q, cube_pos, cube_quat, goal_pose [n, 3] (render inputs), state [n, 30], goal [n, 4],
+ action [n, chunk, 6], action_is_pad [n, chunk]."""
+ e = self.ep_index[rows]
+ k = torch.arange(self.chunk, device=self.dev)
+ end = self.ep_start[e] + self.ep_len[e] # one past the episode's last row
+ idx = rows[:, None] + k[None]
+ pad = idx >= end[:, None]
+ idx = torch.minimum(idx, (end - 1)[:, None])
+ return dict(q=self.q[rows], cube_pos=self.cube_pos[rows], cube_quat=self.cube_quat[rows],
+ goal_pose=self.goal_pose[e], state=self.state[rows],
+ goal=torch.cat((self.goal[e], self.priv[rows]), -1) if self.privileged else self.goal[e],
+ action=self.action[idx],
+ action_is_pad=pad)
+
diff --git a/so101_pick_place/code/src/nedm/so101_policy/vision/demos.py b/so101_pick_place/code/src/nedm/so101_policy/vision/demos.py
new file mode 100644
index 0000000000000000000000000000000000000000..61385bab5d8599d40f81a2e562b4d8ed250427c2
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/vision/demos.py
@@ -0,0 +1,253 @@
+"""Expert demonstrations for the camera student, stored as STATES (the images are drawn on the fly in training).
+
+The privileged FSM expert (``expert.PickPlaceExpert``) acts closed loop through ``DecoderV2`` in one world (``nrd`` =
+``GraspNrdSim`` with one checkpoint, ``mujoco`` = CPU ``MujocoWorlds``, ``kin`` = ``KinWorld``), with the episode loop
+of ``vec_env.run_episodes`` (the same loop as the gate and ``eval_policy.py``: evaluation rules, 8 s horizon, decoder
+macro seeds = task seeds). Once per decision (0.1 s), BEFORE the decision is applied, the recorder stores:
+
+| key | shape | meaning |
+|---|---|---|
+| q, qd | [6] | measured joint angles (rad) and 20 ms step-average rates (the world's state) |
+| cube_pos, cube_quat | [3], [4] | cube centre (m) and TRUE orientation w x y z (what the renderer draws) |
+| dec_obs | [24] | ``DecoderV2.observation()`` (target TCP, yaw sin / cos, target velocity, yaw rate, jaw command, armed, mode) |
+| action | [6] | the expert's decoder action in [-1, 1] (``decoder`` module docstring) |
+| mode | [] | decoder mode code (``decoder.MODES``) |
+
+Per episode: the task (seed, goal x, y, yaw), the outcome of ``task.PickPlaceTask`` (end code, success 15 / 15 and
+10 / 10, lifted, end errors, decisions, 20 ms steps). Decisions are stored for the live part of each episode only
+(``length`` decisions: the decision in which the task ended is the last one). Failures are kept (``success`` False)
+for the analysis; the dataset uses the successful episodes.
+
+Task seeds (written down here): start seeds ``DEMO_START0`` + i (500,000-599,999 reserved for the vision demos; not
+the gate 1000-2023, gate2 400,000+, campaign 300,000+, PPO 200,000+, test 900,000+ or a collector seed:
+``mujoco_env.sample_starts`` refuses those); tasks from ``data_round.make_tasks`` with family expert_base only (start
+spread 40 deg in 70 %, 60 deg in 30 %, goals ``task.sample_goals`` 6-30 cm, yaw +-30 deg), master seed
+``DEMO_MASTER``: the same start and goal distribution as the gate2 expert_base rows that the evaluation uses
+(``tasks_gate2.npz`` rows 0-306). The expert runs with ``ExpertConfig`` defaults (one speed, lift 5 cm); the task
+options of the campaign (speed class, pause, lift) are not used.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import time
+from pathlib import Path
+
+import numpy as np
+import torch
+
+DEMO_START0 = 500_000
+DEMO_MASTER = 20261301
+DECODER_CFG = {"carry_macro": True} # decoder option b2 (CARRY macro), build3_fixes.md: the default of this package
+REC_KEYS = ("q", "qd", "cube_pos", "cube_quat", "dec_obs", "action", "mode") # + "executed" for DAgger records
+EP_KEYS = ("end", "success", "success10", "lifted", "end_xy", "end_yaw", "length", "steps")
+REPO_ROOT = Path(__file__).resolve().parents[4]
+
+
+def make_tasks(n, start0=DEMO_START0, master=DEMO_MASTER, first=0, log=print):
+ """n demo tasks (module docstring) as a gate_expert.py task table (start, settled state, goal, seeds)."""
+ from nedm.so101_policy import data_round as R
+ if start0 + first + n > 600_000 or start0 < 500_000:
+ raise ValueError("vision demo start seeds are 500,000-599,999")
+ idx = np.arange(first, first + n)
+ counts = np.zeros(len(R.FAMILIES), np.int64)
+ counts[0] = first + n # family expert_base only
+ t = R.make_tasks(first + n, set_name="campaign", master=master, start0=start0, counts=counts, idx=idx, log=log)
+ t["demo_master"] = np.int64(master)
+ return t
+
+
+def load_tasks(path, idx=None, final_test=False):
+ """A task file (rows idx). Test seeds (900000+) are refused unless final_test (the final test, one evaluation per
+ final policy)."""
+ t = dict(np.load(Path(path).expanduser()))
+ n = len(t["seeds"])
+ if idx is not None:
+ t = {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in t.items()}
+ if (np.asarray(t["seeds"]) >= 900000).any() and not final_test:
+ raise ValueError("test seeds (900000+) in a demo / development task set")
+ return t
+
+
+def start_state(t, device):
+ from nedm.so101_policy.world import WorldState
+ f = lambda k: torch.as_tensor(t[f"state_{k}"], dtype=torch.float64, device=device) # noqa: E731
+ n = len(t["seeds"])
+ z = lambda *s: torch.zeros(*s, dtype=torch.bool, device=device) # noqa: E731
+ return WorldState(q=f("q"), qd=f("qd"), cube_pos=f("cube_pos"), cube_quat=f("cube_quat"), cube_v=f("cube_v"),
+ cube_w=f("cube_w"), contact=z(n, 3), arm_table=z(n), invalid=z(n))
+
+
+def make_env(world, B, device="cuda", ckpt=None, workers=0, mj_python=None, decoder_cfg=None, horizon=400,
+ members="split", record=False):
+ """The evaluation env of ``eval_policy.run_policy`` (auto reset off, ``TaskConfig.evaluation()``, overlap rules
+ off in CPU MuJoCo only) with an explicit decoder config (review R1: the decoder options travel with the data)."""
+ from nedm.so101_policy.vec_env import EnvConfig, PickPlaceVecEnv
+ ck = [str(Path(c).expanduser()) for c in ([ckpt] if isinstance(ckpt, (str, Path)) else (ckpt or []))]
+ cfg = EnvConfig(world=world, num_envs=B, device=device, ckpts=ck, members=members, auto_reset=False,
+ eval_rules=True, task=dict(horizon=int(horizon)), mj_workers=workers, mj_python=mj_python,
+ starts="", nrd_cuda_graph=True, decoder=dict(DECODER_CFG if decoder_cfg is None else decoder_cfg))
+ return PickPlaceVecEnv(cfg, record=record)
+
+
+class ExpertAct:
+ """The study's FSM expert as an act_fn of ``vec_env.run_episodes``: its module (``expert.py``) is not part of
+ this release (study branch so101-pick-place-study)."""
+
+ def __init__(self, cfg=None):
+ raise NotImplementedError("the FSM expert (nedm.so101_policy.expert) "
+ "is not part of this release (study branch so101-pick-place-study)")
+
+
+class DecisionRecorder:
+ """Wraps an act_fn (obs, env) -> (action, squashed): stores the state at every decision (module docstring) and the
+ action actually sent (squashed actions are clamped to [-1, 1]; pre-tanh ones are stored after tanh). An act_fn with
+ a ``last_label`` attribute (``rollout.DaggerAct``): ``action`` = that label, ``executed`` = the action sent."""
+
+ def __init__(self, act):
+ self.act = act
+ self.keys = REC_KEYS + (("executed",) if hasattr(act, "last_label") else ())
+ self.rec = {k: [] for k in self.keys}
+ self.live = []
+
+ def reset(self, env):
+ if hasattr(self.act, "reset"):
+ self.act.reset(env)
+ self.rec = {k: [] for k in self.keys}
+ self.live = []
+
+ def __call__(self, obs, env):
+ ws = env.ws
+ dec_obs = env.dec.observation()
+ a, sq = self.act(obs, env)
+ a_sent = a.clamp(-1.0, 1.0) if sq else torch.tanh(a)
+ r = self.rec
+ r["q"].append(ws.q.float().cpu())
+ r["qd"].append(ws.qd.float().cpu())
+ r["cube_pos"].append(ws.cube_pos.float().cpu())
+ r["cube_quat"].append(ws.cube_quat.float().cpu())
+ r["dec_obs"].append(dec_obs.float().cpu())
+ if "executed" in r:
+ r["action"].append(self.act.last_label.float().cpu())
+ r["executed"].append(a_sent.float().cpu())
+ else:
+ r["action"].append(a_sent.float().cpu())
+ r["mode"].append(env.dec.mode.to(torch.int8).cpu())
+ self.live.append((env.task.tr.end == 0).cpu())
+ return a, sq
+
+ def arrays(self):
+ """-> dict of [B, K, ...] numpy arrays (K = decisions taken by the loop) and live [B, K]."""
+ out = {k: torch.stack(v, 1).numpy() for k, v in self.rec.items()}
+ out["live"] = torch.stack(self.live, 1).numpy()
+ return out
+
+
+def pack(per_dec, ep, tasks):
+ """Flatten the live decisions of every episode: -> dict with per-decision arrays [N, ...], per-episode arrays [E],
+ ``ep_start`` [E] (row of the first decision) and ``ep_index`` [N] / ``t`` [N] (episode, decision index)."""
+ B = len(ep["end"])
+ length = np.asarray(ep["length"], np.int64)
+ live = per_dec["live"]
+ K = live.shape[1]
+ if (length > K).any():
+ raise RuntimeError("episode longer than the recorded decisions")
+ # the live part is the prefix of each episode
+ for b in range(B):
+ if not live[b, : length[b]].all():
+ raise RuntimeError(f"episode {b}: live mask is not a prefix of length {length[b]}")
+ rows_b = np.repeat(np.arange(B), length)
+ rows_t = np.concatenate([np.arange(n) for n in length]) if B else np.zeros(0, np.int64)
+ out = {k: per_dec[k][rows_b, rows_t] for k in REC_KEYS + ("executed",) if k in per_dec}
+ out["ep_index"], out["t"] = rows_b.astype(np.int32), rows_t.astype(np.int16)
+ out["ep_start"] = np.concatenate([[0], np.cumsum(length)[:-1]]).astype(np.int64)
+ for k in EP_KEYS:
+ out[f"ep_{k}"] = np.asarray(ep[k])
+ out["ep_seed"] = np.asarray(tasks["seeds"], np.int64)
+ out["ep_goal_xy"] = np.asarray(tasks["goal_xy"], np.float32)
+ out["ep_goal_yaw"] = np.asarray(tasks["goal_yaw"], np.float32)
+ return out
+
+
+def source_hashes():
+ files = ["src/nedm/so101_policy/" + f for f in ("decoder.py", "expert.py", "task.py", "vec_env.py", "kin.py",
+ "nrd_sim.py", "mujoco_env.py", "kin_world.py", "vision/demos.py")]
+ return {f: hashlib.sha256((REPO_ROOT / f).read_bytes()).hexdigest()[:16] for f in files if (REPO_ROOT / f).exists()}
+
+
+@torch.no_grad()
+def collect(tasks, world, ckpt=None, device="cuda", workers=0, mj_python=None, decoder_cfg=None, expert_cfg=None,
+ horizon=400, batch=0, log=print):
+ """Expert episodes on all tasks in one world -> packed dict (``pack``) + meta. batch: worlds per env (0 = all)."""
+ from nedm.so101_policy.vec_env import run_episodes
+ n = len(tasks["seeds"])
+ batch = int(batch) or n
+ code = source_hashes() # the code at the start of the run
+ parts, t0, steps = [], time.time(), 0
+ for s in range(0, n, batch):
+ idx = np.arange(s, min(n, s + batch))
+ t = {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
+ B = len(idx)
+ env = make_env(world, B, device, ckpt, workers, mj_python, decoder_cfg, horizon)
+ dev = env.dev
+ rec = DecisionRecorder(ExpertAct(expert_cfg))
+ g = lambda k: torch.as_tensor(t[k], dtype=torch.float64, device=dev) # noqa: E731
+ mj_start = dict(q=t["start_q"], cube_pos=t["start_cube_pos"], cube_quat=t["start_cube_quat"])
+ ep = run_episodes(env, rec, start_state(t, dev), g("goal_xy"), g("goal_yaw"),
+ torch.as_tensor(t["seeds"], dtype=torch.long, device=dev),
+ mj_start=mj_start if world == "mujoco" else None, reset_hook=rec.reset, log=None)
+ steps += env.world_steps
+ env.close()
+ parts.append(pack(rec.arrays(), ep, t))
+ log(f" {world}: tasks {s}-{s + B - 1} done, success {ep['success'].mean() * 100:.1f} %, "
+ f"{time.time() - t0:.0f} s")
+ out = concat(parts)
+ meta = dict(world=world, ckpt=str(ckpt), n_tasks=n, wall_s=time.time() - t0, world_steps=int(steps),
+ decoder_cfg=dict(DECODER_CFG if decoder_cfg is None else decoder_cfg), expert_cfg=dict(expert_cfg or {}),
+ horizon=int(horizon), device=str(device), workers=int(workers), code=code,
+ success=float(np.mean(out["ep_success"])), decisions=int(len(out["t"])))
+ out["meta"] = np.array(json.dumps(meta))
+ return out
+
+
+def concat(parts):
+ """Concatenate packed demo dicts (episode indices and starts shifted)."""
+ if len(parts) == 1:
+ return parts[0]
+ out, e0, r0 = {}, 0, 0
+ for p in parts:
+ E, N = len(p["ep_end"]), len(p["t"])
+ q = dict(p)
+ q["ep_index"] = p["ep_index"] + e0
+ q["ep_start"] = p["ep_start"] + r0
+ for k, v in q.items():
+ if k == "meta" or np.ndim(v) == 0: # meta and scalar records (tasks_file, student): the first file's
+ continue
+ out.setdefault(k, []).append(v)
+ e0, r0 = e0 + E, r0 + N
+ out = {k: np.concatenate(v) for k, v in out.items()}
+ for k, v in parts[0].items():
+ if k == "meta" or np.ndim(v) == 0:
+ out[k] = v
+ return out
+
+
+def load(path):
+ """A demo file -> dict of numpy arrays + ``meta`` (dict)."""
+ z = dict(np.load(Path(path).expanduser(), allow_pickle=False))
+ z["meta"] = json.loads(str(z["meta"])) if "meta" in z else {}
+ return z
+
+
+def summary(d):
+ """Per-file summary: episodes, success, failure causes, decisions per episode."""
+ from nedm.so101_policy.task import ENDS
+ end = d["ep_end"]
+ s = d["ep_success"].astype(bool)
+ causes = {ENDS[int(k)]: int(v) for k, v in zip(*np.unique(end[~s], return_counts=True))}
+ L = d["ep_length"]
+ return dict(episodes=int(len(end)), success=float(s.mean()), success10=float(d["ep_success10"].mean()),
+ lifted=float(d["ep_lifted"].mean()), failures=causes, decisions=int(len(d["t"])),
+ decisions_success=int(L[s].sum()), length_p50=float(np.median(L)), length_max=int(L.max()),
+ end_xy_mm_p50=float(np.median(d["ep_end_xy"][s]) * 1e3) if s.any() else None,
+ meta={k: v for k, v in d["meta"].items() if k != "code"} if isinstance(d.get("meta"), dict) else {})
diff --git a/so101_pick_place/code/src/nedm/so101_policy/vision/perstep.py b/so101_pick_place/code/src/nedm/so101_policy/vision/perstep.py
new file mode 100644
index 0000000000000000000000000000000000000000..0677da6da98c3e6ab1d66a9e4e0e75352a847089
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/vision/perstep.py
@@ -0,0 +1,426 @@
+"""Per-step camera student (build5_vision.md, student (a)): one decoder action per decision from the current images.
+
+Inputs (``teacher`` module docstring): the cameras of ``dataset.Views`` (top + wrist, 288 x 288, the goal plate drawn;
+round 1's choice), the robot-side observation entries (``teacher.ROBOT_KEYS``, 57: joints, rates, TCP / gripper axes,
+goal x, y, sin / cos 4 psi, decoder macro phase and state), mean / std normalised over the training rows.
+
+Network (``PerStepConfig``): per camera an image encoder -> spatial softmax keypoints (expected x, y of ``keypoints``
+learned 1x1-conv heat maps; Levine et al. 2016 / robomimic) + a projected global average pool; encoder ``resnet18``
+(ImageNet weights, frozen batch norm, the first ``stages`` residual stages: 3 = layer3, 256 channels, stride 16 ->
+18 x 18 at 288 px) or ``small`` (4 conv layers with GroupNorm from scratch, stride 8). Then an MLP (``hidden``, ELU)
+over [keypoints and pools of every camera, robot vector] -> the 7-dim PRE-TANH action (the PPO teacher's action space;
+the env applies tanh).
+
+Loss: masked mean squared error to the teacher's deterministic pre-tanh action, the targets clipped to
++- ``target_clip`` (tanh(3) = 0.995), per column weights ``dim_weight``, the mask = the columns the decoder reads at the
+decision (``teacher.read_mask``); rows where the decoder reads nothing are not sampled.
+"""
+from __future__ import annotations
+
+import csv
+import json
+import time
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from nedm.so101_policy.vision import dataset as V
+from nedm.so101_policy.vision import teacher as TT
+
+
+@dataclass
+class PerStepConfig:
+ encoder: str = "resnet18" # resnet18 | small
+ stages: int = 3 # resnet stages kept (1-4)
+ keypoints: int = 32 # spatial-softmax keypoints per camera
+ pool_dim: int = 64 # projected global average pool per camera (0 = off)
+ hidden: tuple = (512, 512)
+ res: int = V.RES
+ cameras: tuple = V.CAMERAS
+ act_dim: int = 7
+ robot_dim: int = 57
+ batch: int = 128
+ render_batch: int = 256
+ lr: float = 3e-4
+ lr_backbone: float = 1e-4
+ weight_decay: float = 1e-4
+ warmup: int = 300
+ cosine: bool = True # cosine decay of the learning rate to 10 % over max_steps
+ target_clip: float = 3.0
+ dim_weight: tuple = (1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
+ amp: bool = True
+ seed: int = 0
+
+ @staticmethod
+ def from_dict(d):
+ d = dict(d or {})
+ known = set(PerStepConfig.__dataclass_fields__)
+ bad = sorted(set(d) - known - {"note", "notes", "kind"})
+ if bad:
+ raise ValueError(f"unknown per-step config keys {bad}")
+ for k in ("cameras", "hidden", "dim_weight"):
+ if k in d:
+ d[k] = tuple(d[k])
+ return PerStepConfig(**{k: v for k, v in d.items() if k in known})
+
+
+class SpatialSoftmax(nn.Module):
+ """[n, C, h, w] -> [n, 2 k]: expected image coordinates (x, y in [-1, 1]) of k learned heat maps."""
+
+ def __init__(self, c_in, k):
+ super().__init__()
+ self.proj = nn.Conv2d(c_in, k, 1)
+ self.log_temp = nn.Parameter(torch.zeros(1))
+ self.k = k
+
+ def forward(self, x):
+ n, _, h, w = x.shape
+ f = self.proj(x).flatten(2).float() / self.log_temp.exp() # [n, k, h w]
+ p = torch.softmax(f, -1)
+ ys = torch.linspace(-1, 1, h, device=x.device)
+ xs = torch.linspace(-1, 1, w, device=x.device)
+ gy, gx = torch.meshgrid(ys, xs, indexing="ij")
+ ex = (p * gx.reshape(1, 1, -1)).sum(-1)
+ ey = (p * gy.reshape(1, 1, -1)).sum(-1)
+ return torch.cat((ex, ey), -1)
+
+
+def _frozen_bn_resnet18(pretrained):
+ import torchvision
+ from torchvision.ops.misc import FrozenBatchNorm2d
+ w = torchvision.models.ResNet18_Weights.IMAGENET1K_V1 if pretrained else None
+ return torchvision.models.resnet18(weights=w, norm_layer=FrozenBatchNorm2d)
+
+
+class Encoder(nn.Module):
+ """One camera: trunk -> (spatial-softmax keypoints, projected average pool)."""
+
+ def __init__(self, cfg: PerStepConfig, pretrained=True):
+ super().__init__()
+ if cfg.encoder == "resnet18":
+ r = _frozen_bn_resnet18(pretrained)
+ layers = [r.conv1, r.bn1, r.relu, r.maxpool] + [getattr(r, f"layer{i}") for i in range(1, cfg.stages + 1)]
+ self.trunk = nn.Sequential(*layers)
+ c = (64, 128, 256, 512)[cfg.stages - 1]
+ self.is_backbone = True
+ elif cfg.encoder == "small":
+ g = lambda c: nn.GroupNorm(8, c) # noqa: E731
+ self.trunk = nn.Sequential(nn.Conv2d(3, 32, 5, 2, 2), g(32), nn.ReLU(), nn.Conv2d(32, 64, 3, 2, 1), g(64),
+ nn.ReLU(), nn.Conv2d(64, 64, 3, 2, 1), g(64), nn.ReLU(),
+ nn.Conv2d(64, 128, 3, 1, 1), g(128), nn.ReLU())
+ c = 128
+ self.is_backbone = False
+ else:
+ raise ValueError(f"encoder {cfg.encoder!r}")
+ self.ssm = SpatialSoftmax(c, cfg.keypoints)
+ self.pool = nn.Linear(c, cfg.pool_dim) if cfg.pool_dim else None
+ self.out_dim = 2 * cfg.keypoints + cfg.pool_dim
+
+ def forward(self, x):
+ f = self.trunk(x)
+ out = [self.ssm(f)]
+ if self.pool is not None:
+ out.append(F.elu(self.pool(f.mean((2, 3)).float())))
+ return torch.cat(out, -1)
+
+
+class PerStepStudent(nn.Module):
+ """Images float [n, C, 3, H, W] (``dataset.to_input``) + robot vector [n, 57] -> pre-tanh action [n, 7]."""
+
+ def __init__(self, cfg: PerStepConfig, stats: dict, pretrained=True):
+ super().__init__()
+ self.cfg = cfg
+ self.enc = nn.ModuleList([Encoder(cfg, pretrained) for _ in cfg.cameras])
+ d = sum(e.out_dim for e in self.enc) + cfg.robot_dim
+ layers, k = [], d
+ for h in cfg.hidden:
+ layers += [nn.Linear(k, h), nn.ELU()]
+ k = h
+ layers.append(nn.Linear(k, cfg.act_dim))
+ self.head = nn.Sequential(*layers)
+ for k_, v in stats.items():
+ self.register_buffer(k_, torch.as_tensor(v, dtype=torch.float32).clone())
+ self.t_render = self.t_model = 0.0
+
+ def forward(self, images, robot):
+ feats = [e(images[:, i]) for i, e in enumerate(self.enc)]
+ r = ((robot - self.robot_mean) / self.robot_std).clamp(-10, 10)
+ return self.head(torch.cat(feats + [r.to(feats[0].dtype)], -1).float())
+
+ def save(self, path, **extra):
+ torch.save(dict(kind="perstep", cfg=asdict(self.cfg), state_dict=self.state_dict(),
+ stats={k: getattr(self, k).cpu() for k in ("robot_mean", "robot_std")}, **extra), path)
+
+
+def load_perstep(path, device="cuda"):
+ ck = torch.load(Path(path).expanduser(), map_location="cpu", weights_only=False)
+ cfg = PerStepConfig.from_dict(ck["cfg"])
+ st = PerStepStudent(cfg, ck["stats"], pretrained=False)
+ st.load_state_dict(ck["state_dict"])
+ return st.to(device).eval(), ck
+
+
+# ---- data -------------------------------------------------------------------------------------------------------------
+class DaggerSet:
+ """DAgger / teacher files (``teacher.collect`` output) on one device. Every episode is used (labels are the
+ teacher's actions at the visited states, failed episodes included). Validation: ``val_frac`` of the episodes of the
+ FIRST file (seeded), so the validation set is the same in every DAgger round. ``chunk`` > 1: targets of decisions
+ k .. k + chunk - 1 of the same episode (ACT), masked after the episode end and (``same_mode``) after the first
+ decoder-mode change (the mode-aware ensembler drops those predictions at execution). Sampled rows: rows where the
+ decoder reads a column (``sample_all``: every row)."""
+
+ def __init__(self, paths, device="cuda", chunk=1, val_frac=0.05, seed=0, target_clip=3.0, robot_idx=None,
+ sample_all=False, same_mode=True):
+ if isinstance(paths, (str, Path)):
+ paths = [paths]
+ files = [TT.load(p) for p in paths]
+ self.meta = [f["meta"] for f in files]
+ decs = {json.dumps(m["teacher"]["decoder_cfg"], sort_keys=True, default=str) for m in self.meta}
+ if len(decs) > 1:
+ raise ValueError("DAgger files with different decoders")
+ self.decoder_cfg = self.meta[0]["teacher"]["decoder_cfg"]
+ keys = set.intersection(*[set(f) for f in files]) - {"meta"}
+ d = TT.D.concat([{k: v for k, v in f.items() if k in keys} for f in files])
+ n_ep = [len(f["ep_end"]) for f in files]
+ E = len(d["ep_end"])
+ rng = np.random.default_rng(int(seed))
+ first = rng.permutation(n_ep[0])
+ val_eps = np.sort(first[: int(round(val_frac * n_ep[0]))])
+ is_val = np.zeros(E, bool)
+ is_val[val_eps] = True
+ self.n_val_eps, self.n_train_eps = int(is_val.sum()), int(E - is_val.sum())
+ self.chunk, self.dev = int(chunk), torch.device(device)
+ t = lambda x, dt=torch.float32: torch.as_tensor(np.ascontiguousarray(x), dtype=dt, device=self.dev) # noqa
+ from nedm.so101_policy import task as T
+ from nedm.so101_policy.vec_env import obs_layout
+ obs_rates = bool(self.meta[0]["teacher"].get("obs_rates", True))
+ self.layout = obs_layout(T.TaskConfig(obs_rates=obs_rates))
+ self.robot_idx = TT.robot_index(self.layout) if robot_idx is None else torch.as_tensor(robot_idx)
+ obs = t(d["obs"])
+ self.robot = obs[:, self.robot_idx.to(self.dev)]
+ self.q, self.cube_pos, self.cube_quat = t(d["q"]), t(d["cube_pos"]), t(d["cube_quat"])
+ self.label = t(d["label"]).clamp(-float(target_clip), float(target_clip))
+ self.mode = t(d["mode"], torch.long)
+ self.mask = TT.read_mask(d["mode"], self.label.shape[1]).to(self.dev)
+ self.src = t(d["src"], torch.long)
+ self.ep_index = t(d["ep_index"], torch.long)
+ self.ep_start = t(d["ep_start"], torch.long)
+ self.ep_len = t(d["ep_length"], torch.long)
+ self.goal_pose = torch.cat((t(d["ep_goal_xy"]), t(d["ep_goal_yaw"])[:, None]), -1)
+ self.goal = V.goal_vec(d["ep_goal_xy"], d["ep_goal_yaw"]).to(self.dev)
+ row_val = torch.as_tensor(is_val, device=self.dev)[self.ep_index]
+ use = torch.ones_like(row_val) if sample_all else self.mask.sum(-1) > 0
+ # mode segments: a new segment at every decoder-mode change and at every episode start
+ md = np.asarray(d["mode"], np.int64)
+ new_seg = np.ones(len(md), bool)
+ new_seg[1:] = (md[1:] != md[:-1]) | (np.asarray(d["ep_index"])[1:] != np.asarray(d["ep_index"])[:-1])
+ self.seg = t(np.cumsum(new_seg), torch.long)
+ self.same_mode = bool(same_mode)
+ self.train_rows = torch.nonzero(use & ~row_val).flatten()
+ self.val_rows = torch.nonzero(use & row_val).flatten()
+ self.n_rows = len(self.q)
+
+ def stats(self, floor=1e-2):
+ r = self.train_rows
+ x = self.robot[r]
+ return dict(robot_mean=x.mean(0).cpu(), robot_std=x.std(0).clamp_min(floor).cpu())
+
+ def sample(self, n, gen=None, split="train"):
+ rows = self.train_rows if split == "train" else self.val_rows
+ return rows[torch.randint(len(rows), (int(n),), device=self.dev, generator=gen)]
+
+ def batch(self, rows):
+ e = self.ep_index[rows]
+ out = dict(q=self.q[rows], cube_pos=self.cube_pos[rows], cube_quat=self.cube_quat[rows],
+ goal_pose=self.goal_pose[e], robot=self.robot[rows], goal=self.goal[e], mode=self.mode[rows])
+ if self.chunk == 1:
+ out.update(label=self.label[rows], mask=self.mask[rows])
+ return out
+ k = torch.arange(self.chunk, device=self.dev)
+ end = self.ep_start[e] + self.ep_len[e]
+ idx = rows[:, None] + k[None]
+ pad = idx >= end[:, None]
+ idx = torch.minimum(idx, (end - 1)[:, None])
+ keep = ~pad
+ if self.same_mode:
+ keep = keep & (self.seg[idx] == self.seg[rows][:, None])
+ out.update(label=self.label[idx], mask=self.mask[idx] * keep[..., None].float(), is_pad=pad)
+ return out
+
+
+# ---- training ---------------------------------------------------------------------------------------------------------
+def masked_mse(pred, label, mask, w):
+ """-> (loss, per-column sums [A], per-column counts [A])."""
+ se = (pred - label) ** 2 * mask
+ per = se.sum(0)
+ cnt = mask.sum(0)
+ loss = (per * w).sum() / cnt.sum().clamp_min(1)
+ return loss, per.detach(), cnt.detach()
+
+
+@torch.no_grad()
+def val_metrics(st, data, views, rows, bs=256):
+ """Masked MSE per column, sign agreement of the trigger a[4] (free / hold) and the abort a[6] on rows."""
+ from nedm.so101_policy.decoder import M
+ A = st.cfg.act_dim
+ per, cnt = torch.zeros(A, device=data.dev), torch.zeros(A, device=data.dev)
+ agree = {"free": [0, 0], "hold": [0, 0], "pre": [0, 0]}
+ for s in range(0, len(rows), bs):
+ b = data.batch(rows[s:s + bs])
+ img = V.to_input(views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"]))
+ with torch.autocast(data.dev.type, dtype=torch.bfloat16, enabled=st.cfg.amp):
+ p = st(img, b["robot"])
+ _, pp, cc = masked_mse(p.float(), b["label"], b["mask"], torch.ones(A, device=data.dev))
+ per += pp
+ cnt += cc
+ for name, sel, j in (("free", b["mode"] == M["free"], 4), ("hold", b["mode"] == M["hold"], 4),
+ ("pre", (b["mode"] >= M["g_brake"]) & (b["mode"] <= M["g_settle"]), A - 1)):
+ if bool(sel.any()):
+ agree[name][0] += int(((p[sel, j] > 0) == (b["label"][sel, j] > 0)).sum())
+ agree[name][1] += int(sel.sum())
+ out = {f"val_mse_a{j}": float(per[j] / cnt[j].clamp_min(1)) for j in range(A)}
+ out["val_mse"] = float(per.sum() / cnt.sum().clamp_min(1))
+ out.update({f"val_trig_agree_{k}": (v[0] / v[1] if v[1] else float("nan")) for k, v in agree.items()})
+ return out
+
+
+def train(data: DaggerSet, views, cfg: PerStepConfig, out_dir, max_steps=4000, init_from=None, log=print, val_n=2048,
+ val_every=500, log_every=100, device="cuda", extra_meta=None):
+ """Train (or fine-tune from ``init_from``: weights AND normalisation) a per-step student. Writes out_dir/{meta.json,
+ learning_curve.csv, train_summary.json, last.pt}. -> student (eval mode)."""
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ dtype_dev = torch.device(device).type
+ cuda = dtype_dev == "cuda"
+ sync = torch.cuda.synchronize if cuda else (lambda: None)
+ torch.manual_seed(cfg.seed)
+ gen = torch.Generator(device=device).manual_seed(cfg.seed)
+ if init_from:
+ st, _ = load_perstep(init_from, device)
+ st.cfg = cfg
+ else:
+ st = PerStepStudent(cfg, data.stats(), pretrained=True).to(device)
+ st.train()
+ bb = [p for e in st.enc if e.is_backbone for p in e.trunk.parameters() if p.requires_grad]
+ bb_ids = {id(p) for p in bb}
+ rest = [p for p in st.parameters() if p.requires_grad and id(p) not in bb_ids]
+ groups = [dict(params=rest, lr=cfg.lr)] + ([dict(params=bb, lr=cfg.lr_backbone)] if bb else [])
+ opt = torch.optim.AdamW(groups, weight_decay=cfg.weight_decay)
+ base = [g["lr"] for g in opt.param_groups]
+ w = torch.as_tensor(cfg.dim_weight, dtype=torch.float32, device=device)
+ vgen = torch.Generator(device=device).manual_seed(cfg.seed + 1)
+ vrows = data.sample(min(val_n, max(1, len(data.val_rows))), vgen, "val") if len(data.val_rows) else None
+ meta = dict(cfg=asdict(cfg), decoder_cfg=data.decoder_cfg, files=[m.get("file", "") for m in data.meta],
+ data_meta=data.meta, n_train_eps=data.n_train_eps, n_val_eps=data.n_val_eps,
+ train_rows=len(data.train_rows), val_rows=len(data.val_rows), init_from=str(init_from or ""),
+ robot_idx=data.robot_idx.tolist(), **(extra_meta or {}))
+ (out / "meta.json").write_text(json.dumps(meta, indent=1, default=str))
+ f = open(out / "learning_curve.csv", "w", newline="")
+ wr = None
+ t0 = time.time()
+ t_render = t_train = 0.0
+ step, samples = 0, 0
+ buf, pos = None, 0
+ agg_loss, agg_n = 0.0, 0
+ while step < max_steps:
+ if buf is None or pos + cfg.batch > cfg.render_batch:
+ tr = time.time()
+ b = data.batch(data.sample(cfg.render_batch, gen))
+ b["rgb"] = views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"])
+ sync()
+ t_render += time.time() - tr
+ buf, pos = b, 0
+ tt = time.time()
+ sl = slice(pos, pos + cfg.batch)
+ pos += cfg.batch
+ img = V.to_input(buf["rgb"][sl])
+ frac = min(1.0, (step + 1) / max(1, cfg.warmup))
+ if cfg.cosine and step >= cfg.warmup:
+ u = (step - cfg.warmup) / max(1, max_steps - cfg.warmup)
+ frac = 0.1 + 0.9 * 0.5 * (1 + np.cos(np.pi * u))
+ for g, lr0 in zip(opt.param_groups, base):
+ g["lr"] = lr0 * frac
+ with torch.autocast(dtype_dev, dtype=torch.bfloat16, enabled=cfg.amp):
+ p = st(img, buf["robot"][sl])
+ loss, _, _ = masked_mse(p.float(), buf["label"][sl], buf["mask"][sl], w)
+ opt.zero_grad(set_to_none=True)
+ loss.backward()
+ gn = torch.nn.utils.clip_grad_norm_(st.parameters(), 10.0)
+ opt.step()
+ sync()
+ t_train += time.time() - tt
+ step += 1
+ samples += cfg.batch
+ agg_loss += float(loss.detach())
+ agg_n += 1
+ do_val = vrows is not None and (step % val_every == 0 or step == max_steps)
+ if step % log_every == 0 or do_val:
+ row = dict(step=step, samples=samples, wall_min=round((time.time() - t0) / 60, 3), loss=agg_loss / agg_n,
+ grad_norm=float(gn), lr=opt.param_groups[0]["lr"], render_s=round(t_render, 1),
+ train_s=round(t_train, 1), samples_per_s=round(samples / max(time.time() - t0, 1e-9), 1),
+ gpu_gb=round(torch.cuda.max_memory_allocated() / 1e9, 2) if cuda else 0.0)
+ agg_loss, agg_n = 0.0, 0
+ if do_val:
+ st.eval()
+ row.update(val_metrics(st, data, views, vrows))
+ st.train()
+ if wr is None:
+ vk = (["val_mse"] + [f"val_mse_a{j}" for j in range(cfg.act_dim)]
+ + [f"val_trig_agree_{k}" for k in ("free", "hold", "pre")])
+ keys = [k for k in row if k not in vk] + vk
+ wr = csv.DictWriter(f, fieldnames=keys, extrasaction="ignore")
+ wr.writeheader()
+ wr.writerow(row)
+ f.flush()
+ log(json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in row.items()}))
+ st.eval()
+ st.save(out / "last.pt", step=step, samples=samples, wall_min=(time.time() - t0) / 60, decoder_cfg=data.decoder_cfg,
+ robot_idx=data.robot_idx.tolist())
+ f.close()
+ summ = dict(steps=step, samples=samples, wall_min=(time.time() - t0) / 60, render_s=t_render, train_s=t_train,
+ views=views.views, views_per_s=views.views / max(views.seconds, 1e-9))
+ (out / "train_summary.json").write_text(json.dumps(summ, indent=1))
+ log(json.dumps(summ))
+ return st
+
+
+# ---- acting -----------------------------------------------------------------------------------------------------------
+class PerStepAct:
+ """Student object for ``teacher.MixAct`` / ``teacher.evaluate``: render the world's state, robot entries of the
+ observation -> pre-tanh action [B, 7] on the env's device."""
+
+ def __init__(self, student: PerStepStudent, views, robot_idx, device="cuda"):
+ self.st, self.views, self.dev = student, views, torch.device(device)
+ self.robot_idx = torch.as_tensor(robot_idx, dtype=torch.long)
+ self.t_render = self.t_model = 0.0
+ self.calls = 0
+
+ def reset(self, env):
+ self.goal_pose = torch.cat((env.task.goal_xy, env.task.goal_yaw[:, None]), -1).to(self.dev, torch.float32)
+
+ @torch.no_grad()
+ def __call__(self, obs, env):
+ ws = env.ws
+ t0 = time.time()
+ rgb = self.views.render(ws.q.to(self.dev, torch.float32), ws.cube_pos.to(self.dev, torch.float32),
+ ws.cube_quat.to(self.dev, torch.float32), self.goal_pose)
+ img = V.to_input(rgb)
+ if self.dev.type == "cuda":
+ torch.cuda.synchronize()
+ t1 = time.time()
+ robot = obs.to(self.dev, torch.float32)[:, self.robot_idx.to(self.dev)]
+ out = []
+ for s in range(0, img.shape[0], 256):
+ with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=self.st.cfg.amp):
+ out.append(self.st(img[s:s + 256], robot[s:s + 256]).float())
+ a = torch.cat(out)
+ if self.dev.type == "cuda":
+ torch.cuda.synchronize()
+ self.t_render += t1 - t0
+ self.t_model += time.time() - t1
+ self.calls += 1
+ return a.to(env.dev, torch.float64)
diff --git a/so101_pick_place/code/src/nedm/so101_policy/vision/teacher.py b/so101_pick_place/code/src/nedm/so101_policy/vision/teacher.py
new file mode 100644
index 0000000000000000000000000000000000000000..c41f1379668805c8a9d33220c1dd87749e9ff55f
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/vision/teacher.py
@@ -0,0 +1,344 @@
+"""PPO teacher + DAgger data for the camera student (build5_vision.md; round 2 of the camera-policy work).
+
+The student acts through the SAME decoder as the PPO teacher (the teacher checkpoint's resolved DecoderV2Config:
+``grasp_gate``, ``grasp_latch``, ``abort_action``, 7-dim pre-tanh action; ``configs/so101_policy/ppo/env_v2.json``), so
+a GRASP trigger outside the gate box is ignored at no cost. The teacher is a ``ppo.Policy`` (deterministic pre-tanh
+mean, the action space of the student) and is queried at ANY state from its own privileged observation (the env's
+79-dim ``task.observation``); DAgger runs in the arm's own world (``nrd``, ``mujoco`` = CPU MuJoCo, ``kin``).
+
+Per decision (0.1 s), BEFORE it is applied, ``Recorder`` stores:
+
+| key | shape | meaning |
+|---|---|---|
+| obs | [D] | the env observation of the teacher (``task.observation``: privileged and robot-side entries) |
+| q, cube_pos, cube_quat | [6], [3], [4] | render inputs (the world's state; TRUE cube orientation) |
+| label | [7] | the teacher's deterministic pre-tanh action at this state |
+| executed | [7] | the pre-tanh action actually sent (teacher, teacher + noise, or student) |
+| src | [] int8 | who acted: 0 teacher, 1 teacher + noise, 2 student |
+| mode | [] int8 | decoder mode at the decision start (``decoder.MODES``) |
+
+Per episode: task seed, goal, outcome (``vec_env`` episode keys). Only the live decisions are stored (``demos.pack``
+rule: the decision in which the task ended is the last one).
+
+Student inputs (written down here): the cameras (``dataset.Views``) and the ROBOT-SIDE entries of the observation
+(``ROBOT_KEYS``: joint angles and rates, TCP and gripper axes by forward kinematics, goal x, y, sin / cos 4 psi, the
+decoder's macro phase and its 24-dim state). Not given: the cube pose / velocity / tilt, the cube in the grasp frame,
+goal - cube, yaw error, ``lifted`` and ``hold_time`` (derived from the cube state).
+
+Loss mask (``read_mask``; where the decoder reads a column at the decision start): mode free a[0:6] (a[5] = lift height
+at a GRASP trigger), pre-close GRASP (g_brake, g_descend, g_settle) a[6] (the abort; latch on), mode hold a[0:5]
+(PLACE trigger a[4]); the other macro phases read nothing.
+
+Seeds (written down here): DAgger / demo task seeds 510,000+ (``DEMO_START0``; the vision demo range 500,000-599,999,
+not the round-1 files 500,000-502,559); never the gate 1000-2023, gate2 400,000+ (development / selection rows) or the
+test 900,000+ (``check_seeds``).
+"""
+from __future__ import annotations
+
+import json
+import math
+import time
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from nedm.so101_policy.vision import demos as D
+
+DEMO_START0 = 510_000
+ROBOT_KEYS = ("q", "qd", "tcp", "grip_x", "grip_z", "goal_xy", "goal_yaw4", "macro", "decoder")
+SRC = {"teacher": 0, "noisy": 1, "student": 2}
+REC_KEYS = ("obs", "q", "cube_pos", "cube_quat", "label", "executed", "src", "mode")
+
+
+def check_seeds(seeds):
+ """Refuse training tasks with validation / test seeds (review_code_v3 N7: the R9 guard for the vision package)."""
+ from nedm.so101_policy.vec_env import reserved_seed_hits
+ h = reserved_seed_hits(seeds)
+ if h:
+ raise ValueError(f"{h} reserved (validation / test) seeds in a training task set")
+
+
+def robot_index(layout: dict) -> torch.Tensor:
+ """Indices of the robot-side observation entries (``ROBOT_KEYS``) in a ``vec_env.obs_layout``."""
+ return torch.cat([torch.arange(layout[k].start, layout[k].stop) for k in ROBOT_KEYS])
+
+
+def read_mask(mode, act_dim=7) -> torch.Tensor:
+ """[N] decoder modes -> [N, act_dim] float mask of the columns the decoder reads (module docstring)."""
+ from nedm.so101_policy.decoder import M
+ mode = torch.as_tensor(mode).long()
+ m = torch.zeros(mode.shape[0], act_dim)
+ free = mode == M["free"]
+ pre = (mode == M["g_brake"]) | (mode == M["g_descend"]) | (mode == M["g_settle"])
+ hold = mode == M["hold"]
+ m[free, :6] = 1.0
+ m[hold, :5] = 1.0
+ if act_dim > 6:
+ m[pre, 6] = 1.0
+ return m
+
+
+def hash_normal(seed, counter, n, stream0=0):
+ """Counter-based standard normals [B, n] of int64 seeds [B] (``gate_expert.hash_normal``)."""
+ from nedm.so101_policy.decoder import hash_uniform
+ cnt = torch.full_like(seed, int(counter))
+ out = []
+ for j in range(n):
+ u1 = hash_uniform(seed, cnt, stream0 + 2 * j + 1)
+ u2 = hash_uniform(seed, cnt, stream0 + 2 * j + 2)
+ out.append(torch.sqrt(-2.0 * torch.log1p(-u1)) * torch.cos(2 * math.pi * u2))
+ return torch.stack(out, -1)
+
+
+class Teacher:
+ """A PPO checkpoint (``ppo.load_policy(with_env=True)``) as the label source: ``act(obs)`` -> deterministic pre-tanh
+ mean [B, A] (float32, on the obs device). ``decoder_cfg`` / ``obs_rates``: the training env's records (review R1)."""
+
+ def __init__(self, path, device="cuda"):
+ from nedm.so101_policy.ppo import load_policy, sha256
+ self.path = str(Path(path).expanduser())
+ self.pol, rec = load_policy(self.path, device, with_env=True)
+ if rec is None:
+ raise ValueError(f"{path}: no env record (needs a checkpoint written after 2026-10-11 23:00)")
+ self.rec = rec
+ self.dev = torch.device(device)
+ self.decoder_cfg = {k: (tuple(v) if isinstance(v, list) else v) for k, v in rec["decoder"].items()}
+ self.obs_rates = bool(rec["task"]["obs_rates"])
+ self.act_dim = int(self.pol.kwargs["act_dim"])
+ self.obs_dim = int(self.pol.kwargs["obs_dim"])
+ self.std = self.pol.std.detach().float()
+ self.sha256 = sha256(self.path)
+ self.files = {k: rec["env"][k] for k in ("geom_path", "kin_points")
+ if rec["env"].get(k) and Path(rec["env"][k]).expanduser().exists()}
+
+ @torch.no_grad()
+ def act(self, obs):
+ return self.pol.act_inference(obs.to(self.dev, torch.float32)).float().to(obs.device)
+
+ def info(self):
+ return dict(path=self.path, sha256=self.sha256, decoder_cfg={k: v for k, v in self.decoder_cfg.items()},
+ obs_rates=self.obs_rates, act_dim=self.act_dim)
+
+
+def make_env(world, B, teacher: Teacher, device="cuda", nrd_ckpt=None, workers=0, mj_python=None, horizon=400,
+ members="split", record=False):
+ """The evaluation env of ``eval_policy.run_policy`` for the teacher's decoder and observation: auto reset off,
+ ``TaskConfig.evaluation()`` (15 mm / 15 deg success), overlap rules off in CPU MuJoCo only, 8 s horizon."""
+ from nedm.so101_policy.vec_env import EnvConfig, PickPlaceVecEnv
+ ck = [str(Path(c).expanduser()) for c in ([nrd_ckpt] if isinstance(nrd_ckpt, (str, Path)) else (nrd_ckpt or []))]
+ cfg = EnvConfig(world=world, num_envs=B, device=device, ckpts=ck, members=members, auto_reset=False,
+ eval_rules=True, task=dict(horizon=int(horizon), obs_rates=teacher.obs_rates), mj_workers=workers,
+ mj_python=mj_python, starts="", nrd_cuda_graph=True, decoder=dict(teacher.decoder_cfg),
+ **teacher.files)
+ env = PickPlaceVecEnv(cfg, record=record)
+ if env.num_obs != teacher.obs_dim or env.num_actions != teacher.act_dim:
+ raise RuntimeError(f"teacher {teacher.obs_dim} obs / {teacher.act_dim} actions vs env {env.num_obs} / "
+ f"{env.num_actions}")
+ return env
+
+
+class MixAct:
+ """act_fn of ``vec_env.run_episodes``: label = the teacher's deterministic pre-tanh action at the current state;
+ executed = the teacher's (with probability ``beta`` per world and decision, counter-based hash of the task seed,
+ the decision index and ``seed``) or the student's (``student``: an object with ``reset(env)`` and
+ ``__call__(obs, env) -> pre-tanh [B, A]``). ``noise`` > 0: the teacher's executed action gets Gaussian noise of
+ noise x the teacher's own std on the move columns a[0:4] (DART-style; counter-based normals; not on the triggers,
+ the lift height or the abort). Pre-tanh actions out (``squashed`` False)."""
+
+ def __init__(self, teacher: Teacher, student=None, beta=1.0, noise=0.0, seed=0):
+ if student is None and beta < 1.0:
+ raise ValueError("beta < 1 needs a student")
+ self.t, self.s, self.beta, self.noise, self.seed = teacher, student, float(beta), float(noise), int(seed)
+ self.k, self.seeds = 0, None
+ self.last_label = self.last_src = None
+
+ def reset(self, env):
+ if self.s is not None:
+ self.s.reset(env)
+ self.k = 0
+ self.seeds = env.task_seed.clone().long() * 1_000_003 + 7919 * self.seed + 17
+
+ @torch.no_grad()
+ def __call__(self, obs, env):
+ lab = self.t.act(obs.to(env.dev)).to(env.dev, torch.float64)
+ a_t = lab
+ src_t = torch.full((env.B,), SRC["teacher"], dtype=torch.int8, device=env.dev)
+ if self.noise > 0:
+ eps = hash_normal(self.seeds.to(env.dev), self.k, 4).to(lab)
+ a_t = lab.clone()
+ a_t[:, :4] = lab[:, :4] + self.noise * self.t.std[:4].to(lab) * eps
+ src_t[:] = SRC["noisy"]
+ if self.beta >= 1.0:
+ a, src = a_t, src_t
+ else:
+ s = self.s(obs, env).to(env.dev, torch.float64)
+ if self.beta <= 0.0:
+ a, src = s, torch.full_like(src_t, SRC["student"])
+ else:
+ from nedm.so101_policy.decoder import hash_uniform
+ u = hash_uniform(self.seeds.to(env.dev), torch.full_like(self.seeds, self.k).to(env.dev), 99)
+ use_t = u < self.beta
+ a = torch.where(use_t[:, None], a_t, s)
+ src = torch.where(use_t, src_t, torch.full_like(src_t, SRC["student"]))
+ self.k += 1
+ self.last_label, self.last_src = lab, src
+ return a, False
+
+
+class Recorder:
+ """Wraps a ``MixAct``: stores the state, the teacher's label and the executed action at every decision (module
+ docstring)."""
+
+ def __init__(self, act: MixAct):
+ self.act = act
+ self.rec = {k: [] for k in REC_KEYS}
+ self.live = []
+
+ def reset(self, env):
+ self.act.reset(env)
+ self.rec = {k: [] for k in REC_KEYS}
+ self.live = []
+
+ def __call__(self, obs, env):
+ ws = env.ws
+ mode = env.dec.mode.to(torch.int8).cpu()
+ a, sq = self.act(obs, env)
+ r = self.rec
+ r["obs"].append(obs.float().cpu())
+ r["q"].append(ws.q.float().cpu())
+ r["cube_pos"].append(ws.cube_pos.float().cpu())
+ r["cube_quat"].append(ws.cube_quat.float().cpu())
+ r["label"].append(self.act.last_label.float().cpu())
+ r["executed"].append(a.float().cpu())
+ r["src"].append(self.act.last_src.cpu())
+ r["mode"].append(mode)
+ self.live.append((env.task.tr.end == 0).cpu())
+ return a, sq
+
+ def arrays(self):
+ out = {k: torch.stack(v, 1).numpy() for k, v in self.rec.items()}
+ out["live"] = torch.stack(self.live, 1).numpy()
+ return out
+
+
+def pack(per_dec, ep, tasks):
+ """Live decisions of every episode -> flat arrays (``demos.pack`` layout with this module's keys)."""
+ B = len(ep["end"])
+ length = np.asarray(ep["length"], np.int64)
+ live = per_dec["live"]
+ for b in range(B):
+ if not live[b, : length[b]].all():
+ raise RuntimeError(f"episode {b}: live mask is not a prefix of length {length[b]}")
+ rows_b = np.repeat(np.arange(B), length)
+ rows_t = np.concatenate([np.arange(n) for n in length]) if B else np.zeros(0, np.int64)
+ out = {k: per_dec[k][rows_b, rows_t] for k in REC_KEYS}
+ out["ep_index"], out["t"] = rows_b.astype(np.int32), rows_t.astype(np.int16)
+ out["ep_start"] = np.concatenate([[0], np.cumsum(length)[:-1]]).astype(np.int64)
+ for k in D.EP_KEYS:
+ out[f"ep_{k}"] = np.asarray(ep[k])
+ out["ep_seed"] = np.asarray(tasks["seeds"], np.int64)
+ out["ep_goal_xy"] = np.asarray(tasks["goal_xy"], np.float32)
+ out["ep_goal_yaw"] = np.asarray(tasks["goal_yaw"], np.float32)
+ return out
+
+
+def _subset(tasks, idx):
+ n = len(tasks["seeds"])
+ return {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
+
+
+@torch.no_grad()
+def collect(tasks, world, teacher: Teacher, student=None, beta=1.0, noise=0.0, seed=0, device="cuda", nrd_ckpt=None,
+ workers=0, mj_python=None, horizon=400, batch=256, members="split", log=print, meta_extra=None):
+ """DAgger / teacher episodes on all tasks in one world -> packed dict (``pack``) + ``meta`` (json string)."""
+ from nedm.so101_policy.vec_env import run_episodes
+ check_seeds(tasks["seeds"])
+ n = len(tasks["seeds"])
+ batch = int(batch) or n
+ t0, steps, parts = time.time(), 0, []
+ t_student = 0.0
+ for s0 in range(0, n, batch):
+ idx = np.arange(s0, min(n, s0 + batch))
+ t = _subset(tasks, idx)
+ env = make_env(world, len(idx), teacher, device, nrd_ckpt, workers, mj_python, horizon, members)
+ dev = env.dev
+ act = MixAct(teacher, student, beta, noise, seed)
+ rec = Recorder(act)
+ g = lambda k: torch.as_tensor(t[k], dtype=torch.float64, device=dev) # noqa: E731
+ mj_start = dict(q=t["start_q"], cube_pos=t["start_cube_pos"], cube_quat=t["start_cube_quat"])
+ ep = run_episodes(env, rec, D.start_state(t, dev), g("goal_xy"), g("goal_yaw"),
+ torch.as_tensor(t["seeds"], dtype=torch.long, device=dev),
+ mj_start=mj_start if world == "mujoco" else None, reset_hook=rec.reset, log=None)
+ steps += env.world_steps
+ env.close()
+ parts.append(pack(rec.arrays(), ep, t))
+ if student is not None and hasattr(student, "t_render"):
+ t_student = student.t_render + student.t_model
+ log(f" collect {world} beta {beta} noise {noise}: tasks {s0}-{s0 + len(idx) - 1}, success "
+ f"{ep['success'].mean() * 100:.1f} %, {time.time() - t0:.0f} s")
+ del env, act, rec
+ out = D.concat(parts)
+ meta = dict(world=world, nrd_ckpt=str(nrd_ckpt), teacher=teacher.info(), n_tasks=n, beta=float(beta),
+ noise=float(noise), seed=int(seed), horizon=int(horizon), batch=batch, wall_s=time.time() - t0,
+ world_steps=int(steps), student_s=float(t_student), success=float(np.mean(out["ep_success"])),
+ decisions=int(len(out["t"])), seeds=[int(tasks["seeds"][0]), int(tasks["seeds"][-1])],
+ code=D.source_hashes(), **(meta_extra or {}))
+ out["meta"] = np.array(json.dumps(meta, default=str))
+ return out
+
+
+@torch.no_grad()
+def evaluate(student, tasks, world, teacher: Teacher, device="cuda", nrd_ckpt=None, workers=0, mj_python=None,
+ horizon=400, record=True, members="split", log=print, policy_path="", with_labels=True):
+ """The student (beta 0) on all tasks in one world -> dict in the ``eval_policy.py run`` format (+ timing, the
+ teacher's labels on the student's states when ``with_labels``: agreement diagnostics)."""
+ from nedm.so101_policy.vec_env import run_episodes
+ B = len(tasks["seeds"])
+ t0 = time.time()
+ env = make_env(world, B, teacher, device, nrd_ckpt, workers, mj_python, horizon, members, record)
+ dev = env.dev
+ act = MixAct(teacher, student, beta=0.0)
+ rec = Recorder(act) if with_labels else act
+ g = lambda k: torch.as_tensor(tasks[k], dtype=torch.float64, device=dev) # noqa: E731
+ mj_start = dict(q=tasks["start_q"], cube_pos=tasks["start_cube_pos"], cube_quat=tasks["start_cube_quat"])
+ r = run_episodes(env, rec, D.start_state(tasks, dev), g("goal_xy"), g("goal_yaw"),
+ torch.as_tensor(tasks["seeds"], dtype=torch.long, device=dev),
+ mj_start=mj_start if world == "mujoco" else None, reset_hook=rec.reset, log=log)
+ out = dict(env.records() if record else {})
+ resolved = env.resolved()
+ steps = env.world_steps
+ env.close()
+ if with_labels:
+ p = pack(rec.arrays(), r, tasks)
+ out.update({f"lab_{k}": p[k] for k in ("label", "executed", "mode", "ep_index", "t")})
+ out.update(end=r["end"], success=r["success"], success10=r["success10"], lifted=r["lifted"], end_xy=r["end_xy"],
+ end_yaw=r["end_yaw"], t_end=r["steps"], ret=r["ret"], length=r["length"], seeds=np.asarray(tasks["seeds"]),
+ box_log=np.zeros(B, bool), world=np.array(world), config=np.array("vision_dagger"), decoder=np.array("v2"),
+ ckpt=np.array(str(nrd_ckpt)), wall_s=np.float64(time.time() - t0), device=np.array(str(dev)),
+ world_steps=np.int64(steps), phase=np.zeros_like(out["mode"]) if record else np.zeros(0),
+ label=np.zeros_like(out["mode"]) if record else np.zeros(0), phase_names=np.array(["policy"]),
+ train_rules=np.bool_(False), assist=np.bool_(False), stochastic=np.bool_(False), noise_seed=np.int64(0),
+ policy=np.array(str(policy_path)), env_resolved=np.array(json.dumps(resolved, default=str)),
+ teacher=np.array(json.dumps(teacher.info(), default=str)),
+ render_s=np.float64(getattr(student, "t_render", 0.0)), model_s=np.float64(getattr(student, "t_model", 0.0)),
+ model_calls=np.int64(getattr(student, "calls", 0)))
+ return out
+
+
+def load(path):
+ z = dict(np.load(Path(path).expanduser(), allow_pickle=False))
+ z["meta"] = json.loads(str(z["meta"])) if "meta" in z else {}
+ return z
+
+
+def summary(d):
+ """Per-file summary: episodes, success, failure causes, decisions, who acted, label statistics."""
+ from nedm.so101_policy.task import ENDS
+ end = d["ep_end"]
+ s = d["ep_success"].astype(bool)
+ causes = {ENDS[int(k)]: int(v) for k, v in zip(*np.unique(end[~s], return_counts=True))}
+ src = {k: int((d["src"] == v).sum()) for k, v in SRC.items()}
+ return dict(episodes=int(len(end)), success=float(s.mean()), lifted=float(d["ep_lifted"].mean()), failures=causes,
+ decisions=int(len(d["t"])), src=src,
+ meta={k: v for k, v in d["meta"].items() if k not in ("code",)} if isinstance(d.get("meta"), dict) else {})
diff --git a/so101_pick_place/code/src/nedm/so101_policy/vision/tray.py b/so101_pick_place/code/src/nedm/so101_policy/vision/tray.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7aa263e1aa2c80b72c8db43e7facd336a49bf65
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/vision/tray.py
@@ -0,0 +1,1307 @@
+"""Tray student (build8_tray_student.md): a camera policy whose ONLY inputs are the top and wrist camera images and the
+arm's joint angles q (6) and joint rates qdot (6), and whose output is a chunk of absolute joint targets (5 arm joints +
+jaw) every 20 ms: deployable on a real SO101 without privileged information. The goal pose is shown as a TRAY drawn on
+the table (``render.so101`` goal "tray"; visual only, no collision in MuJoCo or the NRD); the student reads it from the
+images.
+
+Teacher: a state PPO policy acting through decoder v2 (``teacher.Teacher``; its grasp gate and macro heights read the
+TRUE cube pose: teacher side only). Labels = the joint targets that the teacher + its decoder send.
+
+Joint-level episode loop (``TrayWorld.run``), one decision = 5 world steps of 20 ms, B worlds on one device:
+
+1. At each decision boundary the LABEL decoder ``lab`` (a ``DecoderV2`` with the teacher's config) is made consistent
+ with the world (below), the teacher decides from its 79-dim observation (world state + ``lab``'s state), ``lab``
+ decides with the clean action and steps 5 times with the measured q: its 5 outputs are the labels of the decision.
+2. Who drives the decision (per world): the clean teacher (``lab``'s outputs are executed), the noisy teacher (DART:
+ a driver decoder ``drv`` decides with Gaussian noise of ``noise`` x the teacher's std on the move columns a[0:4];
+ ``lab`` is re-copied from ``drv`` at every boundary, so the labels are the clean teacher's continuation from the
+ noisy state), or the student (its chunk's first ``n_exec`` targets are executed). The mix is drawn per world and
+ decision with probability ``beta`` for the teacher (counter-based hash, as ``teacher.MixAct``).
+3. Re-sync after a student decision (``resync``): the label decoder's command state is set to the student's last two
+ commands (q_cmd, step dq; in free / hold motion also the Cartesian target = FK of the command, its velocity from
+ the last two commands, the IK warm start), the jaw schedule restarts from the student's jaw command if it differs
+ from the shadow's by > 0.02 rad, and the mode is made consistent with the cube: a decoder that thinks it holds the
+ cube (hold, p_brake, p_settle, p_lower) while the cube is not held goes to free (jaw opens); a decoder before the
+ close (free, g_brake, g_descend, g_settle) while the student holds the cube goes to g_grip (then the GRASP lift by
+ the teacher's current a[5]). Macro lines keep their plan (the labels pull the command back onto the line).
+ A perfect follower is re-synced to (nearly) the shadow's own state (``tests``: labels change < 1e-3 rad).
+
+Rules (``rule_config``): the evaluation rules of the study with the decoder-free macro view (``task.step(state,
+macro=None)``) for BOTH teacher and student, so they are judged identically. The three rules that are defined by
+the decoder's macro phases only log: ``keep_out`` (no low TCP near a resting cube outside a macro), ``grasp_box`` (at
+the GRASP trigger / close) and ``cube_slide`` (a cube sliding on the table outside a macro: without the macro view it
+fired on GRASP-descent nudges, 6 of 100 teacher episodes in CPU MuJoCo on stage A, all in g_descend; a pushed cube
+must still be lifted and placed for success). Every other failure rule stays (release_high, unsupported, hold_cap,
+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
+the cube top, after a firm lift (unchanged).
+
+Records (``run(record=True)``): per decision row (boundary) the render inputs q, qd, cube pose (true orientation), who
+drove (``src`` 0 teacher, 1 noisy teacher, 2 student), the label decoder's mode, ``cont`` (= the previous decision was
+driven by the clean teacher: the label plan continues across the boundary) and the teacher's pre-tanh action; per 20
+ms step the label ``u_lab`` [6] and the executed target ``u_exe`` [6]. Only live rows / steps are packed.
+
+Student targets (``TraySet``): the chunk of the label targets u_lab[t .. t + K - 1] minus the measured q at the query
+time t (a boundary), mean / std normalised per (step, joint); element j is valid if inside the episode and (j < 5, or
+every boundary between t and t + j continues the clean teacher's plan: ``cont``).
+
+Stages (``STAGES``, the user's curriculum): A = fixed cube spot + fixed tray spot (arm start from the collector's
+start sampler), B = random cube + fixed tray, C = random cube + random tray (the PPO task distribution). Seeds
+(written down here): training tasks A 530,000+, B 540,000+, C 550,000+; development evaluation sets A 560,000-560,099,
+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
+900,000+; ``teacher.check_seeds``).
+"""
+from __future__ import annotations
+
+import csv
+import json
+import math
+import time
+from dataclasses import asdict, dataclass, replace
+from pathlib import Path
+
+import numpy as np
+import torch
+import torch.nn as nn
+
+from nedm.so101_policy.paths import DATA
+from nedm.so101_policy.vision import dataset as V
+
+CONTROL_DT = 0.02
+PAN_XY = (0.0388, 0.0)
+LOG_ONLY = ("grasp_box", "keep_out", "cube_slide")
+SRC = {"teacher": 0, "noisy": 1, "student": 2}
+
+
+def polar(r, deg):
+ a = math.radians(deg)
+ return (PAN_XY[0] + r * math.cos(a), PAN_XY[1] + r * math.sin(a))
+
+
+CUBE_A = (*polar(0.21, 30.0), math.radians(10.0)) # fixed cube spot of stage A: x, y (m), yaw (rad)
+TRAY_AB = (*polar(0.21, -30.0), math.radians(25.0)) # fixed tray spot of stages A and B
+STAGES = {
+ "A": dict(cube="fixed", tray="fixed", train0=530_000, dev0=560_000),
+ "B": dict(cube="random", tray="fixed", train0=540_000, dev0=561_000),
+ "C": dict(cube="random", tray="random", train0=550_000, dev0=562_000),
+ # real2sim HOME starts (~/so101_r2s_claude/docs/integrate.md): the arm at rest at the real robot's HOME pose
+ # (+ small per-joint noise), the cube resting at the xy / yaw of a random row of the teacher's PPO start bank, the
+ # goal by stage C's rule. Seeds: training 690,000+, development 597,000+ (fresh: --first 1000 = 598,000+).
+ "H": dict(cube="bank", tray="random", arm="home", train0=690_000, dev0=597_000),
+}
+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
+HOME_BANK = str(DATA / "rl_inputs" / "banks" / "bank_pp_split0.npz") # jt_h110's PPO start bank (production_plus split 0)
+
+
+def _home_cfg(home):
+ """HOME task options: home_deg (6 sim deg), noise_deg (U(-n, n) per joint; a number or 6), bank (start bank .npz)."""
+ h = dict(home or {})
+ bad = sorted(set(h) - {"home_deg", "noise_deg", "bank", "note", "notes"})
+ if bad:
+ raise ValueError(f"unknown HOME task keys {bad}")
+ deg = np.asarray(h.get("home_deg", HOME_SIM_DEG), np.float64)
+ noise = np.broadcast_to(np.asarray(h.get("noise_deg", 0.0), np.float64), (6,)).copy()
+ if deg.shape != (6,):
+ raise ValueError("home_deg: 6 sim joint angles (deg)")
+ return deg, noise, str(Path(h.get("bank", HOME_BANK)).expanduser())
+# Teacher-side decoder changes of this build (written down here; build8 sec. 1b-1e). A student that sees only images, q
+# and qdot cannot see the decoder's clocks: (v2) the place opening ramp kept the command below the cube-blocked jaw
+# angle for a whole decision (no visible change: the student stayed with the jaw closed); (v3) the holds before the
+# close (t_settle), after it (t_grip) and before the lowering (t_place_settle) are hidden waits and the minimum-jerk
+# close is slow. TEACHER_DECODER = v3: no waits, jaw ramps at 20 rad/s (8 steps for a full close / open with the
+# 0.09 rad step clip); round-0 students 54 / 60 % (seeds 0 / 1) on stage A. Fixing also the random grasp / place depths
+# (v4: 14 %) and the random line durations (v5: 3 %) made behaviour cloning WORSE: the teacher's random draws spread
+# the data around the nominal path (``V4_DECODER``, ``V5_DECODER`` kept for the record). The decoder's rest conditions
+# and speed / acceleration rules stay; the PPO policy is not read inside the macros. Teacher with v3 / v4 / v5: stage A
+# 100 / 100 in CPU MuJoCo and in the NRD.
+TEACHER_DECODER = {"jaw_speed": 20.0, "t_open": (0.0, 0.0), "t_close": (0.0, 0.0), "t_settle": (0.0, 0.0),
+ "t_grip": (0.0, 0.0), "t_place_settle": (0.0, 0.0)}
+V4_DECODER = {**TEACHER_DECODER, "grasp_dz": (0.001, 0.001), "place_dz": (0.0015, 0.0015)}
+V5_DECODER = {**V4_DECODER, "t_descend": (0.375, 0.375), "t_lift": (0.575, 0.575), "t_lower": (0.525, 0.525),
+ "t_retreat": (0.375, 0.375), "retreat": (0.075, 0.075)}
+DEC_STATE = ("mode", "pos", "yaw", "vel", "yrate", "v0", "vn", "w0", "wn", "tau", "tb", "fv", "fa", "fw", "fwa", "lp0",
+ "lp1", "lk", "ln", "jaw_from", "jaw_to", "jaw_k", "jaw_n", "q_des", "q_cmd", "dq", "low_off", "z_goal",
+ "h", "z_ceil", "yaw_hold0", "goal", "tilt0", "t", "seed", "draws", "episode", "hv", "hw", "hA_d", "hA_w",
+ "hA_T", "hA_tau", "hB_d", "hB_w", "hB_T", "hB_tau", "carry_on", "carry_brk", "ly0", "ly1", "ik_err",
+ "armed")
+
+
+def log_default(s):
+ print(f"[{time.strftime('%H:%M:%S')}] {s}", flush=True)
+
+
+# ---- tasks ------------------------------------------------------------------------------------------------------------
+def wrap90(a):
+ q = math.pi / 2
+ return -(((-a + q / 2) % q) - q / 2)
+
+
+def make_tasks(stage, n, first=0, dev=False, log=log_default, home=None):
+ """n tasks of a stage (module docstring), seeds = the stage's training (or ``dev``) start + first + i. Per seed:
+ rng = default_rng(seed): the cube (A: fixed spot; B: the collector's ``sample_cube`` until it is 6-30 cm from the
+ fixed tray and the needed turn |wrap90(tray yaw - cube yaw)| <= 30 deg; C: ``sample_cube``), the arm start
+ (``Scene.sample_above`` within 40 deg (70 %) or 60 deg (30 %) of the cube direction, as the expert_base family),
+ 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
+ fixed tray; C: ``task.sample_goals``, 6-30 cm, yaw +-30 deg). -> task table (gate_expert format: start_*, state_*,
+ goal_xy, goal_yaw, seeds).
+
+ Stage H (real2sim HOME starts; ``home``: ``_home_cfg`` options): the arm at ``home_deg`` + U(-noise_deg, noise_deg)
+ per joint (at rest), the cube resting flat at the xy and yaw of a random row of the start ``bank`` (redrawn with the
+ arm noise until the warm-up passes), the goal by stage C's rule; extra keys bank_index, home_deg, home_noise_deg."""
+ if STAGES[stage].get("arm") == "home":
+ return _make_home_tasks(stage, n, first, dev, log, home)
+ from nedm.contact_nrd.collect import so101_grasp as g
+ from nedm.so101_policy import task as T
+ from nedm.so101_policy.mujoco_env import RAW, _Block, _SAMPLER, reserved_seeds
+ st = STAGES[stage]
+ seeds = np.arange(n, dtype=np.int64) + (st["dev0"] if dev else st["train0"]) + int(first)
+ from nedm.so101_policy.vision.teacher import check_seeds
+ check_seeds(seeds)
+ bad = sorted(set(seeds.tolist()) & reserved_seeds())
+ if bad:
+ raise ValueError(f"seeds {bad[:5]} are collector campaign seeds")
+ key = ("block", True)
+ if key not in _SAMPLER:
+ _SAMPLER[key] = _Block(1, overlap=True)
+ blk = _SAMPLER[key]
+ s = blk.s
+ q, pos, quat, raw = np.zeros((n, 6)), np.zeros((n, 3)), np.zeros((n, 4)), np.zeros((n, RAW))
+ gxy, gyaw, spread, tries = np.zeros((n, 2)), np.zeros(n), np.zeros(n), np.zeros(n, np.int64)
+ t0 = time.time()
+ for k, seed in enumerate(seeds):
+ rng = np.random.default_rng(int(seed))
+ spread[k] = 40.0 if rng.uniform() < 0.7 else 60.0
+ while True:
+ tries[k] += 1
+ if tries[k] > 500:
+ raise RuntimeError(f"seed {seed}: no start")
+ if st["cube"] == "fixed":
+ cube, cyaw = np.array([CUBE_A[0], CUBE_A[1], s.half]), CUBE_A[2]
+ else:
+ cube, cyaw = s.sample_cube(rng)
+ if st["tray"] == "fixed":
+ d = math.hypot(cube[0] - TRAY_AB[0], cube[1] - TRAY_AB[1])
+ if not (0.06 <= d <= 0.30) or abs(wrap90(TRAY_AB[2] - cyaw)) > math.radians(30.0):
+ continue
+ a = math.degrees(math.atan2(cube[1] - PAN_XY[1], cube[0] - PAN_XY[0]))
+ try:
+ q0 = s.sample_above(rng, angle=(a - spread[k], a + spread[k]))
+ except g.PlanError:
+ continue
+ if q0 is None:
+ continue
+ c = g.resting_cube(cube, cyaw)
+ row = np.concatenate((q0, np.zeros(6), c["pos"], c["quat"], np.zeros(6)))[None]
+ res = blk.reset([0], row, warmup=True)
+ if res["code"][0] == 0 and not res["arm_table"][0] and not res["contact"][0, :2].any():
+ break
+ q[k], pos[k], quat[k], raw[k] = q0, c["pos"], c["quat"], res["raw"][0]
+ if st["tray"] == "fixed":
+ gxy[k], gyaw[k] = TRAY_AB[:2], TRAY_AB[2]
+ else:
+ gen = torch.Generator().manual_seed(int(seed) * 7 + 3)
+ cy, _ = T.cube_yaw_tilt(torch.as_tensor(raw[k:k + 1, 15:19]).float().double())
+ gg, gy = T.sample_goals(torch.as_tensor(raw[k:k + 1, 12:14]).float().double(), cy, gen)
+ gxy[k], gyaw[k] = gg[0].numpy(), float(gy[0])
+ r = raw.astype(np.float32).astype(np.float64)
+ log(f"stage {stage}: {n} tasks (seeds {seeds[0]}-{seeds[-1]}) in {time.time() - t0:.0f} s, tries p50 "
+ f"{np.median(tries):.0f}")
+ out = dict(seeds=seeds, start_q=q, start_cube_pos=pos, start_cube_quat=quat, goal_xy=gxy, goal_yaw=gyaw,
+ spread_deg=spread, tries=tries, stage=np.array(stage), dev=np.bool_(dev))
+ for name, sl in (("q", slice(0, 6)), ("qd", slice(6, 12)), ("cube_pos", slice(12, 15)), ("cube_quat", slice(15, 19)),
+ ("cube_v", slice(19, 22)), ("cube_w", slice(22, 25))):
+ out[f"state_{name}"] = r[:, sl]
+ return out
+
+
+def _make_home_tasks(stage, n, first, dev, log, home):
+ """Stage H of ``make_tasks`` (its docstring)."""
+ from nedm.contact_nrd.collect import so101_grasp as g
+ from nedm.so101_policy import task as T
+ from nedm.so101_policy.mujoco_env import RAW, _Block, _SAMPLER, reserved_seeds
+ from nedm.so101_policy.vision.teacher import check_seeds
+ st = STAGES[stage]
+ deg, noise, bank_path = _home_cfg(home)
+ seeds = np.arange(n, dtype=np.int64) + (st["dev0"] if dev else st["train0"]) + int(first)
+ check_seeds(seeds)
+ bad = sorted(set(seeds.tolist()) & reserved_seeds())
+ if bad:
+ raise ValueError(f"seeds {bad[:5]} are collector campaign seeds")
+ bank = np.load(bank_path)
+ byaw, _ = T.cube_yaw_tilt(torch.as_tensor(bank["cube_quat"]).double())
+ byaw, bxy, N = byaw.numpy(), bank["cube_pos"][:, :2].astype(np.float64), len(bank["q"])
+ key = ("block", True)
+ if key not in _SAMPLER:
+ _SAMPLER[key] = _Block(1, overlap=True)
+ blk = _SAMPLER[key]
+ half = blk.s.half
+ q, pos, quat, raw = np.zeros((n, 6)), np.zeros((n, 3)), np.zeros((n, 4)), np.zeros((n, RAW))
+ gxy, gyaw, tries, bi = np.zeros((n, 2)), np.zeros(n), np.zeros(n, np.int64), np.zeros(n, np.int64)
+ t0 = time.time()
+ for k, seed in enumerate(seeds):
+ rng = np.random.default_rng(int(seed))
+ while True:
+ tries[k] += 1
+ if tries[k] > 500:
+ raise RuntimeError(f"seed {seed}: no start")
+ i = int(rng.integers(N))
+ q0 = np.radians(deg + rng.uniform(-1.0, 1.0, 6) * noise)
+ c = g.resting_cube(np.array([bxy[i, 0], bxy[i, 1], half]), float(byaw[i]))
+ row = np.concatenate((q0, np.zeros(6), c["pos"], c["quat"], np.zeros(6)))[None]
+ res = blk.reset([0], row, warmup=True)
+ if res["code"][0] == 0 and not res["arm_table"][0] and not res["contact"][0, :2].any():
+ break
+ q[k], pos[k], quat[k], raw[k], bi[k] = q0, c["pos"], c["quat"], res["raw"][0], i
+ gen = torch.Generator().manual_seed(int(seed) * 7 + 3)
+ cy, _ = T.cube_yaw_tilt(torch.as_tensor(raw[k:k + 1, 15:19]).float().double())
+ gg, gy = T.sample_goals(torch.as_tensor(raw[k:k + 1, 12:14]).float().double(), cy, gen)
+ gxy[k], gyaw[k] = gg[0].numpy(), float(gy[0])
+ r = raw.astype(np.float32).astype(np.float64)
+ log(f"stage {stage}: {n} tasks (seeds {seeds[0]}-{seeds[-1]}) in {time.time() - t0:.0f} s, tries p50 "
+ f"{np.median(tries):.0f} max {tries.max()}")
+ out = dict(seeds=seeds, start_q=q, start_cube_pos=pos, start_cube_quat=quat, goal_xy=gxy, goal_yaw=gyaw,
+ spread_deg=np.zeros(n), tries=tries, stage=np.array(stage), dev=np.bool_(dev), bank_index=bi,
+ home_deg=deg, home_noise_deg=noise, bank=np.array(bank_path))
+ for name, sl in (("q", slice(0, 6)), ("qd", slice(6, 12)), ("cube_pos", slice(12, 15)), ("cube_quat", slice(15, 19)),
+ ("cube_v", slice(19, 22)), ("cube_w", slice(22, 25))):
+ out[f"state_{name}"] = r[:, sl]
+ return out
+
+
+def mix_tasks(tables, counts, seed=0):
+ """Training task table of ``counts[k]`` rows (the first ones) of each table, rows shuffled with ``seed``; per-task
+ keys kept where every table has them, ``kind`` = the table index, ``kind_stage`` = their stages."""
+ parts = []
+ for t, c in zip(tables, counts):
+ n = len(t["seeds"])
+ if c > n:
+ raise ValueError(f"{c} rows wanted, {n} in the table")
+ parts.append({k: v[:c] for k, v in t.items() if np.ndim(v) and len(v) == n})
+ keys = set.intersection(*[set(p) for p in parts])
+ out = {k: np.concatenate([p[k] for p in parts]) for k in sorted(keys)}
+ out["kind"] = np.concatenate([np.full(c, k, np.int64) for k, c in enumerate(counts)])
+ perm = np.random.default_rng(seed).permutation(len(out["seeds"]))
+ out = {k: v[perm] for k, v in out.items()}
+ if len(np.unique(out["seeds"])) != len(out["seeds"]):
+ raise ValueError("duplicate seeds in the mixed table")
+ out["kind_stage"] = np.array([str(t.get("stage", "?")) for t in tables])
+ out["mix_seed"] = np.int64(seed)
+ return out
+
+
+def load_tasks(path, idx=None):
+ from nedm.so101_policy.vision.demos import load_tasks as lt
+ return lt(path, idx)
+
+
+def subset(tasks, idx):
+ n = len(tasks["seeds"])
+ return {k: (v[idx] if np.ndim(v) and len(v) == n else v) for k, v in tasks.items()}
+
+
+# ---- decoder state copy / re-sync ---------------------------------------------------------------------------------------
+def dec_copy(dst, src, mask):
+ """Rows ``mask`` [B] bool of every per-world state tensor of DecoderV2 ``src`` -> ``dst`` (new tensors)."""
+ for n in DEC_STATE:
+ a, b = getattr(dst, n), getattr(src, n)
+ m = mask.view(-1, *([1] * (a.dim() - 1)))
+ setattr(dst, n, torch.where(m, b, a))
+ for k in dst.counts:
+ dst.counts[k] = torch.where(mask, src.counts[k], dst.counts[k])
+
+
+def settle_cfg():
+ from nedm.so101_policy import task as T
+ return T.TaskConfig()
+
+
+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,
+ settle_z=(-0.004, 0.0015)):
+ """Make the label decoder ``dec`` consistent with a world that the student drove in the last decision (module
+ docstring, point 3). mask [B] bool; u1, u2 [B, 6]: the last and the second last executed command; F: task
+ features of the current state (``held``, ``bottom``); a5 [B]: the teacher's lift-height output in [-1, 1] (for a
+ student grasp). -> dict of [B] bool: to_free, to_grip."""
+ from nedm.so101_policy.decoder import CONTROL_DT as DT, M
+ from nedm.so101_policy.kin import wrap, yaw_of
+ if not bool(mask.any()):
+ z = torch.zeros_like(mask)
+ return dict(to_free=z, to_grip=z.clone(), snap=z.clone())
+ c = dec.cfg
+ f = dec.f
+ u1, u2 = u1.to(**f), u2.to(**f)
+ m = mask
+ mode = dec.mode
+ held = F["held"].to(m.device)
+ holding = (mode == M["hold"]) | (mode == M["p_brake"]) | (mode == M["p_settle"]) | (mode == M["p_lower"])
+ pre = (mode == M["free"]) | (mode == M["g_brake"]) | (mode == M["g_descend"]) | (mode == M["g_settle"])
+ to_free = m & holding & ~held
+ to_grip = m & pre & held
+ new_mode = torch.where(to_free, M["free"], torch.where(to_grip, M["g_grip"], mode))
+ fk = dec.kin.fk
+ p1, r1 = fk(u1)
+ p2, r2 = fk(u2)
+ y1, y2 = yaw_of(r1), yaw_of(r2)
+ # (a) delta re-sync (free / hold, no mode change): shift the shadow's command, IK target and Cartesian target by
+ # the student's deviation from the shadow's own command, and its target velocity by the difference of the command
+ # velocities; a perfect follower leaves the shadow unchanged
+ keep = m & ((mode == M["free"]) | (mode == M["hold"])) & ~to_free & ~to_grip
+ qc = dec.q_cmd
+ qc2 = torch.cat((qc[:, :5] - dec.dq, qc[:, 5:]), -1)
+ q_des_new = dec.q_des + (u1[:, :5] - qc[:, :5])
+ pa, ra = fk(dec.q_des)
+ pb, rb = fk(q_des_new)
+ pc1, rc1 = fk(qc)
+ pc2, rc2 = fk(qc2)
+ pos_k = dec.pos + (pb - pa)
+ yaw_k = dec.yaw + wrap(yaw_of(rb) - yaw_of(ra))
+ vel_k = dec.vel + (p1 - p2) / DT - (pc1 - pc2) / DT
+ yr_k = dec.yrate + wrap(y1 - y2) / DT - wrap(yaw_of(rc1) - yaw_of(rc2)) / DT
+ # (b) absolute re-sync at a mode change (to_free: free motion from the student's command; to_grip: at rest)
+ ab = to_free | to_grip
+ yaw_a = dec.yaw + wrap(y1 - dec.yaw)
+ vel_a = torch.where(to_grip[:, None], torch.zeros_like(p1), (p1 - p2) / DT)
+ yr_a = torch.where(to_grip, torch.zeros_like(y1), wrap(y1 - y2) / DT)
+ blendm = keep | to_free
+ setm = keep | ab
+ m1, m3 = setm, setm[:, None]
+ pos_n = torch.where(ab[:, None], p1, pos_k)
+ yaw_n = torch.where(ab, yaw_a, yaw_k)
+ v_set = torch.where(ab[:, None], vel_a, vel_k)
+ w_set = torch.where(ab, yr_a, yr_k)
+ qd_n = torch.where(ab[:, None], u1[:, :5], q_des_new)
+ dec.pos = torch.where(m3, pos_n, dec.pos)
+ dec.yaw = torch.where(m1, yaw_n, dec.yaw)
+ dec.vel = torch.where(m3, v_set, dec.vel)
+ dec.yrate = torch.where(m1, w_set, dec.yrate)
+ dec.q_des = torch.where(m3, qd_n, dec.q_des)
+ ab3 = ab[:, None]
+ dec.v0, dec.vn = torch.where(ab3, v_set, dec.v0), torch.where(ab3, v_set, dec.vn)
+ dec.w0, dec.wn = torch.where(ab, w_set, dec.w0), torch.where(ab, w_set, dec.wn)
+ dec.tau = torch.where(ab, torch.full_like(dec.tau, dec.T_d), dec.tau)
+ dec.tb = torch.where(ab, torch.full_like(dec.tb, dec.T_d), dec.tb)
+ # command state (every re-synced world, macros included: the limiter continues from the student's command)
+ jaw_prev = dec.q_cmd[:, 5].clone()
+ dec.q_cmd = torch.where(m[:, None], u1, dec.q_cmd)
+ dec.dq = torch.where(m[:, None], u1[:, :5] - u2[:, :5], dec.dq)
+ # macro lines (descent, lift, lowering, retreat): a student ahead of the shadow's line clock moves the clock to
+ # the student's progress along the line (minimum-jerk inverse), so the labels never pull the student back
+ from nedm.so101_policy.decoder import minjerk
+ linem = m & ((mode == M["g_descend"]) | (mode == M["g_lift"]) | (mode == M["p_lower"]) | (mode == M["p_retreat"]))
+ if bool(linem.any()):
+ d = dec.lp1 - dec.lp0
+ L2 = (d * d).sum(-1).clamp_min(1e-12)
+ prog = (((p1 - dec.lp0) * d).sum(-1) / L2).clamp(0.0, 1.0)
+ n_ = dec.ln.clamp_min(1.0)
+ lo, hi = torch.zeros_like(prog), torch.ones_like(prog)
+ for _ in range(30): # s with minjerk(s) = prog
+ mid = (lo + hi) / 2
+ up_ = minjerk(mid) < prog
+ lo, hi = torch.where(up_, mid, lo), torch.where(up_, hi, mid)
+ k_new = torch.minimum(torch.round(hi * n_), n_)
+ adv = linem & (L2 > 1e-8) & (k_new > dec.lk)
+ dec.lk = torch.where(adv, k_new, dec.lk)
+ # macros that wait for the command at rest (g_settle -> g_close, p_lower -> p_open; the decoder's rule is exact to
+ # 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
+ # 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
+ # 0-2 mm); lowering: lowest cube corner <= settle_bottom above the table) or
+ # its command is within rest_tol of the shadow's IK target; the shadow then adopts the student's pose at rest and
+ # the macro goes on (without this the shadow never reached the close: build8 sec. 1c)
+ tc = settle_cfg()
+ xg = F["xg"].to(m.device)
+ in_box = ((xg[:, 0].abs() <= tc.box_x) & (xg[:, 1].abs() <= tc.box_y) & (xg[:, 2] >= settle_z[0])
+ & (xg[:, 2] <= settle_z[1]) & (F["yaw_mis"].to(m.device) <= tc.close_yaw))
+ near_table = F["bottom"].to(m.device) <= settle_bottom
+ close_q = (u1[:, :5] - dec.q_des).abs().amax(-1) < rest_tol
+ done = dec.lk >= dec.ln - 1e-9
+ g_wait = (mode == M["g_descend"]) | (mode == M["g_settle"])
+ snap = m & done & ((g_wait & (in_box | close_q)) | ((mode == M["p_lower"]) & (near_table | close_q)))
+ if bool(snap.any()):
+ s3 = snap[:, None]
+ dec.q_des = torch.where(s3, u1[:, :5], dec.q_des)
+ dec.q_cmd = torch.where(s3, u1, dec.q_cmd)
+ dec.dq = torch.where(s3, torch.zeros_like(dec.dq), dec.dq)
+ dec.pos = torch.where(s3, p1, dec.pos)
+ dec.yaw = torch.where(snap, dec.yaw + wrap(y1 - dec.yaw), dec.yaw)
+ dec.vel = torch.where(s3, torch.zeros_like(dec.vel), dec.vel)
+ dec.yrate = torch.where(snap, torch.zeros_like(dec.yrate), dec.yrate)
+ # a descent that is done: settle at once (g_settle with its hold finished); a lowering: its line is finished
+ dec.mode = torch.where(snap & (mode == M["g_descend"]), M["g_settle"], dec.mode)
+ mode = torch.where(snap & (mode == M["g_descend"]), M["g_settle"], mode)
+ new_mode = torch.where(snap & (new_mode == M["g_descend"]), M["g_settle"], new_mode)
+ dec.lk = torch.where(snap, dec.ln, dec.lk)
+ # jaw: free / hold restart the schedule from the student's jaw if it left the shadow's; mode changes always
+ goal = torch.where(new_mode == M["free"], torch.full_like(dec.yaw, c.jaw_open),
+ torch.where((new_mode == M["hold"]) | (new_mode == M["g_grip"]),
+ torch.full_like(dec.yaw, c.jaw_closed), dec.jaw_to))
+ jm = (blendm & ((u1[:, 5] - jaw_prev).abs() > jaw_tol)) | to_free | to_grip
+ done = (goal - u1[:, 5]).abs() < jaw_done_tol
+ n = torch.round(torch.clamp_min(1.875 * (goal - u1[:, 5]).abs() / c.jaw_speed, c.jaw_min_s) / DT).clamp_min(1)
+ dec.jaw_from = torch.where(jm, torch.where(done, goal, u1[:, 5]), dec.jaw_from)
+ dec.jaw_to = torch.where(jm, goal, dec.jaw_to)
+ dec.jaw_k = torch.where(jm, torch.where(done, torch.ones_like(n), torch.zeros_like(n)), dec.jaw_k)
+ dec.jaw_n = torch.where(jm, torch.where(done, torch.ones_like(n), n), dec.jaw_n)
+ # mode changes
+ if bool(to_free.any()):
+ dec.z_ceil = torch.where(to_free, torch.full_like(dec.z_ceil, c.z_max), dec.z_ceil)
+ dec.armed = dec.armed | to_free
+ dec.lk = torch.where(to_free, torch.zeros_like(dec.lk), dec.lk)
+ dec.ln = torch.where(to_free, torch.zeros_like(dec.ln), dec.ln)
+ if bool(to_grip.any()):
+ a5 = torch.zeros_like(dec.yaw) if a5 is None else a5.to(**f).clamp(-1, 1)
+ h = c.lift_range[0] + (a5 + 1) / 2 * (c.lift_range[1] - c.lift_range[0])
+ dec.h = torch.where(to_grip, h, dec.h)
+ bottom = F["bottom"].to(**f)
+ ceil = torch.clamp_max(p1[:, 2] + c.cube_bottom_max - bottom.clamp_min(0), c.z_max)
+ dec.z_ceil = torch.where(to_grip, ceil, dec.z_ceil)
+ dec.goal = torch.where(to_grip[:, None], torch.cat((p1, yaw_a[:, None]), -1), dec.goal)
+ dec.armed = dec.armed & ~to_grip
+ dec.lp0 = torch.where(to_grip[:, None], p1, dec.lp0)
+ dec.lp1 = torch.where(to_grip[:, None], p1, dec.lp1)
+ ln = torch.round(dec._draw(to_grip, c.t_grip) / DT)
+ dec.ln = torch.where(to_grip, ln, dec.ln)
+ dec.lk = torch.where(to_grip, torch.zeros_like(dec.lk), dec.lk)
+ dec.mode = new_mode
+ return dict(to_free=to_free, to_grip=to_grip, snap=snap)
+
+
+# ---- the joint-level task world --------------------------------------------------------------------------------------
+def rule_config(horizon=400, obs_rates=True, **kw):
+ from nedm.so101_policy import task as T
+ return T.TaskConfig(horizon=int(horizon), obs_rates=bool(obs_rates), log_only=LOG_ONLY, **kw)
+
+
+class TrayWorld:
+ """B task worlds of one kind (``nrd`` = GraspNrdSim, ``mujoco`` = CPU MuJoCo, ``kin``) + the teacher's label
+ decoder + the task rules of this module (module docstring). ``run(tasks, ...)`` plays one episode per world."""
+
+ def __init__(self, world, B, teacher, device="cuda", nrd_ckpt=None, workers=0, mj_python=None, horizon=400,
+ members="split", decoder=None):
+ from nedm.so101_policy import task as T
+ from nedm.so101_policy import vec_env as VE
+ from nedm.so101_policy.decoder import DecoderV2, DecoderV2Config
+ self.kind, self.B, self.teacher = world, int(B), teacher
+ self.dev = torch.device("cpu" if world == "mujoco" else device)
+ ck = [str(Path(c).expanduser()) for c in ([nrd_ckpt] if isinstance(nrd_ckpt, (str, Path)) else (nrd_ckpt or []))]
+ cfg = VE.EnvConfig(world=world, num_envs=self.B, device=device, ckpts=ck, members=members, mj_workers=workers,
+ mj_python=mj_python, starts="", decoder=dict(teacher.decoder_cfg), **teacher.files)
+ self.cfg = cfg
+ self.kin = VE.kinematics(cfg.kin_points, self.dev)
+ self.geom = VE.task_geometry(cfg.geom_path, self.dev)
+ self.world = VE.make_world(cfg, self.B, self.dev, self.kin, self.geom)
+ self.tcfg = rule_config(horizon, teacher.obs_rates)
+ self.task = T.PickPlaceTask(self.B, self.dev, kin=self.kin, geom=self.geom, cfg=self.tcfg,
+ overlap_rules=world != "mujoco")
+ self.decoder_over = dict(TEACHER_DECODER if decoder is None else decoder)
+ self.dcfg = replace(DecoderV2Config(), **{**teacher.decoder_cfg, **{k: tuple(v) if isinstance(v, list) else v
+ for k, v in self.decoder_over.items()}})
+ if self.dcfg.blend != "cosine" or self.dcfg.carry_macro:
+ raise ValueError("the tray world supports the cosine blend without the CARRY macro")
+ self.lab = DecoderV2(self.B, self.dev, kin=self.kin, cfg=self.dcfg)
+ self.drv = None
+ self.ws = None
+ self.world_steps = 0
+ self.nrd_ckpt = ck
+
+ def close(self):
+ if hasattr(self.world, "close"):
+ self.world.close()
+
+ def _reset(self, tasks):
+ from nedm.so101_policy.vision.demos import start_state
+ B, dev = self.B, self.dev
+ if len(tasks["seeds"]) != B:
+ raise ValueError(f"{len(tasks['seeds'])} tasks for {B} worlds")
+ idx = torch.arange(B, device=dev)
+ st = start_state(tasks, dev)
+ if self.kind == "mujoco":
+ mj = dict(q=tasks["start_q"], cube_pos=tasks["start_cube_pos"], cube_quat=tasks["start_cube_quat"])
+ ws = self.world.reset(idx.cpu(), mj, warmup=True).to(dev)
+ dq = float((ws.q - st.q).abs().max())
+ dc = float((ws.cube_pos - st.cube_pos).abs().max())
+ if dq > 1e-6 or dc > 1e-6:
+ raise RuntimeError(f"MuJoCo warm-up start differs from the stored settled state ({dq:.2e}, {dc:.2e})")
+ elif self.kind == "mjwarp":
+ ws = self.world.reset(idx, st, warmup=False)
+ else:
+ ws = self.world.reset(idx, st)
+ self.ws = ws.to(dev)
+ seeds = torch.as_tensor(tasks["seeds"], dtype=torch.long, device=dev)
+ self.seeds = seeds
+ self.lab.reset(idx, self.ws.q, seed=seeds)
+ if self.drv is not None:
+ self.drv.reset(idx, self.ws.q, seed=seeds)
+ g = lambda k: torch.as_tensor(tasks[k], dtype=torch.float64, device=dev) # noqa: E731
+ self.task.reset(idx, self.ws, g("goal_xy"), g("goal_yaw"))
+ self.goal_pose = torch.cat((g("goal_xy"), g("goal_yaw")[:, None]), -1)
+
+ def observation(self, F):
+ from nedm.so101_policy import task as T
+ tk = self.task
+ return T.observation(F, tk.goal_xy, tk.goal_yaw, tk.tr.lifted, tk.tr.air_run, self.tcfg, self.lab.observation(),
+ self.lab.macro())
+
+ @torch.no_grad()
+ def run(self, tasks, student=None, beta=1.0, noise=None, seed=0, record=True, n_exec=5, record_states=False,
+ log=None, ensemble=None, jaw_lead=0, full_horizon=False):
+ """One episode per world on ``tasks`` (B rows). student: a ``TrayActor`` (or None: beta must be 1); beta: the
+ probability that the teacher drives a decision (per world and decision); noise [B] (or float): DART noise
+ scale of the teacher's move columns per world (beta 1 only); n_exec: executed targets per student query (<= 5,
+ one query per decision). -> dict: per-episode arrays (end, success, success10, lifted, end_xy, end_yaw, steps,
+ rows) and with ``record`` the packed rows / steps (module docstring); ``record_states``: per-step q, cube pose
+ [B, S, ...] of all worlds (videos); ``ensemble`` (with n_exec 1): temporal ensembling of the overlapping chunk
+ predictions for the current step, weight exp(ensemble x age in steps) (ACT's convention: > 0 favours the older
+ predictions, < 0 the newer); ``jaw_lead``: the jaw target is taken that many steps ahead in the chunk(s) (the
+ cube-blocked jaw hides the first steps of an opening ramp); ``full_horizon``: keep stepping every world (and
+ querying the student) to the horizon after its task ended (videos; the outcome arrays still hold the task end)."""
+ from nedm.so101_policy import task as T
+ from nedm.so101_policy.decoder import DecoderV2, hash_uniform
+ from nedm.so101_policy.vision.teacher import hash_normal
+ te, B, dev = self.teacher, self.B, self.dev
+ if student is None and beta < 1:
+ raise ValueError("beta < 1 needs a student")
+ nz = torch.zeros(B, dtype=torch.float64, device=dev) if noise is None else \
+ torch.as_tensor(noise, dtype=torch.float64, device=dev).expand(B).clone()
+ noisy_w = nz > 0
+ if bool(noisy_w.any()) and beta < 1:
+ raise ValueError("DART noise only in teacher-driven episodes (beta 1)")
+ if bool(noisy_w.any()) and self.drv is None:
+ self.drv = DecoderV2(B, dev, kin=self.kin, cfg=self.dcfg)
+ n_exec = int(n_exec) # query period (steps): a new chunk every n_exec steps, its first n_exec
+ if n_exec < 1: # targets executed (5 = one query per decision, at the boundaries)
+ raise ValueError("n_exec must be >= 1")
+ t0 = time.time()
+ self._reset(tasks)
+ if student is not None:
+ student.reset(B)
+ lab, drv, task, tc = self.lab, self.drv, self.task, self.tcfg
+ any_noise = bool(noisy_w.any())
+ steps_per = lab.cfg.decision_steps
+ K = math.ceil(tc.horizon / steps_per)
+ hseed = self.seeds * 1_000_003 + 7919 * int(seed) + 17
+ std = te.std.to(dev, torch.float64)
+ u1 = self.ws.q.clone()
+ u2 = self.ws.q.clone()
+ src_prev = torch.zeros(B, dtype=torch.long, device=dev)
+ a_prev = torch.zeros(B, te.act_dim, dtype=torch.float64, device=dev)
+ R = {k: [] for k in ("q", "qd", "cube_pos", "cube_quat", "src", "mode", "cont", "live", "a_pre", "to_free",
+ "to_grip", "snap")}
+ S = {k: [] for k in ("u_lab", "u_exe", "live", "st_q", "st_qd", "st_cube_pos", "st_cube_quat")}
+ SS = {k: [] for k in ("q", "cube")} if record_states else None
+ info = None
+ t_student = 0.0
+ tlo, thi = self.kin.tlo.to(dev), self.kin.thi.to(dev)
+ chunk, q_step, hist = None, 0, []
+ for k in range(K + 1):
+ live0 = task.tr.end == 0
+ if not bool(live0.any()) and not full_horizon:
+ break
+ ws = self.ws
+ F = T.features(ws, self.kin, None, tc)
+ if any_noise:
+ dec_copy(lab, drv, noisy_w)
+ stud_prev = src_prev == SRC["student"]
+ rs = resync(lab, stud_prev & live0, u1, u2, F, a_prev[:, 5] if a_prev.shape[1] > 5 else None)
+ obs = self.observation(F)
+ a_pre = te.act(obs.to(te.dev)).to(dev, torch.float64)
+ a_clean = torch.tanh(a_pre)
+ if beta >= 1.0:
+ use_t = torch.ones(B, dtype=torch.bool, device=dev)
+ elif beta <= 0.0:
+ use_t = torch.zeros(B, dtype=torch.bool, device=dev)
+ else:
+ use_t = hash_uniform(hseed, torch.full_like(hseed, k), 99) < beta
+ src = torch.where(use_t, torch.where(noisy_w, SRC["noisy"], SRC["teacher"]), SRC["student"]).long()
+ cont = (src_prev == SRC["teacher"]) & (k > 0)
+ if record:
+ for name, v in (("q", ws.q), ("qd", ws.qd), ("cube_pos", ws.cube_pos), ("cube_quat", ws.cube_quat)):
+ R[name].append(v.float().cpu())
+ R["src"].append(src.to(torch.int8).cpu())
+ R["mode"].append(lab.mode.to(torch.int8).cpu())
+ R["cont"].append(cont.cpu())
+ R["live"].append(live0.cpu())
+ R["a_pre"].append(a_pre.float().cpu())
+ R["to_free"].append(rs["to_free"].cpu())
+ R["to_grip"].append(rs["to_grip"].cpu())
+ R["snap"].append(rs["snap"].cpu())
+ if any_noise:
+ eps = hash_normal(hseed, k, 4).to(a_pre)
+ a_n = a_pre.clone()
+ a_n[:, :4] = a_pre[:, :4] + nz[:, None] * std[:4] * eps
+ drv.decide(torch.tanh(a_n), ws)
+ lab.decide(a_clean, ws)
+ stud = src == SRC["student"]
+ for j in range(steps_per):
+ gs = k * steps_per + j # 20 ms steps since the reset
+ live_s = task.tr.end == 0
+ if student is not None and bool((stud & (live_s | full_horizon)).any()) and (chunk is None or gs % n_exec == 0):
+ ts = time.time()
+ chunk = student(self.ws, self.goal_pose).to(dev, torch.float64)
+ chunk = torch.minimum(torch.maximum(chunk, tlo), thi)
+ q_step = gs
+ t_student += time.time() - ts
+ if record:
+ for name, v in (("st_q", self.ws.q), ("st_qd", self.ws.qd), ("st_cube_pos", self.ws.cube_pos),
+ ("st_cube_quat", self.ws.cube_quat)):
+ S[name].append(v.float().cpu())
+ u_l, _ = lab.step(self.ws.q)
+ u_e = u_l
+ if any_noise:
+ u_d, _ = drv.step(self.ws.q)
+ u_e = torch.where(noisy_w[:, None], u_d, u_e)
+ if chunk is not None and ensemble is not None and n_exec == 1:
+ if not hist or hist[-1][0] != q_step:
+ hist.append((q_step, chunk))
+ hist = [(t_, c_) for t_, c_ in hist if gs - t_ < c_.shape[1]]
+ num = torch.zeros_like(u_e)
+ den = 0.0
+ for t_, c_ in hist:
+ w_ = math.exp(float(ensemble) * (gs - t_))
+ kk = min(gs - t_ + int(jaw_lead), c_.shape[1] - 1)
+ num = num + w_ * torch.cat((c_[:, gs - t_, :5], c_[:, kk, 5:]), -1)
+ den += w_
+ u_e = torch.where(stud[:, None], num / den, u_e)
+ elif chunk is not None:
+ jj = min(gs - q_step, chunk.shape[1] - 1)
+ kk = min(gs - q_step + int(jaw_lead), chunk.shape[1] - 1)
+ u_e = torch.where(stud[:, None], torch.cat((chunk[:, jj, :5], chunk[:, kk, 5:]), -1), u_e)
+ w = self.world.step(u_e)
+ self.ws = w if self.kind != "mujoco" else w.to(dev)
+ _, _, _, info = task.step(self.ws, None, None)
+ self.world_steps += B
+ if record:
+ S["u_lab"].append(u_l.float().cpu())
+ S["u_exe"].append(u_e.float().cpu())
+ S["live"].append(live_s.cpu())
+ if record_states:
+ SS["q"].append(self.ws.q.float().cpu())
+ SS["cube"].append(torch.cat((self.ws.cube_pos, self.ws.cube_quat), -1).float().cpu())
+ u2, u1 = u1, u_e
+ src_prev = src
+ a_prev = a_clean
+ if log is not None and k % 20 == 19:
+ log(f" decision {k + 1}: ended {int((task.tr.end != 0).sum())}/{B}")
+ tr = task.tr
+ cp = lambda v: v.detach().cpu().clone().numpy() # noqa: E731
+ out = dict(end=cp(tr.end), success=cp(tr.end == T.EC["success"]), success10=cp(tr.success10),
+ lifted=cp(tr.lifted), end_xy=cp(tr.end_xy), end_yaw=cp(tr.end_yaw), steps=cp(tr.t),
+ box_log=cp(tr.box_log), seeds=np.asarray(tasks["seeds"]),
+ goal_xy=np.asarray(tasks["goal_xy"], np.float32), goal_yaw=np.asarray(tasks["goal_yaw"], np.float32),
+ noise=nz.cpu().numpy(), wall_s=np.float64(time.time() - t0), student_s=np.float64(t_student))
+ if self.kind == "mujoco":
+ out["mj_reason"] = self.world.end_reason.clone().numpy().astype(np.int16)
+ if record:
+ out.update(pack({k: torch.stack(v, 1).numpy() for k, v in R.items()},
+ {k: torch.stack(v, 1).numpy() for k, v in S.items()}, out["steps"], steps_per))
+ if record_states:
+ out["state_q"] = torch.stack(SS["q"], 1).numpy()
+ out["state_cube"] = torch.stack(SS["cube"], 1).numpy()
+ return out
+
+
+def pack(rows, steps, ep_steps, steps_per=5):
+ """Live rows / steps of every episode -> flat arrays. rows: dict of [B, K, ...]; steps: dict of [B, S, ...];
+ ep_steps [B] = live 20 ms steps of each episode (the step in which the task ended included)."""
+ B = len(ep_steps)
+ ep_steps = np.asarray(ep_steps, np.int64)
+ n_rows = (ep_steps + steps_per - 1) // steps_per
+ Kr, Ks = rows["live"].shape[1], steps["live"].shape[1]
+ if (n_rows > Kr).any() or (ep_steps > Ks).any():
+ raise RuntimeError("episode longer than the records")
+ for b in range(B):
+ if not rows["live"][b, : n_rows[b]].all() or not steps["live"][b, : ep_steps[b]].all():
+ raise RuntimeError(f"episode {b}: live records are not a prefix")
+ rb = np.repeat(np.arange(B), n_rows)
+ rt = np.concatenate([np.arange(n) for n in n_rows]) if B else np.zeros(0, np.int64)
+ sb = np.repeat(np.arange(B), ep_steps)
+ stt = np.concatenate([np.arange(n) for n in ep_steps]) if B else np.zeros(0, np.int64)
+ out = {f"row_{k}": v[rb, rt] for k, v in rows.items() if k != "live"}
+ out.update({k: v[sb, stt] for k, v in steps.items() if k != "live"})
+ out["row_ep"], out["row_t"] = rb.astype(np.int32), (rt * steps_per).astype(np.int16)
+ out["ep_row_start"] = np.concatenate([[0], np.cumsum(n_rows)[:-1]]).astype(np.int64)
+ out["ep_rows"] = n_rows
+ out["ep_step_start"] = np.concatenate([[0], np.cumsum(ep_steps)[:-1]]).astype(np.int64)
+ return out
+
+
+EP_KEYS = ("end", "success", "success10", "lifted", "end_xy", "end_yaw", "steps", "box_log", "seeds", "goal_xy",
+ "goal_yaw", "noise", "mj_reason", "ep_rows", "ep_row_start", "ep_step_start")
+
+
+def concat(parts):
+ """Concatenate ``run`` outputs (episode, row and step indices shifted)."""
+ if len(parts) == 1:
+ return parts[0]
+ out, e0, r0, s0 = {}, 0, 0, 0
+ for p in parts:
+ E = len(p["end"])
+ q = dict(p)
+ if "row_ep" in p:
+ q["row_ep"] = p["row_ep"] + e0
+ q["ep_row_start"] = p["ep_row_start"] + r0
+ q["ep_step_start"] = p["ep_step_start"] + s0
+ r0 += len(p["row_ep"])
+ s0 += len(p["u_lab"])
+ e0 += E
+ for k, v in q.items():
+ if np.ndim(v) == 0:
+ continue
+ out.setdefault(k, []).append(v)
+ out = {k: np.concatenate(v) for k, v in out.items()}
+ for k, v in parts[0].items():
+ if np.ndim(v) == 0:
+ out[k] = np.asarray(sum(np.asarray(p[k]) for p in parts)) if k in ("wall_s", "student_s") else v
+ return out
+
+
+@torch.no_grad()
+def collect(tasks, world, teacher, student=None, beta=1.0, noise=0.0, seed=0, device="cuda", nrd_ckpt=None,
+ workers=0, mj_python=None, horizon=400, batch=512, log=log_default, meta_extra=None, n_exec=5,
+ tw_cache=None, decoder=None, ensemble=None, jaw_lead=0):
+ """Episodes on all tasks (batches of ``batch`` worlds) -> packed dict + ``meta`` (json). noise: a float (every
+ episode) or an array per task."""
+ from nedm.so101_policy.vision.teacher import check_seeds
+ check_seeds(tasks["seeds"])
+ n = len(tasks["seeds"])
+ nzs = np.broadcast_to(np.asarray(noise, np.float64), (n,))
+ parts, t0, steps = [], time.time(), 0
+ for s0 in range(0, n, batch):
+ idx = np.arange(s0, min(n, s0 + batch))
+ t = subset(tasks, idx)
+ key = (world, len(idx))
+ if tw_cache is not None and key in tw_cache:
+ tw = tw_cache[key]
+ else:
+ tw = TrayWorld(world, len(idx), teacher, device, nrd_ckpt, workers, mj_python, horizon, decoder=decoder)
+ if tw_cache is not None:
+ tw_cache[key] = tw
+ w0 = tw.world_steps
+ r = tw.run(t, student, beta, nzs[idx], seed, True, n_exec, ensemble=ensemble, jaw_lead=jaw_lead)
+ steps += tw.world_steps - w0
+ if tw_cache is None:
+ tw.close()
+ parts.append(r)
+ log(f" collect {world} beta {beta} noise {float(np.mean(nzs[idx])):.2f}: tasks {s0}-{idx[-1]}, success "
+ f"{r['success'].mean() * 100:.1f} %, {time.time() - t0:.0f} s")
+ out = concat(parts)
+ meta = dict(world=world, nrd_ckpt=str(nrd_ckpt), teacher=teacher.info(), n_tasks=n, beta=float(beta),
+ noise=float(np.mean(nzs)), seed=int(seed), horizon=int(horizon), batch=int(batch),
+ wall_s=time.time() - t0, world_steps=int(steps), success=float(np.mean(out["success"])),
+ rows=int(len(out["row_ep"])), seeds=[int(tasks["seeds"][0]), int(tasks["seeds"][-1])],
+ n_exec=int(n_exec), rules=dict(log_only=list(LOG_ONLY), macro_view="none"),
+ decoder_over={k: v for k, v in tw.decoder_over.items()}, **(meta_extra or {}))
+ out["meta"] = np.array(json.dumps(meta, default=str))
+ return out
+
+
+def load(path):
+ z = dict(np.load(Path(path).expanduser(), allow_pickle=False))
+ z["meta"] = json.loads(str(z["meta"])) if "meta" in z else {}
+ return z
+
+
+def summarize(r):
+ """Success, failure causes, lift rate, end errors of a ``run`` / ``collect`` / ``evaluate`` output."""
+ from nedm.so101_policy.task import ENDS
+ s = np.asarray(r["success"]).astype(bool)
+ causes = {ENDS[int(k)]: int(v) for k, v in zip(*np.unique(np.asarray(r["end"])[~s], return_counts=True))}
+ n = len(s)
+ lo, hi = wilson(int(s.sum()), n)
+ out = dict(n=n, success=float(s.mean()), ci95=[lo, hi], success10=float(np.mean(r["success10"])),
+ lifted=float(np.mean(r["lifted"])), causes=causes)
+ if s.any():
+ out["end_xy_mm_p50_success"] = float(np.median(np.asarray(r["end_xy"])[s]) * 1e3)
+ return out
+
+
+def wilson(k, n, z=1.96):
+ if n == 0:
+ return (float("nan"), float("nan"))
+ p = k / n
+ d = 1 + z * z / n
+ c = (p + z * z / (2 * n)) / d
+ h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
+ return (c - h, c + h)
+
+
+# ---- dataset ---------------------------------------------------------------------------------------------------------
+class TraySet:
+ """Collected files (``collect``) on one device. A sample = one query state: render inputs, robot vector [q, qd]
+ (12), target chunk [K, 6] = u_lab[t + j] - q_t with its validity mask (module docstring). ``step_rows``: every 20 ms
+ step is a sample (needs the per-step states ``st_*`` of the files; for students queried more often than once per
+ decision), else the decision boundaries only. Target j is valid inside the episode if every decision boundary
+ between t and t + j continues the clean teacher's plan (``row_cont``). Validation: ``val_frac`` of the FIRST
+ file's episodes (seeded): the same in every round."""
+
+ def __init__(self, paths, device="cuda", chunk=10, val_frac=0.05, seed=0, steps_per=5, step_rows=False):
+ if isinstance(paths, (str, Path)):
+ paths = [paths]
+ files = [load(p) for p in paths]
+ self.meta = [f["meta"] for f in files]
+ keys = set.intersection(*[set(f) for f in files]) - {"meta"}
+ d = concat([{k: v for k, v in f.items() if k in keys} for f in files])
+ n_ep = [len(f["end"]) for f in files]
+ E = len(d["end"])
+ rng = np.random.default_rng(int(seed))
+ first = rng.permutation(n_ep[0])
+ val_eps = np.sort(first[: int(round(val_frac * n_ep[0]))])
+ is_val = np.zeros(E, bool)
+ is_val[val_eps] = True
+ self.n_val_eps, self.n_train_eps = int(is_val.sum()), int(E - is_val.sum())
+ self.chunk, self.dev, self.steps_per = int(chunk), torch.device(device), int(steps_per)
+ self.step_rows = bool(step_rows)
+ t = lambda x, dt=torch.float32: torch.as_tensor(np.ascontiguousarray(x), dtype=dt, device=self.dev) # noqa
+ self.cont = t(d["row_cont"], torch.bool)
+ self.ep_steps, self.ep_step_start = t(d["steps"], torch.long), t(d["ep_step_start"], torch.long)
+ self.ep_rows, self.ep_row_start = t(d["ep_rows"], torch.long), t(d["ep_row_start"], torch.long)
+ self.u_lab = t(d["u_lab"])
+ self.goal_pose = torch.cat((t(d["goal_xy"]), t(d["goal_yaw"])[:, None]), -1)
+ self.ep_success = t(d["success"], torch.bool)
+ if self.step_rows:
+ if "st_q" not in d:
+ raise ValueError("step_rows needs files with per-step states (st_*)")
+ steps = np.asarray(d["steps"], np.int64)
+ s_ep = np.repeat(np.arange(E), steps)
+ s_t = np.concatenate([np.arange(n) for n in steps])
+ self.q, self.qd = t(d["st_q"]), t(d["st_qd"])
+ self.cube_pos, self.cube_quat = t(d["st_cube_pos"]), t(d["st_cube_quat"])
+ self.s_ep, self.s_t = t(s_ep, torch.long), t(s_t, torch.long)
+ self.s_g = torch.arange(len(s_ep), device=self.dev)
+ else:
+ self.q, self.qd = t(d["row_q"]), t(d["row_qd"])
+ self.cube_pos, self.cube_quat = t(d["row_cube_pos"]), t(d["row_cube_quat"])
+ self.s_ep, self.s_t = t(d["row_ep"], torch.long), t(d["row_t"], torch.long)
+ self.s_g = self.ep_step_start[self.s_ep] + self.s_t
+ self.robot = torch.cat((self.q, self.qd), -1)
+ row_val = torch.as_tensor(is_val, device=self.dev)[self.s_ep]
+ self.train_rows = torch.nonzero(~row_val).flatten()
+ self.val_rows = torch.nonzero(row_val).flatten()
+ self.n_rows = len(self.q)
+
+ def targets(self, rows):
+ """-> (target [n, K, 6] = u_lab - q_t, valid [n, K] bool)."""
+ e = self.s_ep[rows]
+ K, sp = self.chunk, self.steps_per
+ j = torch.arange(K, device=self.dev)
+ t0 = self.s_t[rows]
+ tloc = t0[:, None] + j[None] # local step of target j
+ inside = tloc < self.ep_steps[e][:, None]
+ g = self.s_g[rows][:, None] + j[None]
+ g = torch.minimum(g, (self.ep_step_start[e] + self.ep_steps[e] - 1)[:, None])
+ tgt = self.u_lab[g] - self.q[rows][:, None, :]
+ # boundaries crossed by target j: m = 1 .. (t0 % sp + j) // sp; boundary m = row t0 // sp + m of the episode
+ crossed = (t0[:, None] % sp + j[None]) // sp
+ nb = int(crossed.max()) if len(rows) else 0
+ last_row = self.ep_row_start[e] + self.ep_rows[e] - 1
+ base = self.ep_row_start[e] + t0 // sp
+ ok = torch.ones(len(rows), K, dtype=torch.bool, device=self.dev)
+ chain = torch.ones(len(rows), dtype=torch.bool, device=self.dev)
+ for m in range(1, nb + 1):
+ rr = base + m
+ chain = chain & (self.cont[torch.minimum(rr, last_row)] | (rr > last_row))
+ ok = ok & ~((crossed >= m) & ~chain[:, None])
+ return tgt, inside & ok
+
+ def batch(self, rows):
+ e = self.s_ep[rows]
+ tgt, valid = self.targets(rows)
+ return dict(q=self.q[rows], cube_pos=self.cube_pos[rows], cube_quat=self.cube_quat[rows],
+ goal_pose=self.goal_pose[e], robot=self.robot[rows], target=tgt, valid=valid)
+
+ def stats(self, floor=1e-3, robot_floor=1e-2, n=200_000, seed=0):
+ g = torch.Generator(device=self.dev).manual_seed(seed)
+ rows = self.train_rows[torch.randint(len(self.train_rows), (min(n, len(self.train_rows)),), device=self.dev,
+ generator=g)]
+ tgt, valid = self.targets(rows)
+ v = valid[..., None].float()
+ cnt = v.sum(0).clamp_min(1)
+ mu = (tgt * v).sum(0) / cnt
+ sd = (((tgt - mu) ** 2 * v).sum(0) / cnt).sqrt().clamp_min(floor)
+ x = self.robot[rows]
+ return dict(robot_mean=x.mean(0).cpu(), robot_std=x.std(0).clamp_min(robot_floor).cpu(), tgt_mean=mu.cpu(),
+ tgt_std=sd.cpu())
+
+ def sample(self, n, gen=None, split="train"):
+ rows = self.train_rows if split == "train" else self.val_rows
+ return rows[torch.randint(len(rows), (int(n),), device=self.dev, generator=gen)]
+
+
+# ---- students ----------------------------------------------------------------------------------------------------------
+@dataclass
+class TrayConfig:
+ kind: str = "perstep" # perstep | act
+ chunk: int = 10 # targets per query (20 ms each); the first n_exec are executed
+ n_exec: int = 5 # query period in 20 ms steps (5 = once per decision)
+ step_rows: bool = False # train on every step's state (needed for n_exec < 5), not only the boundaries
+ ensemble: object = None # execution with n_exec 1: temporal ensembling coefficient (None: off)
+ jaw_lead: int = 0 # execution: the jaw target taken this many steps ahead in the chunk(s)
+ res: int = V.RES
+ cameras: tuple = ("top", "wrist")
+ robot_dim: int = 12 # 12: q (6) + qdot (6); 6: q only (the qdot ablation: no copycat input)
+ qd_noise: float = 0.0 # training only: Gaussian noise on the normalised qdot inputs (std units)
+ # per-step CNN
+ encoder: str = "resnet18"
+ stages: int = 3
+ keypoints: int = 32
+ pool_dim: int = 64
+ hidden: tuple = (512, 512)
+ # ACT (LeRobot)
+ dim_model: int = 512
+ n_heads: int = 8
+ dim_feedforward: int = 3200
+ n_encoder_layers: int = 4
+ n_decoder_layers: int = 1
+ use_vae: bool = True
+ latent_dim: int = 32
+ n_vae_encoder_layers: int = 4
+ kl_weight: float = 10.0
+ dropout: float = 0.1
+ # training
+ batch: int = 128
+ render_batch: int = 256
+ lr: float = 3e-4
+ lr_backbone: float = 1e-4
+ weight_decay: float = 1e-4
+ warmup: int = 300
+ cosine: bool = True
+ grad_clip: float = 10.0
+ shift_px: int = 0
+ amp: bool = True
+ seed: int = 0
+
+ @staticmethod
+ def from_dict(d):
+ d = dict(d or {})
+ known = set(TrayConfig.__dataclass_fields__)
+ bad = sorted(set(d) - known - {"note", "notes"})
+ if bad:
+ raise ValueError(f"unknown tray config keys {bad}")
+ for k in ("cameras", "hidden"):
+ if k in d:
+ d[k] = tuple(d[k])
+ return TrayConfig(**{k: v for k, v in d.items() if k in known})
+
+
+STAT_KEYS = ("robot_mean", "robot_std", "tgt_mean", "tgt_std")
+
+
+def robot_norm(st, robot):
+ """Normalised robot vector: the first ``cfg.robot_dim`` entries of [q, qdot] (12: both; 6: q only); in training
+ mode with ``cfg.qd_noise`` > 0, Gaussian noise of that std on the normalised qdot entries (against the copycat
+ shortcut of behaviour cloning with rate inputs)."""
+ k = st.cfg.robot_dim
+ r = ((robot[:, :k] - st.robot_mean[:k]) / st.robot_std[:k]).clamp(-10, 10)
+ if st.training and getattr(st.cfg, "qd_noise", 0.0) > 0 and k > 6:
+ r = torch.cat((r[:, :6], r[:, 6:] + st.cfg.qd_noise * torch.randn_like(r[:, 6:])), -1)
+ return r
+
+
+class PerStepChunk(nn.Module):
+ """Per camera ResNet18 (ImageNet, frozen BN, to layer3) -> spatial-softmax keypoints + pooled features; MLP over
+ [cameras, normalised q / qdot] -> a normalised target chunk [K, 6]."""
+
+ def __init__(self, cfg: TrayConfig, stats, pretrained=True):
+ super().__init__()
+ from nedm.so101_policy.vision.perstep import Encoder, PerStepConfig
+ self.cfg = cfg
+ pc = PerStepConfig(encoder=cfg.encoder, stages=cfg.stages, keypoints=cfg.keypoints, pool_dim=cfg.pool_dim)
+ self.enc = nn.ModuleList([Encoder(pc, pretrained) for _ in cfg.cameras])
+ d = sum(e.out_dim for e in self.enc) + cfg.robot_dim
+ layers, k = [], d
+ for h in cfg.hidden:
+ layers += [nn.Linear(k, h), nn.ELU()]
+ k = h
+ layers.append(nn.Linear(k, cfg.chunk * 6))
+ self.head = nn.Sequential(*layers)
+ for k_, v in stats.items():
+ self.register_buffer(k_, torch.as_tensor(v, dtype=torch.float32).clone())
+
+ def forward(self, images, robot):
+ feats = [e(images[:, i]) for i, e in enumerate(self.enc)]
+ r = robot_norm(self, robot)
+ return self.head(torch.cat(feats + [r.to(feats[0].dtype)], -1).float()).view(-1, self.cfg.chunk, 6)
+
+ def loss(self, images, robot, tgt_n, valid):
+ p = self(images, robot)
+ e = (p.float() - tgt_n).abs() * valid[..., None]
+ return e.sum() / (valid.sum() * 6).clamp_min(1), {}
+
+ @torch.no_grad()
+ def predict(self, images, robot):
+ return self(images, robot).float()
+
+ def backbone_params(self):
+ return [p for e in self.enc if e.is_backbone for p in e.trunk.parameters() if p.requires_grad]
+
+
+class ActChunk(nn.Module):
+ """LeRobot ACT (0.6.1) on [q, qdot] (``observation.state``, 12) and the two cameras -> normalised chunk [K, 6]."""
+
+ OBS_STATE, IMG = "observation.state", "observation.images."
+
+ def __init__(self, cfg: TrayConfig, stats, device="cuda", pretrained=True):
+ super().__init__()
+ from lerobot.configs.types import FeatureType, PolicyFeature
+ from lerobot.policies.act.configuration_act import ACTConfig
+ from lerobot.policies.act.modeling_act import ACTPolicy
+ self.cfg = cfg
+ inp = {self.OBS_STATE: PolicyFeature(FeatureType.STATE, (cfg.robot_dim,))}
+ for cam in cfg.cameras:
+ inp[self.IMG + cam] = PolicyFeature(FeatureType.VISUAL, (3, cfg.res, cfg.res))
+ out = {"action": PolicyFeature(FeatureType.ACTION, (6,))}
+ ac = ACTConfig(input_features=inp, output_features=out, chunk_size=cfg.chunk, n_action_steps=1,
+ dim_model=cfg.dim_model, n_heads=cfg.n_heads, dim_feedforward=cfg.dim_feedforward,
+ n_encoder_layers=cfg.n_encoder_layers, n_decoder_layers=cfg.n_decoder_layers,
+ use_vae=cfg.use_vae, latent_dim=cfg.latent_dim, n_vae_encoder_layers=cfg.n_vae_encoder_layers,
+ kl_weight=cfg.kl_weight, dropout=cfg.dropout, temporal_ensemble_coeff=None,
+ pretrained_backbone_weights="ResNet18_Weights.IMAGENET1K_V1" if pretrained else None,
+ device=str(device))
+ self.policy = ACTPolicy(ac)
+ for k_, v in stats.items():
+ self.register_buffer(k_, torch.as_tensor(v, dtype=torch.float32).clone())
+
+ def _batch(self, images, robot, tgt_n=None, valid=None):
+ b = {self.OBS_STATE: robot_norm(self, robot)}
+ for i, cam in enumerate(self.cfg.cameras):
+ b[self.IMG + cam] = images[:, i]
+ if tgt_n is not None:
+ b["action"] = tgt_n
+ b["action_is_pad"] = ~valid
+ return b
+
+ def loss(self, images, robot, tgt_n, valid):
+ from lerobot.utils.constants import OBS_IMAGES
+ b = self._batch(images, robot, tgt_n, valid)
+ b[OBS_IMAGES] = [b[k] for k in self.policy.config.image_features]
+ hat, (mu, logs) = self.policy.model(b)
+ m = valid[..., None].float()
+ l1 = ((tgt_n - hat.float()).abs() * m).sum() / (m.sum() * 6).clamp_min(1)
+ info = {"l1": float(l1.detach())}
+ loss = l1
+ if self.cfg.use_vae and logs is not None:
+ kld = (-0.5 * (1 + logs - mu.pow(2) - logs.exp())).sum(-1).mean()
+ info["kld"] = float(kld.detach())
+ loss = loss + kld * self.cfg.kl_weight
+ return loss, info
+
+ @torch.no_grad()
+ def predict(self, images, robot):
+ from lerobot.utils.constants import OBS_IMAGES
+ b = self._batch(images, robot)
+ b[OBS_IMAGES] = [b[k] for k in self.policy.config.image_features]
+ hat, _ = self.policy.model(b)
+ return hat.float()
+
+ def backbone_params(self):
+ return [p for n, p in self.policy.named_parameters() if n.startswith("model.backbone") and p.requires_grad]
+
+
+def build(cfg: TrayConfig, stats, device="cuda", pretrained=True):
+ if cfg.kind == "perstep":
+ return PerStepChunk(cfg, stats, pretrained).to(device)
+ if cfg.kind == "act":
+ return ActChunk(cfg, stats, device, pretrained).to(device)
+ raise ValueError(f"student kind {cfg.kind!r}")
+
+
+def save_student(st, path, **extra):
+ torch.save(dict(kind=st.cfg.kind, cfg=asdict(st.cfg), state_dict=st.state_dict(),
+ stats={k: getattr(st, k).cpu() for k in STAT_KEYS}, **extra), path)
+
+
+def load_student(path, device="cuda"):
+ ck = torch.load(Path(path).expanduser(), map_location="cpu", weights_only=False)
+ cfg = TrayConfig.from_dict(ck["cfg"])
+ st = build(cfg, ck["stats"], device, pretrained=False)
+ st.load_state_dict(ck["state_dict"])
+ return st.eval(), ck
+
+
+def normalise(st, tgt):
+ return (tgt - st.tgt_mean) / st.tgt_std
+
+
+def denormalise(st, p):
+ return p * st.tgt_std + st.tgt_mean
+
+
+@torch.no_grad()
+def val_metrics(st, data, views, rows, bs=256):
+ """Mean absolute error (rad) of the de-normalised targets: first n_exec steps and the whole chunk, per joint."""
+ e1, c1 = torch.zeros(6, device=data.dev), torch.zeros(6, device=data.dev)
+ ea, ca = torch.zeros(6, device=data.dev), torch.zeros(6, device=data.dev)
+ ne = st.cfg.n_exec
+ for s in range(0, len(rows), bs):
+ b = data.batch(rows[s:s + bs])
+ img = V.to_input(views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"]))
+ with torch.autocast(data.dev.type, dtype=torch.bfloat16, enabled=st.cfg.amp):
+ p = denormalise(st, st.predict(img, b["robot"]))
+ err = (p - b["target"]).abs() * b["valid"][..., None]
+ e1 += err[:, :ne].sum((0, 1))
+ c1 += b["valid"][:, :ne].sum()
+ ea += err.sum((0, 1))
+ ca += b["valid"].sum()
+ out = {f"val_mae_exec_j{j}": float(e1[j] / c1[j].clamp_min(1)) for j in range(6)}
+ out["val_mae_exec"] = float(e1.sum() / c1.sum().clamp_min(1))
+ out["val_mae_chunk"] = float(ea.sum() / ca.sum().clamp_min(1))
+ return out
+
+
+def train(data: TraySet, views, cfg: TrayConfig, out_dir, max_steps=4000, init_from=None, log=log_default,
+ val_n=2048, val_every=500, log_every=100, device="cuda", extra_meta=None):
+ """Train (or fine-tune from ``init_from``: weights AND normalisation) a tray student. Writes out_dir/{meta.json,
+ learning_curve.csv, train_summary.json, last.pt}. -> student (eval mode)."""
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ dtype_dev = torch.device(device).type
+ cuda = dtype_dev == "cuda"
+ sync = torch.cuda.synchronize if cuda else (lambda: None)
+ if data.chunk != cfg.chunk:
+ raise ValueError(f"data chunk {data.chunk} != config chunk {cfg.chunk}")
+ torch.manual_seed(cfg.seed)
+ gen = torch.Generator(device=device).manual_seed(cfg.seed)
+ if init_from:
+ st, _ = load_student(init_from, device)
+ st.cfg = cfg
+ else:
+ st = build(cfg, data.stats(), device, pretrained=True)
+ st.train()
+ bb = st.backbone_params()
+ bb_ids = {id(p) for p in bb}
+ rest = [p for p in st.parameters() if p.requires_grad and id(p) not in bb_ids]
+ groups = [dict(params=rest, lr=cfg.lr)] + ([dict(params=bb, lr=cfg.lr_backbone)] if bb else [])
+ opt = torch.optim.AdamW(groups, weight_decay=cfg.weight_decay)
+ base = [g["lr"] for g in opt.param_groups]
+ vgen = torch.Generator(device=device).manual_seed(cfg.seed + 1)
+ vrows = data.sample(min(val_n, max(1, len(data.val_rows))), vgen, "val") if len(data.val_rows) else None
+ meta = dict(cfg=asdict(cfg), data_meta=data.meta, n_train_eps=data.n_train_eps, n_val_eps=data.n_val_eps,
+ train_rows=len(data.train_rows), val_rows=len(data.val_rows), init_from=str(init_from or ""),
+ **(extra_meta or {}))
+ (out / "meta.json").write_text(json.dumps(meta, indent=1, default=str))
+ f = open(out / "learning_curve.csv", "w", newline="")
+ wr = None
+ t0 = time.time()
+ t_render = t_train = 0.0
+ step, samples = 0, 0
+ buf, pos = None, 0
+ agg_loss, agg_n = 0.0, 0
+ while step < max_steps:
+ if buf is None or pos + cfg.batch > cfg.render_batch:
+ tr = time.time()
+ b = data.batch(data.sample(cfg.render_batch, gen))
+ b["rgb"] = views.render(b["q"], b["cube_pos"], b["cube_quat"], b["goal_pose"])
+ b["tgt_n"] = normalise(st, b["target"])
+ sync()
+ t_render += time.time() - tr
+ buf, pos = b, 0
+ tt = time.time()
+ sl = slice(pos, pos + cfg.batch)
+ pos += cfg.batch
+ img = V.to_input(buf["rgb"][sl], cfg.shift_px, gen)
+ frac = min(1.0, (step + 1) / max(1, cfg.warmup))
+ if cfg.cosine and step >= cfg.warmup:
+ u = (step - cfg.warmup) / max(1, max_steps - cfg.warmup)
+ frac = 0.1 + 0.9 * 0.5 * (1 + np.cos(np.pi * u))
+ for g_, lr0 in zip(opt.param_groups, base):
+ g_["lr"] = lr0 * frac
+ with torch.autocast(dtype_dev, dtype=torch.bfloat16, enabled=cfg.amp):
+ loss, _ = st.loss(img, buf["robot"][sl], buf["tgt_n"][sl], buf["valid"][sl])
+ opt.zero_grad(set_to_none=True)
+ loss.backward()
+ gn = torch.nn.utils.clip_grad_norm_(st.parameters(), cfg.grad_clip)
+ opt.step()
+ sync()
+ t_train += time.time() - tt
+ step += 1
+ samples += cfg.batch
+ agg_loss += float(loss.detach())
+ agg_n += 1
+ do_val = vrows is not None and (step % val_every == 0 or step == max_steps)
+ if step % log_every == 0 or do_val:
+ row = dict(step=step, samples=samples, wall_min=round((time.time() - t0) / 60, 3), loss=agg_loss / agg_n,
+ grad_norm=float(gn), lr=opt.param_groups[0]["lr"], render_s=round(t_render, 1),
+ train_s=round(t_train, 1), samples_per_s=round(samples / max(time.time() - t0, 1e-9), 1),
+ gpu_gb=round(torch.cuda.max_memory_allocated() / 1e9, 2) if cuda else 0.0)
+ agg_loss, agg_n = 0.0, 0
+ if do_val:
+ st.eval()
+ row.update(val_metrics(st, data, views, vrows))
+ st.train()
+ if wr is None:
+ vk = ["val_mae_exec", "val_mae_chunk"] + [f"val_mae_exec_j{j}" for j in range(6)]
+ wr = csv.DictWriter(f, fieldnames=[k for k in row if k not in vk] + vk, extrasaction="ignore")
+ wr.writeheader()
+ wr.writerow(row)
+ f.flush()
+ log(json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in row.items()}))
+ st.eval()
+ save_student(st, out / "last.pt", step=step, samples=samples, wall_min=(time.time() - t0) / 60)
+ f.close()
+ summ = dict(steps=step, samples=samples, wall_min=(time.time() - t0) / 60, render_s=t_render, train_s=t_train,
+ views=views.views, views_per_s=views.views / max(views.seconds, 1e-9))
+ (out / "train_summary.json").write_text(json.dumps(summ, indent=1))
+ log(json.dumps(summ))
+ return st
+
+
+class TrayActor:
+ """The student as the driver of ``TrayWorld.run``: renders the worlds' states (top + wrist with the tray), feeds
+ [q, qdot] -> absolute joint targets [B, K, 6] (= q + de-normalised chunk)."""
+
+ def __init__(self, student, views, device="cuda"):
+ self.st, self.views, self.dev = student, views, torch.device(device)
+ self.t_render = self.t_model = 0.0
+ self.calls = 0
+
+ def reset(self, B):
+ pass
+
+ @torch.no_grad()
+ def __call__(self, ws, goal_pose):
+ t0 = time.time()
+ q = ws.q.to(self.dev, torch.float32)
+ cp, cq = ws.cube_pos.to(self.dev, torch.float32), ws.cube_quat.to(self.dev, torch.float32)
+ ok = torch.isfinite(q).all(-1) & torch.isfinite(cp).all(-1) & torch.isfinite(cq).all(-1)
+ q = torch.where(ok[:, None], q, torch.zeros_like(q))
+ cp = torch.where(ok[:, None], cp, torch.tensor([0.2, 0.0, 0.015], device=self.dev))
+ cq = torch.where(ok[:, None], cq, torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.dev))
+ rgb = self.views.render(q, cp, cq, goal_pose.to(self.dev, torch.float32))
+ img = V.to_input(rgb)
+ if self.dev.type == "cuda":
+ torch.cuda.synchronize()
+ t1 = time.time()
+ robot = torch.cat((q, ws.qd.to(self.dev, torch.float32).nan_to_num()), -1)
+ out = []
+ for s in range(0, img.shape[0], 256):
+ with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=self.st.cfg.amp):
+ out.append(denormalise(self.st, self.st.predict(img[s:s + 256], robot[s:s + 256])))
+ delta = torch.cat(out)
+ if self.dev.type == "cuda":
+ torch.cuda.synchronize()
+ self.t_render += t1 - t0
+ self.t_model += time.time() - t1
+ self.calls += 1
+ return (q[:, None, :] + delta).to(ws.q.device, torch.float64)
+
+
+@torch.no_grad()
+def evaluate(actor, tasks, world, teacher, device="cuda", nrd_ckpt=None, workers=0, mj_python=None, horizon=400,
+ n_exec=5, record_states=False, log=None, tw=None, decoder=None, ensemble=None, jaw_lead=0,
+ full_horizon=False):
+ """The student (beta 0) or the teacher (actor None) on all tasks (one batch) -> ``run`` output + summary."""
+ B = len(tasks["seeds"])
+ own = tw is None
+ if own:
+ tw = TrayWorld(world, B, teacher, device, nrd_ckpt, workers, mj_python, horizon, decoder=decoder)
+ w0 = tw.world_steps
+ r = tw.run(tasks, actor, 0.0 if actor is not None else 1.0, None, 0, True, n_exec, record_states, log,
+ ensemble=ensemble, jaw_lead=jaw_lead, full_horizon=full_horizon)
+ r["ensemble"] = np.float64(np.nan if ensemble is None else ensemble)
+ r["jaw_lead"] = np.int64(jaw_lead)
+ r["world_steps"] = np.int64(tw.world_steps - w0)
+ if own:
+ tw.close()
+ if actor is not None:
+ r["render_s"], r["model_s"] = np.float64(actor.t_render), np.float64(actor.t_model)
+ r["world"] = np.array(world)
+ r["decoder_over"] = np.array(json.dumps(tw.decoder_over, default=str))
+ r["summary"] = np.array(json.dumps(summarize(r)))
+ return r
diff --git a/so101_pick_place/code/src/nedm/so101_policy/vision/viral.py b/so101_pick_place/code/src/nedm/so101_policy/vision/viral.py
new file mode 100644
index 0000000000000000000000000000000000000000..50d77a514d474e9a0deea47b0086c1d9ab46ec4d
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/vision/viral.py
@@ -0,0 +1,2962 @@
+"""VIRAL / DoorMan-style camera student of build9 (``~/so101_policy/docs/build9_viral_student.md``).
+
+Student inputs: ONLY the top and wrist RGB images (Newton / Warp renderer, the goal drawn as a flat red colour block,
+``render.so101`` goal "block") and the arm's q (6) and qdot (6). Output: a chunk of ``chunk`` absolute joint targets
+(5 arm joints + jaw, 20 ms each) relative to q at the query, one query every 0.1 s, the first 5 executed through the
+same action layer as the teacher (``joint_env.safety``). Labels: the Markov joint teacher (``joint_env.JointTeacher``)
+at every recorded decision boundary: chunk elements 0-4 = the JT's 5 targets at the query state, 5-9 = the JT's 5
+targets at the next boundary of the same episode (on the path that happened), relative to q at the query.
+
+Pieces:
+
+- ``DRViews``: ``SO101Renderer`` (Newton, top + wrist, block goal, table drawn as a body; tiled ray order 8 x 8) with
+ visual randomisation (``DRConfig``): per row object colours (arm, cube, block, table), camera pose offsets (top and
+ wrist), per call the light direction; ``augment`` per image in torch (brightness, contrast, saturation, hue, noise,
+ blur; VIRAL's kinds, one draw per image).
+- ``ViralNet``: per camera ResNet18 to layer3 (ImageNet, frozen BN) -> spatial-softmax keypoints + pool (build8's
+ per-step encoder); MLP over [image features, normalised q, qdot (+ Gaussian noise on qdot in training)] -> normalised
+ chunk; training-only auxiliary head on the image features -> block x, y, sin / cos 4 yaw and cube x, y, z.
+- ``StudentSet``: ``joint_teacher.run_tasks`` record files -> query rows, chunk targets and validity, aux targets.
+- ``train``: images rendered on the fly (fresh randomisation per sample), masked L1 on the chunk + aux loss.
+- ``Actor``: the student as the driver of ``run_tasks`` (DR fixed per world for an episode, or nominal visuals).
+- ``OnlineDAgger`` (``OnlineConfig``, ``ReplayBuffer``): VIRAL's online loop on one GPU: NRD worlds with automatic
+ resets, fixed teacher / student world slots for the whole run, every world rendered once per decision, the JT
+ labels every world, a GPU replay buffer, a few training steps per decision (``vision_viral.py online``).
+- ``expand_hist``: a student with a robot-input history (``ViralConfig.hist``) from one without (zero weights on the
+ new inputs).
+
+Measured choices (build9 report): qdot noise 0.3 (1.0 and 0.0 were worse), jaw lead 4 at execution (8, build8's
+value, closes the jaw during the descent and opens it before the cube is down), no robot history (3 decisions of
+history: worse), one training step per new sample in the online loop (two: worse).
+
+Real2sim (``~/so101_r2s_claude/docs/integrate.md``; all OFF by default, old configs and checkpoints unchanged):
+
+- ``ViralConfig.scene`` = the render agent's real-scene file (``real_scene_v1.json``, read by
+ ``render.so101.RealScene.from_scene_dict``; ``load_real_setup``): the calibrated ``external`` + ``wrist`` fisheye
+ cameras (crop box of the real 640 x 480 frame per camera by the student-view rules shared with the robot code),
+ the light-box scene and its body groups, its per-world randomisation (``RealDR``: colours, camera poses, mat /
+ walls, tone map), per call its lights and intrinsics (never ``create_default_light``), its tone map and
+ supersampling (inside ``SO101Renderer``), its camera effects (``image_fx``: ``render.camera_fx.ImageFX``) and the
+ config's extra ones (``CamFX``: vignetting, motion blur, blur, white balance, gamma, noise, JPEG; ``fixed_*`` /
+ nominal effects on every image, the random ones on training images only; ``ViewFX``). The scene / calibration
+ sha256 and the crops are pinned in the student config (``pin_real``). ``make_views(cfg, n)`` builds the views of
+ any config.
+- Image lag (``ViralConfig.lag`` / ``lag_range``): the images show the world ``k`` control steps (20 ms) BEFORE the
+ decision (q and qdot stay current); k fixed (evaluation, default ``lag``) or drawn per world per episode
+ (training: ``lag_range``). ``LagHistory`` keeps the states, ``step_tap`` feeds it from any ``JointVecEnv.step``
+ caller (``joint_teacher.run_tasks``); round files record the states (``row_lag``, ``lag_rows``; a lag above
+ ``LAG_REC`` reaches into the decisions before).
+- Image latency v8 (``OnlineConfig.img_lag`` -> ``ImgLagConfig``, 2026-10-23, off by default; measurement
+ ~/so101_r2s_claude/v8/latency/: scripts/lag_fit.py, lag_dist.py -> lag_fit.json, lag_boot.json, lag_dist.json; the
+ robot's images are 28-62 ms older than its joint reading, new every query, independent per camera): in the online
+ loop a lag in ms per world (or per camera: one render call each), drawn at the episode start and again per decision
+ with ``redraw_p``, the images rendered from the state interpolated between the 20 ms states and the goal of then
+ (``LagHistory(goal=True).at``); replaces the integer lag in that loop.
+Studentlab (2026-10-22, ~/so101_studentlab_claude/trials/BUILD.md; all OFF by default, old configs, checkpoints and
+results bit for bit unchanged): ``ViralConfig.cmd_in`` (the previous decision's 5 executed targets - the measured q
+now, / ``cmd_scale``, appended to the robot vector), ``ViralConfig.img_hist`` (the previous decision's images through
+the same encoders, features appended to the head input; ``ReplayBuffer`` links to the previous sample instead of
+copies), ``expand_student`` (zero-init expansion: the same chunk as the given student), ``OnlineConfig.goal_jump``
+(``joint_env.GoalJumpConfig``: goal jumps while the cube is held near the goal). Saved configs keep the old keys while
+the new inputs are off (``cfg_dict``). ``OnlineConfig.light_redraw_p`` (< 1; review 2026-10-23): the per-call light and
+intrinsics stay for several decisions, so the image pairs of the image history share them as on the robot (a change
+cuts the pair). The robot side of the new inputs: ``scripts/so101_policy/real2sim/hw/hw_lib.py`` (``StudentPolicy``,
+``Guard.u_layer``).
+Background randomisation (studentlab external-camera fix, 2026-10-23, ~/so101_studentlab_claude/trials/bgdr/BUILD.md;
+OFF unless the scene file's ``dr`` / ``ViralConfig.real_dr`` sets it; scene v3 does): ``RealDR.floor_turn_deg`` /
+``floor_xy`` / ``wall_end`` (floor box and back-wall end per world) and ``RealDR.bg`` (``nedm.render.bg_dr``: texture,
+clutter, spots, dark-area profile, floor / mat gradients, low texture, mat folds and boundary blur in linear colour
+before the tone map, on the external camera's floor / walls / mat / dark-area pixels only). ``DRViews`` then builds
+the renderer with ``bg_cameras`` (segment output), keeps a placement prior (``bg_prior``) and adds the ``bg_*``
+layers to every per-world draw (zeros in ``nominal_draw``), so the online loop's per-world reset and
+``merge_nominal`` carry them unchanged.
+Scene v4 round (2026-10-23, OFF by default, ~/so101_r2s_claude/v8/scene4): ``RealScene.parts`` may sit on the fixed
+base (scene v4 draws the real table clamp at the base) and ``RealDR.base_addon`` (``nedm.render.base_addon``) puts
+random blocks and cables at the base outline in a share of the worlds; ``load_real_setup`` then adds the slot bodies
+to the scene (``RealScene.addon_slots``), nominal draws keep them hidden; ``DRViews`` draws them on their own
+generator (seed + 917), so the other draws of every per-world reset stay as with them off.
+Gripper look (v12 visual fix, 2026-10-26, OFF by default, ~/so101_r2s_claude/v12/vis): ``RealDR.gripper_look``
+(``nedm.render.gripper_look.GripperLookDR``: per world the albedo of the camera bracket plate and the servo bracket,
+the scene's fitted screws shown / moved / recoloured, 0-4 light or dark marks on the gripper parts in the bottom half
+of the wrist view, a bright plate top edge; exclusion zones for a held-out variant); ``load_real_setup`` adds its
+parts to the scene (``RealScene.look_slots``), ``DRViews`` draws it on its own generator (seed + 921) with the draw key
+``part_pose`` (nominal draws: the scene's look). In the online loop it is a TRAINING-view option
+(``OnlineConfig.gripper_look``, merged into the training views' ``real_dr`` by ``online_views_cfg``, like
+``plate_mm``): the student's saved config, its evaluation views and the robot never see it.
+``OnlineConfig.require_scene_sha256`` makes a run refuse a student whose scene file is not the named one.
+
+- Robot timing and servo in the online loop (``OnlineConfig.dyn`` -> ``joint_env.RobotDynConfig``: command delay with
+ jitter, weaker arm servo, command lag, gravity sag, command noise; per world per episode), robot-like qdot inputs
+ (``qd_robot_p``: ``robot_qd``, the slope of the quantised q, exactly 0 when still), longer episodes (``horizon``,
+ ``hold_cap_s``) and a per-sample scale of the loss-side qdot noise (``qd_noise_zero_p``). Evaluation:
+ ``$NEDM_SO101_DYN`` (``joint_teacher.make_env``).
+- The student's own last command (``ViralConfig.lastcmd``; VIRAL feeds its student the integrated command and the
+ last raw output): 12 more robot inputs [last target - q (6), (last target - the target before) / 20 ms (6)], the
+ targets of the last two 20 ms steps before the decision as executed (sim: ``JointVecEnv.u_exe[:, -1]`` / ``[:, -2]``
+ after the action layer, before the robot dynamics; robot: ``hw_lib.Guard.prev``, the command without the integral
+ correction), 0 at an episode start (``lastcmd_raw``), fixed scales ``LASTCMD_DQ_SCALE`` / ``LASTCMD_V_SCALE`` (not
+ data statistics). Its own zero-initialised input layer (``ViralNet.lastcmd_in``) added to the head's first layer:
+ ``expand_lastcmd`` turns a student without it into one that acts exactly like it at the start. Online loop
+ (``OnlineDAgger``: acting and the buffer, teacher slots too), evaluation (``Actor.env``), robot (``hw_lib``).
+
+Both "last command" inputs are independent options (merge 2026-10-23): the studentlab ``cmd_in`` (the last decision's 5
+executed targets, columns of the head's first layer; robot: ``Guard.u_layer``) and the real2sim ``lastcmd`` (the last
+two 20 ms targets, its own zero-init layer; robot: ``Guard.prev``). With both on, the robot vector is [q, qd, history,
+cmd (n_exec x 6), lastcmd (12)] (``ViralConfig.robot_dim``).
+"""
+from __future__ import annotations
+
+import contextlib
+import csv
+import hashlib
+import json
+import math
+import os
+import time
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from nedm.so101_policy import joint_env as JE
+from nedm.so101_policy.vision import dataset as V
+
+CAMERAS = ("top", "wrist")
+CMD_SCALE = tuple(float(v) for v in JE.LEAD) + (0.1,) # cmd input scale (rad): the lead band (arm), 0.1 rad (jaw)
+
+
+def log_default(s):
+ print(f"[{time.strftime('%H:%M:%S')}] {s}", flush=True)
+
+
+# ---- rendering with visual randomisation ------------------------------------------------------------------------------
+@dataclass
+class DRConfig:
+ on: bool = True
+ # per row (world) object colours: brightness factor and per-channel tint
+ arm_bright: tuple = (0.75, 1.25)
+ arm_tint: float = 0.08
+ cube_bright: tuple = (0.75, 1.25)
+ cube_tint: float = 0.10
+ block_bright: tuple = (0.75, 1.25)
+ block_tint: float = 0.10
+ table_bright: tuple = (0.6, 1.35)
+ table_tint: float = 0.15
+ # camera pose offsets (uniform, world-frame position m, local rotation rad)
+ top_pos: float = 0.01
+ top_rot: float = 0.03
+ wrist_pos: float = 0.002
+ wrist_rot: float = 0.02
+ # light direction per call: elevation (deg above the horizon) and any azimuth
+ light_elev: tuple = (35.0, 85.0)
+ # per image (probability, range); VIRAL's kinds
+ p_bright: float = 0.4
+ bright: tuple = (0.7, 1.5)
+ p_contrast: float = 0.4
+ contrast: tuple = (0.6, 1.4)
+ p_sat: float = 0.4
+ sat: tuple = (0.5, 1.6)
+ p_hue: float = 0.4
+ hue: float = 0.06
+ p_noise: float = 0.25
+ noise: tuple = (0.0, 0.06)
+ p_blur: float = 0.25
+ blur: tuple = (0.1, 1.2)
+
+ @staticmethod
+ def from_dict(d):
+ d = dict(d or {})
+ known = set(DRConfig.__dataclass_fields__)
+ bad = sorted(set(d) - known - {"note"})
+ if bad:
+ raise ValueError(f"unknown DR keys {bad}")
+ return DRConfig(**{k: (tuple(v) if isinstance(v, list) else v) for k, v in d.items() if k in known})
+
+
+def _quat_axis_angle(v):
+ """[..., 3] rotation vectors -> quaternions w x y z."""
+ a = v.norm(dim=-1, keepdim=True)
+ s = torch.where(a > 1e-12, torch.sin(a / 2) / a.clamp_min(1e-12), torch.full_like(a, 0.5))
+ return torch.cat((torch.cos(a / 2), v * s), -1)
+
+
+# ---- real2sim: image-space camera effects -----------------------------------------------------------------------------
+@dataclass
+class CamFX:
+ """Image-space effects of a real camera on float images in 0-1 (``to_input``), one draw per image (each camera
+ separately). ``fixed_*``: what the real camera always has (every sim image: training and both evaluations; 0 =
+ off); the others are random, training images only, each with probability ``p_*``. Order: vignetting, motion blur,
+ blur (optics), then the colour augmentation of ``DRConfig``, then white balance, gamma, sensor noise, JPEG."""
+ fixed_blur: float = 0.0 # Gaussian sigma (output px), e.g. for the real 480 -> 224 area downscale
+ fixed_vignette: float = 0.0 # x * (1 - v r^2), r = 1 at the image corner
+ fixed_jpeg: int = 0 # JPEG quality 1-100 (0: off)
+ p_vignette: float = 0.0
+ vignette: tuple = (0.0, 0.3)
+ p_motion: float = 0.0
+ motion_px: tuple = (0.0, 4.0) # motion blur: line length (output px), any direction
+ p_blur: float = 0.0
+ blur: tuple = (0.2, 1.0) # Gaussian sigma (output px)
+ p_wb: float = 0.0
+ wb: float = 0.08 # white balance: per-channel gain 1 +- wb
+ p_gamma: float = 0.0
+ gamma: tuple = (0.85, 1.2) # x ** g
+ p_noise: float = 0.0
+ shot: tuple = (0.0, 0.004) # sensor noise: variance = shot * x + read ** 2
+ read: tuple = (0.0, 0.02)
+ p_jpeg: float = 0.0
+ jpeg: tuple = (50.0, 95.0) # JPEG quality (standard IJG tables, 4:2:0 chroma)
+
+ @staticmethod
+ def for_cameras(d, cameras):
+ """{CamFX keys, "per_camera": {camera: {keys}}} -> one CamFX per camera (unknown keys refused)."""
+ d = dict(d or {})
+ per = d.pop("per_camera", {}) or {}
+ for k in ("note", "notes"):
+ d.pop(k, None)
+ known = set(CamFX.__dataclass_fields__)
+ bad = sorted((set(d) | {k for v in per.values() for k in v}) - known - {"note"})
+ if bad:
+ raise ValueError(f"unknown camera effect keys {bad}")
+ if set(per) - set(cameras):
+ raise ValueError(f"camera effects for {sorted(set(per) - set(cameras))}: not cameras of {cameras}")
+ out = []
+ for c in cameras:
+ kw = {**d, **{k: v for k, v in (per.get(c) or {}).items() if k != "note"}}
+ out.append(CamFX(**{k: (tuple(v) if isinstance(v, list) else v) for k, v in kw.items()}))
+ return out
+
+
+_JPEG_Y = torch.tensor([[16, 11, 10, 16, 24, 40, 51, 61], [12, 12, 14, 19, 26, 58, 60, 55],
+ [14, 13, 16, 24, 40, 57, 69, 56], [14, 17, 22, 29, 51, 87, 80, 62],
+ [18, 22, 37, 56, 68, 109, 103, 77], [24, 35, 55, 64, 81, 104, 113, 92],
+ [49, 64, 78, 87, 103, 121, 120, 101], [72, 92, 95, 98, 112, 100, 103, 99]], dtype=torch.float32)
+_JPEG_C = torch.tensor([[17, 18, 24, 47, 99, 99, 99, 99], [18, 21, 26, 66, 99, 99, 99, 99],
+ [24, 26, 56, 99, 99, 99, 99, 99], [47, 66, 99, 99, 99, 99, 99, 99]] + [[99] * 8] * 4,
+ dtype=torch.float32)
+
+
+def _dct8(device):
+ k, n = torch.arange(8, dtype=torch.float32), torch.arange(8, dtype=torch.float32)
+ D = torch.cos(math.pi * (2 * n[None] + 1) * k[:, None] / 16) * math.sqrt(2 / 8)
+ D[0] /= math.sqrt(2)
+ return D.to(device)
+
+
+def _jpeg_tables(quality, base):
+ """IJG quality scaling: quality [N] (1-100) -> tables [N, 8, 8]."""
+ q = quality.clamp(1, 100)
+ s = torch.where(q < 50, 5000 / q, 200 - 2 * q)
+ return ((base.to(q.device)[None] * s[:, None, None] + 50) // 100).clamp(1, 255)
+
+
+def _block_q(ch, table, D):
+ """[N, c, h, w] (0-255) -> each 8 x 8 block DCT-quantised with table [N, 8, 8] and back."""
+ N, c, h, w = ch.shape
+ ph, pw = (-h) % 8, (-w) % 8
+ x = F.pad(ch, (0, pw, 0, ph), mode="replicate") if ph or pw else ch
+ H, W = x.shape[2:]
+ b = x.reshape(N, c, H // 8, 8, W // 8, 8).permute(0, 1, 2, 4, 3, 5) - 128.0 # [N, c, hb, wb, 8, 8]
+ co = D @ b @ D.T
+ t = table[:, None, None, None]
+ co = torch.round(co / t) * t
+ b = D.T @ co @ D + 128.0
+ return b.permute(0, 1, 2, 4, 3, 5).reshape(N, c, H, W)[:, :, :h, :w]
+
+
+def jpeg_sim(x, quality):
+ """JPEG round trip of float images x [N, 3, H, W] in 0-1 at ``quality`` [N]: YCbCr (JFIF), 4:2:0 chroma
+ (2 x 2 mean, bilinear back), 8 x 8 DCT with the standard tables scaled by quality, 8-bit output."""
+ D = _dct8(x.device)
+ v = x * 255.0
+ r, g, b = v[:, 0:1], v[:, 1:2], v[:, 2:3]
+ y = 0.299 * r + 0.587 * g + 0.114 * b
+ cb = -0.168736 * r - 0.331264 * g + 0.5 * b + 128.0
+ cr = 0.5 * r - 0.418688 * g - 0.081312 * b + 128.0
+ H, W = x.shape[2:]
+ c = F.avg_pool2d(torch.cat((cb, cr), 1), 2, ceil_mode=True)
+ y = _block_q(y, _jpeg_tables(quality, _JPEG_Y), D)
+ c = _block_q(c, _jpeg_tables(quality, _JPEG_C), D)
+ c = F.interpolate(c, size=(H, W), mode="bilinear", align_corners=False)
+ cb, cr = c[:, :1] - 128.0, c[:, 1:] - 128.0
+ out = torch.cat((y + 1.402 * cr, y - 0.344136 * cb - 0.714136 * cr, y + 1.772 * cb), 1)
+ return torch.round(out.clamp(0, 255)) / 255.0
+
+
+def _gauss(x, sig):
+ """Separable Gaussian blur of x [N, 3, H, W] with sigma [N] (px; <= 0.05: unchanged)."""
+ N = x.shape[0]
+ rad = int(min(6, max(1, math.ceil(3 * float(sig.max())))))
+ k = torch.arange(-rad, rad + 1, device=x.device, dtype=x.dtype)
+ s = sig.clamp_min(0.05).to(x.dtype)
+ w = torch.exp(-(k[None] ** 2) / (2 * s[:, None] ** 2))
+ w = w / w.sum(-1, keepdim=True)
+ xb = x.reshape(1, N * 3, *x.shape[2:])
+ wk = w.repeat_interleave(3, 0)
+ xb = F.conv2d(F.pad(xb, (rad, rad, 0, 0), mode="replicate"), wk[:, None, None, :], groups=N * 3)
+ xb = F.conv2d(F.pad(xb, (0, 0, rad, rad), mode="replicate"), wk[:, None, :, None], groups=N * 3)
+ return torch.where((sig > 0.05)[:, None, None, None], xb.reshape_as(x), x)
+
+
+def _motion(x, length, angle, taps=7):
+ """Motion blur: the mean of ``taps`` copies of x [N, 3, H, W] shifted along ``angle`` [N] over ``length`` [N] px."""
+ N, _, H, W = x.shape
+ theta = torch.zeros(N, 2, 3, device=x.device, dtype=x.dtype)
+ theta[:, 0, 0] = theta[:, 1, 1] = 1.0
+ grid = F.affine_grid(theta, (N, 3, H, W), align_corners=False)
+ acc = torch.zeros_like(x)
+ for t in torch.linspace(-0.5, 0.5, taps).tolist():
+ g = grid.clone()
+ g[..., 0] += (2.0 / W) * (t * length * torch.cos(angle))[:, None, None]
+ g[..., 1] += (2.0 / H) * (t * length * torch.sin(angle))[:, None, None]
+ acc += F.grid_sample(x, g, mode="bilinear", padding_mode="border", align_corners=False)
+ return acc / taps
+
+
+def _vignette(x, v):
+ N, _, H, W = x.shape
+ yy = (torch.arange(H, device=x.device, dtype=x.dtype) + 0.5) / H - 0.5
+ xx = (torch.arange(W, device=x.device, dtype=x.dtype) + 0.5) / W - 0.5
+ r2 = (xx[None, :] ** 2 + yy[:, None] ** 2) / 0.5 # 1 at the corners
+ return x * (1 - v.to(x.dtype)[:, None, None, None] * r2[None, None])
+
+
+def _rand(N, gen, dev):
+ return lambda lo, hi: lo + (hi - lo) * torch.rand(N, device=dev, generator=gen)
+
+
+def fx_optics(x, fx: CamFX, gen=None, random=False):
+ """Vignetting, motion blur, blur (``CamFX``) of x [N, 3, H, W] in 0-1."""
+ N, dev = x.shape[0], x.device
+ if fx.fixed_vignette > 0:
+ x = _vignette(x, torch.full((N,), float(fx.fixed_vignette), device=dev))
+ if random and fx.p_vignette > 0:
+ u = _rand(N, gen, dev)
+ x = _vignette(x, (u(0, 1) < fx.p_vignette).float() * u(*fx.vignette))
+ if random and fx.p_motion > 0:
+ u = _rand(N, gen, dev)
+ on = u(0, 1) < fx.p_motion
+ L, a = on.float() * u(*fx.motion_px), u(0, 2 * math.pi)
+ if bool(on.any()):
+ x = torch.where(on[:, None, None, None], _motion(x, L, a), x)
+ sig = torch.full((N,), float(fx.fixed_blur), device=dev)
+ if random and fx.p_blur > 0:
+ u = _rand(N, gen, dev)
+ on = u(0, 1) < fx.p_blur
+ sig = torch.where(on, torch.sqrt(sig ** 2 + u(*fx.blur) ** 2), sig)
+ if bool((sig > 0.05).any()):
+ x = _gauss(x, sig)
+ return x.clamp(0, 1)
+
+
+def fx_sensor(x, fx: CamFX, gen=None, random=False):
+ """White balance, gamma, sensor noise, JPEG (``CamFX``) of x [N, 3, H, W] in 0-1."""
+ N, dev = x.shape[0], x.device
+ if random and fx.p_wb > 0:
+ u = _rand(N, gen, dev)
+ on = (u(0, 1) < fx.p_wb).float()[:, None]
+ gain = 1 + on * (2 * torch.rand(N, 3, device=dev, generator=gen) - 1) * fx.wb
+ x = (x * gain[:, :, None, None]).clamp(0, 1)
+ if random and fx.p_gamma > 0:
+ u = _rand(N, gen, dev)
+ on = u(0, 1) < fx.p_gamma
+ g = torch.where(on, u(*fx.gamma), torch.ones(N, device=dev))
+ x = x.clamp_min(0) ** g[:, None, None, None]
+ if random and fx.p_noise > 0:
+ u = _rand(N, gen, dev)
+ on = (u(0, 1) < fx.p_noise).float()[:, None, None, None]
+ sh, rd = u(*fx.shot)[:, None, None, None], u(*fx.read)[:, None, None, None]
+ x = (x + on * torch.sqrt(sh * x.clamp_min(0) + rd ** 2) * torch.randn(x.shape, device=dev, generator=gen))
+ x = x.clamp(0, 1)
+ q = torch.full((N,), float(fx.fixed_jpeg), device=dev)
+ if random and fx.p_jpeg > 0:
+ u = _rand(N, gen, dev)
+ on = u(0, 1) < fx.p_jpeg
+ r = u(*fx.jpeg)
+ q = torch.where(on & ((q <= 0) | (r < q)), r, q) # the stronger of the fixed and the random JPEG
+ if bool((q > 0).any()):
+ i = (q > 0).nonzero().flatten()
+ x = x.clone()
+ x[i] = jpeg_sim(x[i], q[i])
+ return x
+
+
+# ---- real2sim: the real scene of a student config ---------------------------------------------------------------------
+REAL_CAMS = ("external", "wrist")
+# top-level keys of a scene file that ``RealScene.from_scene_dict`` reads (others: a warning) and meta keys
+SCENE_KEYS = {"version", "calib", "geometry", "colors", "light", "student_view", "tone", "render", "dr", "image_fx"}
+SCENE_META_KEYS = {"note", "notes", "source", "sources", "evidence", "created", "author", "description", "measured",
+ "status", "todo"}
+
+
+def _sha(path):
+ return hashlib.sha256(Path(path).expanduser().read_bytes()).hexdigest()
+
+
+@dataclass
+class RealSetup:
+ """A config's resolved real2sim scene (``load_real_setup``)."""
+ scene_path: str
+ scene_sha256: str
+ calib_path: str
+ calib_sha256: str
+ real: object # nedm.render.so101.RealScene (crop None: the student-view rules)
+ crops: dict # camera -> [x, y, w, h] of the real image (the resolved student view)
+ dr: object # nedm.render.so101.RealDR (the scene's "dr" + cfg.real_dr)
+ image_fx: dict | None # camera -> render.camera_fx.ImageFX dict; None: none
+ cam_fx: dict # CamFX keys (+ per_camera): the config's extra student-side effects
+
+
+def _merge(base: dict, over: dict) -> dict:
+ out = {k: (dict(v) if isinstance(v, dict) else v) for k, v in (base or {}).items()}
+ for k, v in (over or {}).items():
+ out[k] = {**out.get(k, {}), **v} if isinstance(v, dict) and isinstance(out.get(k), dict) else v
+ return out
+
+
+def load_real_setup(cfg: "ViralConfig", geometry_over: dict | None = None) -> RealSetup:
+ """The real scene of ``cfg`` (``cfg.scene`` set): the render agent's scene file (``real_scene_v1.json`` layout,
+ read by ``nedm.render.so101.RealScene.from_scene_dict``: calib, geometry, colors, light, student_view, tone,
+ render.supersample, dr, image_fx) or a bare calibration contract (``RealScene`` defaults). ``cfg.calib`` (if set)
+ replaces the file's calibration path (a relative path in the file is relative to the file). The crop of every
+ calibrated camera follows the student-view rules (``nedm.render.student_view``, shared with the robot code);
+ ``cfg.crops`` is only the pinned record (``pin_real``). ``cfg.real_dr`` is merged over the scene's ``dr``,
+ ``cfg.cam_fx`` adds student-side image effects (``CamFX``). ``geometry_over``: evaluation-only overrides of the
+ scene file's ``geometry`` section (e.g. ``table_plane``), applied after the file is read (the sha256 stays the
+ file's own)."""
+ from nedm.render.so101 import RealDR, RealScene, load_calibration
+ sp = Path(cfg.scene).expanduser()
+ raw = json.loads(sp.read_text())
+ if geometry_over:
+ bad = sorted(set(geometry_over) - set(RealScene.GEOMETRY_KEYS))
+ if bad or not str(raw.get("version", "")).startswith("real_scene"):
+ raise ValueError(f"geometry_over {sorted(geometry_over)}: needs a scene file and RealScene geometry keys")
+ raw["geometry"] = {**(raw.get("geometry") or {}), **geometry_over}
+ is_scene = str(raw.get("version", "")).startswith("real_scene")
+ if is_scene:
+ odd = sorted(k for k in raw if k not in SCENE_KEYS | SCENE_META_KEYS and not k.startswith("_"))
+ if odd:
+ print(f"WARNING: scene file {sp}: keys {odd} are not read by RealScene.from_scene_dict", flush=True)
+ calib_p = cfg.calib or raw.get("calib") or ""
+ if not calib_p:
+ raise ValueError(f"no calibration: set ViralConfig.calib or the scene file's 'calib' ({sp})")
+ cp = Path(calib_p).expanduser()
+ if not cp.is_absolute():
+ cp = (sp.parent / cp).resolve()
+ calib = load_calibration(cp)
+ real = RealScene.from_scene_dict(raw, calib=calib, source=str(sp))
+ else:
+ if cfg.calib:
+ raise ValueError(f"{sp} is a calibration contract, not a scene file: leave ViralConfig.calib empty")
+ cp, real = sp, RealScene(calib=raw, source=str(sp))
+ crops = {}
+ for c in cfg.cameras:
+ if c not in REAL_CAMS:
+ continue
+ v = real.view(c, cfg.res)
+ if v is not None and (tuple(v.out_wh) != (cfg.res, cfg.res) or v.interp != "area"):
+ raise ValueError(f"student view of {c!r}: output {tuple(v.out_wh)} {v.interp!r}, the student needs "
+ f"{cfg.res} x {cfg.res} 'area' (what the renderer matches)")
+ crops[c] = [int(x) for x in real.crop_box(c, cfg.res)]
+ dr = RealDR.from_dict(_merge(getattr(real, "dr", None) or {}, cfg.real_dr or {}))
+ if dr.addon_on: # base add-on randomisation (scene v4 round): its slot bodies in the scene
+ from dataclasses import replace as _replace
+ real = _replace(real, addon_slots=dr.addon_slots())
+ if getattr(dr, "look_on", False): # v12 gripper look: its slot parts and movable screws in the scene
+ from dataclasses import replace as _replace
+ real = _replace(real, look_slots=dr.look_slots(real))
+ ifx = getattr(real, "image_fx", None)
+ if ifx:
+ ifx = {k: v for k, v in ifx.items() if k not in ("note", "notes")}
+ per = set(ifx) <= set(REAL_CAMS) | {"top", "front"}
+ if per and [c for c in cfg.cameras if c not in ifx]:
+ raise ValueError(f"image_fx: no entry for cameras {[c for c in cfg.cameras if c not in ifx]}")
+ ifx = {c: dict(ifx[c]) if per else dict(ifx) for c in cfg.cameras}
+ else:
+ ifx = None
+ cam_fx = dict(cfg.cam_fx or {})
+ CamFX.for_cameras(cam_fx, cfg.cameras) # validate now
+ return RealSetup(str(sp), _sha(sp), str(cp), _sha(cp), real, crops, dr, ifx, cam_fx)
+
+
+def pin_real(cfg: "ViralConfig", allow_change=False) -> "ViralConfig":
+ """Fix the real scene in a (training) config: the resolved crops and the sha256 of the scene and calibration
+ files (checked by ``make_views``: a changed file is refused unless ``allow_change``). Old configs: unchanged."""
+ if not cfg.scene:
+ return cfg
+ rs = load_real_setup(cfg)
+ for k, v in (("scene_sha256", rs.scene_sha256), ("calib_sha256", rs.calib_sha256)):
+ old = getattr(cfg, k)
+ if old and old != v and not allow_change:
+ raise ValueError(f"{k}: the file changed since this student was configured ({old[:12]} -> {v[:12]}); "
+ "pass allow_change (--allow-scene-change) to use the new file knowingly")
+ setattr(cfg, k, v)
+ if cfg.crops and {c: list(b) for c, b in cfg.crops.items()} != rs.crops and not allow_change:
+ raise ValueError(f"crops {cfg.crops} != the scene's student view {rs.crops}")
+ cfg.crops = {c: list(b) for c, b in rs.crops.items()}
+ return cfg
+
+
+def make_views(cfg: "ViralConfig", num_worlds, seed=0, device="cuda", allow_change=False, geometry_over=None, **kw):
+ """The student's views for config ``cfg``: build9's sim scene (``cfg.scene`` empty; exactly the old ``DRViews``
+ call) or the real scene (``load_real_setup``; the scene / calibration sha256 and the crops pinned in ``cfg`` must
+ match the files, unless ``allow_change``). ``geometry_over``: evaluation-only scene geometry overrides (real scene
+ only, ``load_real_setup``), e.g. ``{"table_plane": (c0, c1, c2)}`` for a lowered table."""
+ if not cfg.scene:
+ if geometry_over:
+ raise ValueError("geometry_over needs the real scene (cfg.scene)")
+ return DRViews(num_worlds, cfg.res, cfg.cameras, dr=DRConfig.from_dict(cfg.dr), seed=seed, device=device, **kw)
+ rs = load_real_setup(cfg, geometry_over)
+ msgs = []
+ for k, v in (("scene_sha256", rs.scene_sha256), ("calib_sha256", rs.calib_sha256)):
+ old = getattr(cfg, k)
+ if old and old != v:
+ msgs.append(f"{k} of the student {old[:12]} != the file's {v[:12]} "
+ f"({rs.scene_path if 'scene' in k else rs.calib_path})")
+ if cfg.crops and {c: list(b) for c, b in cfg.crops.items()} != rs.crops:
+ msgs.append(f"crops of the student {cfg.crops} != the scene's student view {rs.crops}")
+ if msgs:
+ if not allow_change:
+ raise ValueError("; ".join(msgs) + ": pass --allow-scene-change to render with the new files")
+ print("WARNING: " + "; ".join(msgs), flush=True)
+ return DRViews(num_worlds, cfg.res, cfg.cameras, dr=DRConfig.from_dict(cfg.dr), seed=seed, device=device, real=rs,
+ **kw)
+
+
+class ViewFX:
+ """Image-space model of the real cameras for ``to_input``: the config's ``CamFX`` (per camera) and the scene
+ file's ``image_fx`` (``nedm.render.camera_fx.ImageFX`` per camera; nominal effects always, one random draw per
+ image on training images). Order: CamFX optics, the DRConfig colour augmentation, CamFX sensor, ImageFX."""
+
+ def __init__(self, cam_fx: list, image_fx: list | None):
+ self.cam, self.image = list(cam_fx), (list(image_fx) if image_fx is not None else None)
+
+ @staticmethod
+ def from_setup(rs: RealSetup, cameras):
+ img = None
+ if rs.image_fx is not None:
+ from nedm.render.camera_fx import ImageFX
+ img = [ImageFX.from_dict(rs.image_fx[c]) for c in cameras]
+ for c, f in zip(cameras, img):
+ if f.extra:
+ raise ValueError(f"image_fx[{c!r}]: unknown keys {sorted(f.extra)}")
+ return ViewFX(CamFX.for_cameras(rs.cam_fx, cameras), img)
+
+ def apply(self, x, gen=None, random=False, augment_fn=None):
+ """x [n, C, 3, H, W] float 0-1 -> same."""
+ n, C = x.shape[:2]
+ x = torch.stack([fx_optics(x[:, c], self.cam[c], gen, random) for c in range(C)], 1)
+ if augment_fn is not None:
+ x = augment_fn(x.reshape(n * C, *x.shape[2:])).reshape(x.shape)
+ x = torch.stack([fx_sensor(x[:, c], self.cam[c], gen, random) for c in range(C)], 1)
+ if self.image is not None:
+ out = []
+ for c in range(C):
+ img = x[:, c].permute(0, 2, 3, 1).contiguous()
+ draw = self.image[c].draw(n, gen, x.device) if random else None
+ out.append(self.image[c].apply(img, draw, gen).permute(0, 3, 1, 2))
+ x = torch.stack(out, 1)
+ return x
+
+
+class DRViews:
+ """The student's cameras with visual randomisation (module docstring). ``render(q, cube_pos, cube_quat, goal_pose,
+ dr=None)``: dr = None (nominal visuals) or a dict of per-row draws (``draw``): colors [n, nb, 3], cam_dpos [n, C, 3],
+ cam_drot [n, C, 3]; the light direction is drawn per call when ``light`` is True. -> uint8 [n, C, H, W, 3].
+
+ ``real`` (a ``RealSetup``; ``make_views``): the real scene instead (module docstring): draws = colors [n, nb, 3],
+ cam_offset [n, C, 6], env_pose [n, n_env, 7] (``RealDR``) and exposure [n, C] (tone map only), and with the
+ background randomisation on (``RealDR.bg``, scene v3; ``bg_cams``) the background layers ``bg_*`` (per world for
+ the episode, ``nedm.render.bg_dr``); the scene's lights (randomised per call by ``RealDR.lights`` when ``light``);
+ ``fx`` = the cameras' ``CamFX`` (None: sim scene). With the plate thickness randomisation (v8,
+ ``RealDR.plate_thickness``; ``plate_on``) the per-world plate thickness ``plate_dz`` [n] as well (visual only;
+ the renderer is built with its plate depth; ``render(..., held=)`` [n] bool: cubes the jaws hold are not lifted).
+ ``render(..., plane=)`` [n, 3] (real scene without its own table_plane, ``table_render_ok``): every world's table
+ plane (``SO101Scene`` world_plane; v8 ``OnlineConfig.table_render``). With the gripper look (v12,
+ ``RealDR.gripper_look``; ``look_on``) the draws carry ``part_pose`` [n, K, 7] (the look parts' local poses).
+
+ Per-call state (studentlab image history): ``render(..., keep=True)`` keeps the last call's random light (and
+ intrinsics) instead of a new draw (no random numbers used); ``call_id`` counts the changes of the per-call state
+ (a new random draw, or random -> nominal), so a caller can tell whether two calls share it."""
+
+ def __init__(self, num_worlds, res=224, cameras=CAMERAS, backend="newton", tiled=True, shadows=True,
+ top_eye=V.TOP_EYE, top_target=V.TOP_TARGET, dr: DRConfig | None = None, seed=0, device="cuda",
+ real: RealSetup | None = None):
+ self.real, self.fx = real, None
+ self.table_render_ok = False # per-world table planes (v8; the real scene without its own table_plane)
+ if real is not None:
+ self._init_real(num_worlds, res, cameras, backend, tiled, shadows, dr, seed, device, real)
+ self.table_render_ok = real.real.table_plane is None
+ return
+ from nedm.render.so101 import SO101Renderer
+ self.r = SO101Renderer(int(num_worlds), width=int(res), height=int(res), backend=backend, cameras=tuple(cameras),
+ top_eye=tuple(top_eye), top_target=tuple(top_target), shadows=shadows, goal="block",
+ table_body=True)
+ if tiled and backend == "newton":
+ from newton._src.sensors.warp_raytrace.types import RenderOrder
+ rc = self.r.renderer.backend._camera.render_config
+ rc.render_order, rc.tile_width, rc.tile_height = RenderOrder.TILED, 8, 8
+ self.num_worlds, self.res, self.cameras = int(num_worlds), int(res), tuple(cameras)
+ self.dr = dr or DRConfig()
+ self.dev = torch.device(device)
+ self.calls, self.views, self.seconds = 0, 0, 0.0
+ sc = self.r.scene
+ nb = len(sc.body_names)
+ self.nb = nb
+ self.base = torch.tensor([m.color for m in sc.scene.bodies], dtype=torch.float32, device=self.dev) # [nb, 3]
+ n_arm = len(sc.mesh_body)
+ self.groups = dict(arm=slice(0, n_arm), cube=slice(n_arm, n_arm + sc.cube_meshes),
+ block=slice(n_arm + sc.cube_meshes, n_arm + sc.cube_meshes + sc.goal_meshes),
+ table=slice(nb - 1, nb))
+ self.gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 911)
+ self._colors_nominal = True
+ self.light_default = (-0.57735026, 0.57735026, -0.57735026)
+ self._light_state = "nominal"
+ self.call_id = 0 # changes of the per-call state (class docstring)
+
+ # -- the real scene (real2sim) --
+ def _init_real(self, num_worlds, res, cameras, backend, tiled, shadows, dr, seed, device, rs: RealSetup):
+ from nedm.render.so101 import SO101Renderer
+ if backend != "newton":
+ raise NotImplementedError("the real scene needs the newton backend")
+ self.num_worlds, self.res, self.cameras = int(num_worlds), int(res), tuple(cameras)
+ self.dr = dr or DRConfig()
+ self.dev = torch.device(device)
+ self.calls, self.views, self.seconds = 0, 0, 0.0
+ # the renderer checks at construction that no body sits in front of a calibrated camera (check_near)
+ self.bg_cams = rs.dr.bg_cameras(self.cameras) # background layers (RealDR.bg; none: off, as before)
+ bgkw = dict(bg_cameras=self.bg_cams, bg_dark_groups=rs.dr.bg_dr().dark_groups) if self.bg_cams else {}
+ self.plate_on = bool(getattr(rs.dr, "plate_on", False)) # v8: plate thickness (RealDR.plate_thickness)
+ if self.plate_on:
+ bgkw["plate_depth"] = rs.dr.plate_depth()
+ self.r = SO101Renderer(self.num_worlds, width=self.res, height=self.res, backend="newton", cameras=self.cameras,
+ shadows=shadows, goal="block", real=rs.real, **bgkw)
+ self.bg_prior = self.r.bg_prior().to(device) if self.bg_cams else None # clutter / spot placement
+ if tiled:
+ from newton._src.sensors.warp_raytrace.types import RenderOrder
+ rc = self.r.renderer.backend._camera.render_config
+ rc.render_order, rc.tile_width, rc.tile_height = RenderOrder.TILED, 8, 8
+ sc = self.r.scene
+ self.nb = len(sc.body_names)
+ self.base = torch.tensor([m.color for m in sc.scene.bodies], dtype=torch.float32, device=self.dev)
+ self.groups = {g: list(v) for g, v in sc.groups.items()}
+ self.env0 = sc.env_pose.to(self.dev)
+ self.tone0 = sc.tone_params.to(self.dev) if getattr(sc, "tone_params", None) is not None else None
+ self.rdr = rs.dr
+ self.gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 911)
+ self.light_gen = torch.Generator().manual_seed(int(seed) + 913) # per-call draws (lights, intrinsics): CPU
+ # base add-ons (RealDR.base_addon): their own generator, so every other draw (each per-world reset of the
+ # online loop) is the same with them on or off (paired arms); None when off (nothing changes)
+ self.addon_gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 917) if rs.dr.addon_on else None
+ # v12 gripper look (RealDR.gripper_look): its own generator as well (None when off: nothing changes)
+ self.look_on = bool(getattr(rs.dr, "look_on", False))
+ self.look_gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 921) if self.look_on else None
+ self.lights0 = [dict(lt) for lt in rs.real.lights]
+ self.models0 = list(sc.camera_models)
+ self.intrinsics_dr = float(getattr(self.rdr, "focal", 0.0)) > 0 or float(getattr(self.rdr, "pp_px", 0.0)) > 0
+ self._call_state = "nominal"
+ self.call_id = 0 # changes of the per-call state (class docstring)
+ self.fx = ViewFX.from_setup(rs, self.cameras)
+
+ def nominal_draw(self, n):
+ """Per-row draws with the nominal visuals (real scene)."""
+ C = len(self.cameras)
+ d = dict(colors=self.base.expand(n, self.nb, 3).clone(),
+ cam_offset=torch.zeros(n, C, 6, device=self.dev),
+ env_pose=self.env0.expand(n, *self.env0.shape).clone())
+ if self.tone0 is not None:
+ d["tone"] = self.tone0.expand(n, *self.tone0.shape).clone()
+ if self.bg_cams:
+ d.update(self.rdr.bg_nominal(n, self.cameras, self.res, self.dev))
+ if self.plate_on: # the scene's own plate
+ d["plate_dz"] = torch.zeros(n, dtype=torch.float64, device=self.dev)
+ if self.look_on: # v12: the scene's own gripper look (screws in place, marks and edge hidden)
+ p0 = self.r.scene.look_pose0.to(self.dev)
+ d["part_pose"] = p0.expand(n, *p0.shape).clone()
+ return d
+
+ def merge_nominal(self, d, nominal):
+ """Rows ``nominal`` [n] bool of the draws ``d`` replaced by the nominal visuals (real scene)."""
+ nd = self.nominal_draw(len(nominal))
+ return {k: torch.where(nominal.view(-1, *([1] * (v.dim() - 1))), nd[k].to(v), v) for k, v in d.items()}
+
+ def _draw_real(self, n):
+ kw = {"addon_generator": self.addon_gen} if self.addon_gen is not None else {}
+ if self.look_gen is not None:
+ kw["look_generator"] = self.look_gen
+ d = self.rdr.draw(self.r.scene, n, self.gen, device=self.dev, res=self.res, bg_prior=self.bg_prior, **kw)
+ return {k: v.to(self.dev) for k, v in d.items()}
+
+ def _per_call_real(self, nominal, keep=False):
+ """Lights (and the intrinsics, if the scene randomises them) of the call: shared by all worlds. ``keep``: a
+ random call keeps the last random draw (no new draw) if the last call was random as well."""
+ if nominal:
+ if self._call_state != "nominal":
+ self.r.set_lights(self.lights0)
+ if self.intrinsics_dr:
+ self.r.set_camera_models(self.models0)
+ self._call_state = "nominal"
+ self.call_id += 1
+ return
+ if keep and self._call_state == "random":
+ return
+ self.r.set_lights(self.rdr.lights(self.lights0, self.light_gen))
+ if self.intrinsics_dr:
+ self.r.set_camera_models(self.rdr.camera_models(self.r.scene, self.light_gen, out_res=self.res))
+ self._call_state = "random"
+ self.call_id += 1
+
+ def _render_real(self, q, cube_pos, cube_quat, goal_pose, dr=None, light=None, keep=False, plane=None, held=None):
+ t0 = time.time()
+ if plane is not None and not self.table_render_ok:
+ raise ValueError("render(plane=): the real scene has its own table_plane")
+ self._per_call_real((dr is None) if light is None else not light, keep)
+ out = []
+ for s in range(0, q.shape[0], self.num_worlds):
+ e = min(q.shape[0], s + self.num_worlds)
+ d = None if dr is None else {k: v[s:e] for k, v in dr.items()}
+ rkw = {}
+ if plane is not None:
+ rkw["world_plane"] = plane[s:e]
+ if held is not None:
+ rkw["cube_held"] = held[s:e]
+ out.append(self.r.render_dr(q[s:e], cube_pos[s:e], cube_quat[s:e], goal_pose[s:e], draw=d,
+ **rkw).to(self.dev))
+ rgb = torch.cat(out) if len(out) > 1 else out[0]
+ self.calls += 1
+ self.views += q.shape[0] * len(self.cameras)
+ self.seconds += time.time() - t0
+ return rgb
+
+ # -- draws --
+ def _u(self, n, lo, hi, *shape):
+ return lo + (hi - lo) * torch.rand(n, *shape, device=self.dev, generator=self.gen)
+
+ def draw(self, n):
+ """Per-row randomisation draws for n rows."""
+ if self.real is not None:
+ return self._draw_real(n)
+ d = self.dr
+ cols = self.base.expand(n, self.nb, 3).clone()
+ for g, (br, ti) in dict(arm=(d.arm_bright, d.arm_tint), cube=(d.cube_bright, d.cube_tint),
+ block=(d.block_bright, d.block_tint), table=(d.table_bright, d.table_tint)).items():
+ sl = self.groups[g]
+ b = self._u(n, br[0], br[1], 1, 1)
+ t = self._u(n, 1 - ti, 1 + ti, 1, 3)
+ cols[:, sl] = (cols[:, sl] * b * t).clamp(0, 1)
+ C = len(self.cameras)
+ pos = torch.tensor([d.wrist_pos if c == "wrist" else d.top_pos for c in self.cameras], device=self.dev)
+ rot = torch.tensor([d.wrist_rot if c == "wrist" else d.top_rot for c in self.cameras], device=self.dev)
+ dpos = self._u(n, -1.0, 1.0, C, 3) * pos[None, :, None]
+ drot = self._u(n, -1.0, 1.0, C, 3) * rot[None, :, None]
+ return dict(colors=cols, cam_dpos=dpos, cam_drot=drot)
+
+ def _light(self, nominal, keep=False):
+ import warp as wp
+ if nominal:
+ d = self.light_default
+ if self._light_state != "nominal":
+ self._light_state = "nominal"
+ self.call_id += 1
+ else:
+ if keep and self._light_state == "random":
+ return # the last call's random light stays
+ self._light_state = "random"
+ self.call_id += 1
+ el = math.radians(float(self._u(1, *self.dr.light_elev)[0]))
+ az = float(self._u(1, 0.0, 2 * math.pi)[0])
+ d = (-math.cos(el) * math.cos(az), -math.cos(el) * math.sin(az), -math.sin(el))
+ self.r.renderer.backend._camera.utils.create_default_light(self.r.shadows, direction=wp.vec3f(*d))
+
+ @torch.no_grad()
+ def render(self, q, cube_pos, cube_quat, goal_pose, dr=None, light=None, keep=False, plane=None, held=None):
+ """``keep``: keep the last call's random per-call state; ``plane`` / ``held`` (real scene): per-world table
+ planes / held cubes (class docstring)."""
+ if self.real is not None:
+ if plane is None and held is None:
+ return self._render_real(q, cube_pos, cube_quat, goal_pose, dr, light, keep)
+ return self._render_real(q, cube_pos, cube_quat, goal_pose, dr, light, keep, plane, held)
+ if plane is not None or held is not None:
+ raise ValueError("render(plane=, held=): the real scene only")
+ from nedm.render.so101 import qmul, wxyz, xyzw
+ t0 = time.time()
+ nominal = dr is None
+ self._light(nominal if light is None else not light, keep)
+ out = []
+ for s in range(0, q.shape[0], self.num_worlds):
+ e = min(q.shape[0], s + self.num_worlds)
+ n = e - s
+ body_q, cam_q = self.r.scene.transforms(q[s:e], cube_pos[s:e], cube_quat[s:e], goal_pose[s:e])
+ if dr is not None:
+ cq = cam_q.to(self.dev, torch.float32).clone()
+ cq[..., :3] = cq[..., :3] + dr["cam_dpos"][s:e].to(cq)
+ dq = _quat_axis_angle(dr["cam_drot"][s:e].to(cq))
+ cq[..., 3:] = xyzw(qmul(wxyz(cq[..., 3:]), dq))
+ cam_q = cq
+ cols = dr["colors"][s:e]
+ else:
+ cols = self.base.expand(n, self.nb, 3)
+ if n < self.num_worlds:
+ pad = self.num_worlds - n
+ body_q = torch.cat([body_q, body_q[:1].expand(pad, *body_q.shape[1:])])
+ cam_q = torch.cat([cam_q, cam_q[:1].expand(pad, *cam_q.shape[1:])])
+ cols = torch.cat([cols, cols[:1].expand(pad, *cols.shape[1:])])
+ if not (nominal and self._colors_nominal):
+ self.r._newton_colors(cols.float().cpu())
+ self._colors_nominal = nominal
+ frames = self.r.renderer.render(cam_q, body_q=body_q)
+ out.append(frames.rgb_torch()[:n].clone(memory_format=torch.contiguous_format))
+ rgb = torch.cat(out) if len(out) > 1 else out[0]
+ self.calls += 1
+ self.views += q.shape[0] * len(self.cameras)
+ self.seconds += time.time() - t0
+ return rgb
+
+
+def _gray(x):
+ return (0.299 * x[:, 0] + 0.587 * x[:, 1] + 0.114 * x[:, 2])[:, None]
+
+
+def augment(x, d: DRConfig, gen=None):
+ """Per-image colour randomisation of float images x [N, 3, H, W] in 0-1 (module docstring) -> same shape."""
+ N, dev = x.shape[0], x.device
+
+ def u(lo, hi):
+ return lo + (hi - lo) * torch.rand(N, 1, 1, 1, device=dev, generator=gen)
+
+ def on(p):
+ return (torch.rand(N, 1, 1, 1, device=dev, generator=gen) < p).float()
+
+ m = on(d.p_bright)
+ x = x * (1 + m * (u(*d.bright) - 1))
+ m = on(d.p_contrast)
+ mu = _gray(x).mean((2, 3), keepdim=True)
+ x = mu + (x - mu) * (1 + m * (u(*d.contrast) - 1))
+ m = on(d.p_sat)
+ g = _gray(x)
+ x = g + (x - g) * (1 + m * (u(*d.sat) - 1))
+ m = on(d.p_hue)
+ th = m * u(-d.hue, d.hue) * 2 * math.pi # hue turn in YIQ space
+ yiq = torch.tensor([[0.299, 0.587, 0.114], [0.596, -0.274, -0.322], [0.211, -0.523, 0.312]], device=dev)
+ inv = torch.linalg.inv(yiq)
+ y = torch.einsum("ij,njhw->nihw", yiq, x)
+ c, s = torch.cos(th), torch.sin(th)
+ i2 = c * y[:, 1:2] - s * y[:, 2:3]
+ q2 = s * y[:, 1:2] + c * y[:, 2:3]
+ x = torch.einsum("ij,njhw->nihw", inv, torch.cat((y[:, :1], i2, q2), 1))
+ m = on(d.p_noise)
+ x = x + m * u(*d.noise) * torch.randn(x.shape, device=dev, generator=gen)
+ m = on(d.p_blur)
+ if bool(m.any()):
+ sig = u(*d.blur)[:, 0, 0, 0]
+ k = torch.arange(-2, 3, device=dev, dtype=x.dtype)
+ w = torch.exp(-(k[None] ** 2) / (2 * sig[:, None] ** 2))
+ w = w / w.sum(-1, keepdim=True) # [N, 5]
+ xb = x.reshape(1, N * 3, *x.shape[2:])
+ wk = w.repeat_interleave(3, 0)
+ xb = F.conv2d(F.pad(xb, (2, 2, 0, 0), mode="replicate"), wk[:, None, None, :], groups=N * 3)
+ xb = F.conv2d(F.pad(xb, (0, 0, 2, 2), mode="replicate"), wk[:, None, :, None], groups=N * 3)
+ x = torch.where(m.bool(), xb.reshape_as(x), x)
+ return x.clamp(0, 1)
+
+
+def to_input(rgb, d: DRConfig | None = None, gen=None, fx: ViewFX | None = None, fx_random=None):
+ """uint8 [n, C, H, W, 3] -> float [n, C, 3, H, W], ImageNet-normalised; ``d``: per-image augmentation (training).
+ ``fx`` (real scene, ``DRViews.fx``): the cameras' image-space model; its random effects when ``fx_random``
+ (default: when ``d`` augments), its fixed / nominal effects always. Real camera frames: no ``fx``."""
+ x = rgb.permute(0, 1, 4, 2, 3).float().div_(255.0)
+ n, C = x.shape[:2]
+ aug = d is not None and d.on
+ if fx is not None:
+ rnd = aug if fx_random is None else bool(fx_random)
+ x = fx.apply(x, gen, rnd, (lambda y: augment(y, d, gen)) if aug else None)
+ elif aug:
+ x = augment(x.reshape(n * C, *x.shape[2:]), d, gen).reshape(x.shape)
+ m = torch.tensor(V.IMAGENET_MEAN, device=x.device).view(1, 1, 3, 1, 1)
+ s = torch.tensor(V.IMAGENET_STD, device=x.device).view(1, 1, 3, 1, 1)
+ return (x - m) / s
+
+
+# ---- the student network -----------------------------------------------------------------------------------------------
+@dataclass
+class ViralConfig:
+ chunk: int = 10
+ n_exec: int = 5
+ res: int = 224
+ cameras: tuple = CAMERAS
+ qd_noise: float = 1.0 # training: Gaussian noise (std units) on the normalised qdot input
+ qd_input_zero: bool = False # real2sim: the qdot input is always 0 (every path: training, acting, the robot),
+ # so the student's step size cannot follow the measured arm speed
+ hist: int = 0 # robot input history: [q, qdot] of the previous ``hist`` decisions (online path)
+ lastcmd: bool = False # real2sim: + the student's last executed command (module docstring, 12 inputs
+ # after the history and the cmd input; online loop, evaluation and robot; not
+ # the round files; independent of ``cmd_in``)
+ # studentlab (2026-10-22; off by default, online path only): the student's own last command and its last images
+ cmd_in: bool = False # + the previous decision's 5 EXECUTED targets (after the action layer) - the
+ # measured q now, [5, 6] / cmd_scale (0 at an episode start; teacher-driven
+ # worlds: the teacher's executed targets)
+ cmd_scale: tuple = CMD_SCALE # rad per joint: the lead band (arm) and 0.1 rad (jaw)
+ img_hist: bool = False # + the previous decision's images of both cameras through the same encoders
+ # (the current images at an episode start)
+ encoder: str = "resnet18"
+ stages: int = 3
+ keypoints: int = 32
+ pool_dim: int = 64
+ hidden: tuple = (512, 512)
+ aux_weight: float = 1.0 # block x, y, sin / cos 4 yaw + cube x, y, z from the image features
+ aux_hidden: int = 256
+ jaw_lead: int = 0 # execution: jaw target taken this many steps ahead in the chunk
+ batch: int = 128
+ render_batch: int = 256
+ reuse: int = 1 # training steps per rendered image = reuse (random sub-batches of the buffer)
+ lr: float = 3e-4
+ lr_backbone: float = 1e-4
+ weight_decay: float = 1e-4
+ warmup: int = 300
+ grad_clip: float = 10.0
+ amp: bool = True
+ seed: int = 0
+ dr: dict = field(default_factory=dict) # DRConfig overrides (training images)
+ dr_frac: float = 1.0 # share of training samples with randomised visuals
+ # ---- real2sim (module docstring; defaults = build9's sim scene, no lag) ----
+ scene: str = "" # real-scene file (JSON, ``load_real_setup``); "" = the sim scene
+ calib: str = "" # calibration contract; "" = the scene file's "calib"
+ crops: dict = field(default_factory=dict) # {camera: [x, y, w, h]} real-image crop (resolved by ``pin_real``)
+ real_dr: dict = field(default_factory=dict) # RealDR overrides (+ exposure_log2) over the scene file's "dr"
+ cam_fx: dict = field(default_factory=dict) # CamFX: extra image-space effects (student side)
+ lag: int = 0 # image lag (20 ms control steps): evaluation / deployment nominal
+ lag_range: tuple = (0, 0) # training: lag drawn per world per episode, inclusive
+ scene_sha256: str = "" # pinned at the start of training (``pin_real``)
+ calib_sha256: str = ""
+
+ @staticmethod
+ def from_dict(d):
+ d = dict(d or {})
+ known = set(ViralConfig.__dataclass_fields__)
+ bad = sorted(set(d) - known - {"note", "notes"})
+ if bad:
+ raise ValueError(f"unknown viral config keys {bad}")
+ for k in ("cameras", "hidden", "lag_range", "cmd_scale"):
+ if k in d:
+ d[k] = tuple(d[k])
+ cfg = ViralConfig(**{k: v for k, v in d.items() if k in known})
+ if len(cfg.cmd_scale) != 6 or min(float(v) for v in cfg.cmd_scale) <= 0:
+ raise ValueError(f"cmd_scale {cfg.cmd_scale}: 6 positive values (rad)")
+ return cfg
+
+ @property
+ def lag_max(self):
+ return max(int(self.lag), int(self.lag_range[1]))
+
+ @property
+ def robot_dim(self):
+ """Length of the robot input vector: [q, qd] now + ``hist`` decisions before (12 each), then the cmd input
+ (``cmd_in``: n_exec x 6), then the last command (``lastcmd``: 12)."""
+ return 12 * (1 + int(self.hist)) + (int(self.n_exec) * 6 if getattr(self, "cmd_in", False) else 0) + \
+ 12 * int(bool(getattr(self, "lastcmd", False)))
+
+
+STAT_KEYS = ("robot_mean", "robot_std", "tgt_mean", "tgt_std", "aux_mean", "aux_std")
+AUX_DIM = 7
+# the last-command input (``ViralConfig.lastcmd``): fixed scales, NOT data statistics (a lastcmd checkpoint depends on
+# them: never change them; another scale = another option). Last target - q: arm 0.05 rad (the action layer's lead
+# band is 0.045-0.12 rad; real robot 10-22: |prev - q| p99 0.02 rad, the dead band 0.006-0.013 rad), jaw 0.25 rad (it
+# squeezes the cube: real p50 0.12, max 0.37 rad). Target change per 20 ms: arm 1 rad/s (real p99 0.6-0.9, max 1.9),
+# jaw 5 rad/s (real p99 3.9 rad/s). Normalised values are clamped to +-10 like the other robot inputs.
+LASTCMD_DQ_SCALE = (0.05, 0.05, 0.05, 0.05, 0.05, 0.25)
+LASTCMD_V_SCALE = (1.0, 1.0, 1.0, 1.0, 1.0, 5.0)
+
+
+def lastcmd_raw(u_last, u_prev, q, fresh=None):
+ """The last-command input before normalisation (``ViralConfig.lastcmd``; the same function for the sim and the
+ robot): u_last, u_prev [B, 6] the targets executed in the last and the second-to-last 20 ms step before the decision
+ (sim: ``JointVecEnv.u_exe[:, -1]``, ``[:, -2]``; robot: ``hw_lib.Guard.prev`` of those steps), q [B, 6] the
+ measured q at the decision (any joint frame: only differences) -> [B, 12] float64 = [u_last - q, (u_last - u_prev)
+ / 20 ms]; ``fresh`` [B] bool: rows at an episode start (no command yet) -> 0; non-finite entries -> 0."""
+ u1, u0 = u_last.to(torch.float64), u_prev.to(device=u_last.device, dtype=torch.float64)
+ out = torch.cat((u1 - q.to(u1), (u1 - u0) / JE.CONTROL_DT), -1)
+ out = torch.where(torch.isfinite(out), out, torch.zeros_like(out))
+ if fresh is not None:
+ out = torch.where(fresh.to(out.device).view(-1, 1), torch.zeros_like(out), out)
+ return out
+
+
+def lastcmd_zeros(B, device):
+ """[B, 12] float64: the last-command input at an episode start."""
+ return torch.zeros(int(B), 12, dtype=torch.float64, device=device)
+
+
+NEW_INPUT_KEYS = ("cmd_in", "cmd_scale", "img_hist") # left out of saved configs while off (``cfg_dict``)
+ARCH_KEYS = ("hist", "cmd_in", "img_hist") # change the head's input: ``expand_student``
+
+
+def cfg_dict(cfg: ViralConfig) -> dict:
+ """The config as saved in checkpoints / meta files: ``asdict`` without the studentlab input options while they are
+ off (so a student without them stays readable by code that predates them); with any of them on, all are saved.
+ The same for the last-command input (``lastcmd``): no key while it is off."""
+ d = asdict(cfg)
+ if not cfg.cmd_in and not cfg.img_hist and tuple(cfg.cmd_scale) == CMD_SCALE:
+ for k in NEW_INPUT_KEYS:
+ d.pop(k, None)
+ if not d.get("lastcmd"):
+ d.pop("lastcmd", None)
+ return d
+
+
+class ViralNet(nn.Module):
+ def __init__(self, cfg: ViralConfig, stats, pretrained=True):
+ super().__init__()
+ from nedm.so101_policy.vision.perstep import Encoder, PerStepConfig
+ self.cfg = cfg
+ pc = PerStepConfig(encoder=cfg.encoder, stages=cfg.stages, keypoints=cfg.keypoints, pool_dim=cfg.pool_dim)
+ self.enc = nn.ModuleList([Encoder(pc, pretrained) for _ in cfg.cameras])
+ fd = sum(e.out_dim for e in self.enc)
+ self.fd = fd
+ self.n_cmd = int(cfg.n_exec) * 6 if getattr(cfg, "cmd_in", False) else 0
+ if self.n_cmd:
+ self.register_buffer("cmd_s", torch.tensor(cfg.cmd_scale, dtype=torch.float32).repeat(int(cfg.n_exec)),
+ persistent=False)
+ layers, k = [], fd + 12 * (1 + int(cfg.hist)) + self.n_cmd + (fd if getattr(cfg, "img_hist", False) else 0)
+ for h in cfg.hidden:
+ layers += [nn.Linear(k, h), nn.ELU()]
+ k = h
+ layers.append(nn.Linear(k, cfg.chunk * 6))
+ self.head = nn.Sequential(*layers)
+ self.aux = nn.Sequential(nn.Linear(fd, cfg.aux_hidden), nn.ELU(), nn.Linear(cfg.aux_hidden, AUX_DIM))
+ for k_, v in stats.items():
+ self.register_buffer(k_, torch.as_tensor(v, dtype=torch.float32).clone())
+ self.lastcmd = bool(getattr(cfg, "lastcmd", False))
+ if self.lastcmd: # the last-command inputs: their own weights into the head's first layer, zero at start
+ self.lastcmd_in = nn.Linear(12, self.head[0].out_features, bias=False)
+ nn.init.zeros_(self.lastcmd_in.weight)
+ self.register_buffer("lastcmd_scale", torch.tensor(LASTCMD_DQ_SCALE + LASTCMD_V_SCALE)) # saved with the checkpoint
+
+ def features(self, images):
+ return torch.cat([e(images[:, i]) for i, e in enumerate(self.enc)], -1)
+
+ def lastcmd_norm(self, lc):
+ """[B, 12] raw last-command input (``lastcmd_raw``) -> / the fixed scales, clamped to +-10 (no noise)."""
+ return (lc.float() / self.lastcmd_scale).clamp(-10, 10)
+
+ def robot(self, robot, qd_scale=None):
+ """[B, 12 (1 + hist) (+ 30 cmd)] = [q, qd] now, then the previous decisions (newest first), then (``cmd_in``)
+ the previous decision's executed targets - q now ([5, 6] flattened) -> normalised (+ qdot noise in training on
+ every qdot block; ``qd_scale`` [B]: per-sample factor on that noise, None = 1; the cmd part: / cmd_scale)."""
+ H = 1 + int(self.cfg.hist)
+ nc = getattr(self, "n_cmd", 0)
+ if nc:
+ cmd = (robot[:, 12 * H:12 * H + nc] / self.cmd_s).clamp(-10, 10)
+ return torch.cat((ViralNet._robot(self, robot[:, :12 * H].contiguous(), H, qd_scale), cmd), -1)
+ return ViralNet._robot(self, robot, H, qd_scale)
+
+ def _robot(self, robot, H, qd_scale):
+ if getattr(self.cfg, "qd_input_zero", False):
+ robot = robot.view(-1, H, 12)
+ robot = torch.cat((robot[..., :6], torch.zeros_like(robot[..., 6:])), -1)
+ r = ((robot.view(-1, H, 12) - self.robot_mean) / self.robot_std).clamp(-10, 10)
+ if self.training and self.cfg.qd_noise > 0:
+ n = self.cfg.qd_noise * torch.randn_like(r[..., 6:])
+ if qd_scale is not None:
+ n = n * qd_scale.to(n).view(-1, 1, 1)
+ r = torch.cat((r[..., :6], r[..., 6:] + n), -1)
+ return r.reshape(-1, 12 * H)
+
+ def _split_lastcmd(self, robot):
+ """lastcmd students: robot [B, robot_dim] -> (the robot vector without the last command: [q, qd, history,
+ (cmd)], the raw last command [B, 12] = the last 12 values)."""
+ n = 12 * (1 + int(self.cfg.hist)) + int(getattr(self, "n_cmd", 0))
+ if robot.shape[-1] != n + 12:
+ raise ValueError(f"lastcmd student: robot input of {robot.shape[-1]} values, needs {n + 12}")
+ return robot[:, :n].contiguous(), robot[:, n:n + 12]
+
+ def _head(self, x, lc=None):
+ """The head on its input x [B, k] float32 -> [B, chunk, 6]; lastcmd: the first layer's output + the
+ last-command term of the raw last command ``lc`` (exactly + 0 while its weights are zero: the student it was
+ expanded from, bit for bit)."""
+ if not self.lastcmd:
+ return self.head(x).view(-1, self.cfg.chunk, 6)
+ h = self.head[0](x)
+ h = h + self.lastcmd_in(self.lastcmd_norm(lc)).to(h.dtype)
+ return self.head[1:](h).view(-1, self.cfg.chunk, 6)
+
+ def forward(self, images, robot, qd_scale=None, prev=None):
+ """``prev`` (``img_hist``): the previous decision's images [B, C, 3, H, W] (None: the current ones, as at an
+ episode start); both through the same encoders, the previous features appended to the head input.
+ ``robot`` = [q, qd, history (12 (1 + hist)), (cmd_in: n_exec x 6), (lastcmd: 12)] (``cfg.robot_dim``)."""
+ lc = None
+ if self.lastcmd:
+ robot, lc = self._split_lastcmd(robot)
+ if getattr(self.cfg, "img_hist", False):
+ B = images.shape[0]
+ if prev is None:
+ f = self.features(images)
+ fp = f
+ else:
+ both = self.features(torch.cat((images, prev.to(images)), 0))
+ f, fp = both[:B], both[B:]
+ x = torch.cat((f, self.robot(robot, qd_scale).to(f.dtype), fp), -1)
+ return self._head(x.float(), lc), f
+ f = self.features(images)
+ return self._head(torch.cat((f, self.robot(robot, qd_scale).to(f.dtype)), -1).float(), lc), f
+
+ def head_from_features(self, f, robot, fp=None):
+ """The normalised chunk [B, chunk, 6] from the encoder features ``f`` [B, fd] (``img_hist``: + ``fp``, the
+ previous decision's features; None = ``f``, as at an episode start) = ``forward`` without its encoder pass
+ (the robot caches the previous query's features: ``hw_lib.StudentPolicy``)."""
+ lc = None
+ if self.lastcmd:
+ robot, lc = self._split_lastcmd(robot)
+ parts = [f, self.robot(robot).to(f.dtype)]
+ if getattr(self.cfg, "img_hist", False):
+ parts.append(f if fp is None else fp.to(f.dtype))
+ return self._head(torch.cat(parts, -1).float(), lc)
+
+ def loss(self, images, robot, tgt_n, valid, aux_n=None, qd_scale=None, prev=None):
+ p, f = self(images, robot, qd_scale, prev)
+ e = (p.float() - tgt_n).abs() * valid[..., None]
+ l_act = e.sum() / (valid.sum() * 6).clamp_min(1)
+ info = {"l_act": float(l_act.detach())}
+ loss = l_act
+ if aux_n is not None and self.cfg.aux_weight > 0:
+ pa = self.aux(f).float()
+ l_aux = F.smooth_l1_loss(pa, aux_n, beta=0.5)
+ loss = loss + self.cfg.aux_weight * l_aux
+ info["l_aux"] = float(l_aux.detach())
+ return loss, info
+
+ @torch.no_grad()
+ def predict(self, images, robot, prev=None):
+ return self(images, robot, prev=prev)[0].float()
+
+ @torch.no_grad()
+ def predict_aux(self, images):
+ return self.aux(self.features(images)).float() * self.aux_std + self.aux_mean
+
+ def backbone_params(self):
+ return [p for e in self.enc if e.is_backbone for p in e.trunk.parameters() if p.requires_grad]
+
+
+def head_layout(cfg: ViralConfig, fd: int) -> dict:
+ """Column ranges of the head's first layer: features now, robot [q, qd] (now + history), cmd, previous features."""
+ out, k = {}, 0
+ for name, n in (("feat", fd), ("robot", 12 * (1 + int(cfg.hist))),
+ ("cmd", int(cfg.n_exec) * 6 if cfg.cmd_in else 0), ("feat_prev", fd if cfg.img_hist else 0)):
+ out[name] = (k, k + n)
+ k += n
+ return out
+
+
+def expand_student(st: ViralNet, hist=None, cmd_in=None, img_hist=None, device="cuda", cmd_scale=None):
+ """A student with more inputs (robot history ``hist``, the command input ``cmd_in``, the image history
+ ``img_hist``; None = keep) from the given one: the same weights, ZERO weights on the new inputs' columns of the
+ head's first layer, so the new student gives the same chunk as the given one on the same inputs (whatever the new
+ inputs are). Inputs cannot be removed. ``cmd_scale``: the cmd input scale of a NEW cmd input (default the
+ config's)."""
+ from dataclasses import replace as _rep
+ c0 = st.cfg
+ h1 = int(c0.hist) if hist is None else int(hist)
+ m1 = bool(c0.cmd_in) if cmd_in is None else bool(cmd_in)
+ i1 = bool(c0.img_hist) if img_hist is None else bool(img_hist)
+ if h1 < int(c0.hist) or (c0.cmd_in and not m1) or (c0.img_hist and not i1):
+ raise ValueError(f"cannot remove inputs: hist {c0.hist} -> {h1}, cmd_in {c0.cmd_in} -> {m1}, "
+ f"img_hist {c0.img_hist} -> {i1}")
+ if cmd_scale is not None and c0.cmd_in and tuple(cmd_scale) != tuple(c0.cmd_scale):
+ raise ValueError("cmd_scale of an existing cmd input cannot change")
+ if (h1, m1, i1) == (int(c0.hist), bool(c0.cmd_in), bool(c0.img_hist)):
+ return st
+ kw = dict(hist=h1, cmd_in=m1, img_hist=i1)
+ if cmd_scale is not None:
+ kw["cmd_scale"] = tuple(float(v) for v in cmd_scale)
+ cfg = _rep(c0, **kw)
+ new = ViralNet(cfg, {k: getattr(st, k) for k in STAT_KEYS}, pretrained=False).to(device)
+ sd = st.state_dict()
+ nd = new.state_dict()
+ lo, ln = head_layout(c0, st.fd), head_layout(cfg, new.fd)
+ for k, v in sd.items():
+ if k == "head.0.weight":
+ w = torch.zeros_like(nd[k])
+ for seg, (a, b) in lo.items():
+ if b > a:
+ a1 = ln[seg][0]
+ w[:, a1:a1 + (b - a)] = v[:, a:b]
+ nd[k] = w
+ else:
+ nd[k] = v
+ new.load_state_dict(nd)
+ return new
+
+
+def expand_lastcmd(st: ViralNet, device="cuda"):
+ """A student with the last-command input (``ViralConfig.lastcmd``) from one without: the same weights (any
+ history), zero weights on the new inputs (``lastcmd_in``), so it acts exactly as the given student until trained.
+ A student that has it already: returned as is."""
+ from dataclasses import replace as _rep
+ if getattr(st.cfg, "lastcmd", False):
+ return st
+ new = ViralNet(_rep(st.cfg, lastcmd=True), {k: getattr(st, k) for k in STAT_KEYS}, pretrained=False).to(device)
+ miss, extra = new.load_state_dict(st.state_dict(), strict=False)
+ if sorted(miss) != ["lastcmd_in.weight", "lastcmd_scale"] or extra:
+ raise RuntimeError(f"expand_lastcmd: unexpected state keys (missing {miss}, unexpected {extra})")
+ return new.train(st.training)
+
+
+def expand_hist(st: ViralNet, hist: int, device="cuda"):
+ """A student with ``hist`` decisions of robot history from one without (or with fewer): the same weights, zero
+ weights on the new history inputs of the head's first layer (so it starts as the given student)."""
+ if hist < int(st.cfg.hist):
+ raise ValueError("cannot shrink the history")
+ return expand_student(st, hist=hist, device=device)
+
+
+def save_student(st, path, **extra):
+ # cfg_dict: no lastcmd / cmd_in / cmd_scale / img_hist keys while they are off (the old checkpoint layout: older
+ # code, e.g. a robot bundle, can load it)
+ torch.save(dict(cfg=cfg_dict(st.cfg), state_dict=st.state_dict(), stats={k: getattr(st, k).cpu() for k in STAT_KEYS},
+ **extra), path)
+
+
+def load_student(path, device="cuda"):
+ ck = torch.load(Path(path).expanduser(), map_location="cpu", weights_only=False)
+ cfg = ViralConfig.from_dict(ck["cfg"])
+ st = ViralNet(cfg, ck["stats"], pretrained=False).to(device)
+ st.load_state_dict(ck["state_dict"])
+ return st.eval(), ck
+
+
+# ---- data ----------------------------------------------------------------------------------------------------------------
+def aux_targets(goal_pose, cube_pos):
+ """[n, 3] (x, y, yaw), [n, 3] -> [n, 7]: block x, y, sin 4 yaw, cos 4 yaw, cube x, y, z."""
+ gy = goal_pose[:, 2]
+ return torch.cat((goal_pose[:, :2], torch.sin(4 * gy)[:, None], torch.cos(4 * gy)[:, None], cube_pos), -1)
+
+
+# ---- real2sim: image lag ------------------------------------------------------------------------------------------------
+LAG_REC = 4 # control steps of state history recorded per round-file row (``row_lag``)
+
+
+def _state13(q, cp, cq):
+ return torch.cat((q, cp, cq), -1)
+
+
+def lag_interp(z, lag):
+ """Round-file rows without ``row_lag``: the states 1..lag control steps before each row, interpolated linearly
+ between the row and the previous row (100 ms = ``JE.STEPS`` steps earlier) of the same episode (q, cube position;
+ quaternion nlerp); the first row of an episode: the row itself. -> [N, lag, 13] float32."""
+ q, cp, cq = (np.asarray(z[k], np.float64) for k in ("row_q", "row_cube_pos", "row_cube_quat"))
+ cur = np.concatenate((q, cp, cq), -1)
+ prev = np.roll(cur, 1, 0)
+ first = np.asarray(z["row_t"]) == 0 if "row_t" in z.files else np.isin(np.arange(len(cur)), z["ep_row_start"])
+ prev[first] = cur[first]
+ dot = (prev[:, 9:13] * cur[:, 9:13]).sum(-1, keepdims=True)
+ prev[:, 9:13] = np.where(dot < 0, -prev[:, 9:13], prev[:, 9:13])
+ out = []
+ for k in range(1, lag + 1):
+ a = min(1.0, k / JE.STEPS)
+ x = (1 - a) * cur + a * prev
+ x[:, 9:13] /= np.linalg.norm(x[:, 9:13], axis=-1, keepdims=True)
+ out.append(x)
+ return np.stack(out, 1).astype(np.float32)
+
+
+def lag_rows(r, sub, kmax=LAG_REC):
+ """``run_tasks`` record ``r`` + the states after every 20 ms step ``sub`` [B, D, STEPS, 13] (``SubstepLog``) ->
+ ``row_lag`` [N, kmax, 13] float32: the state k = 1..kmax control steps before each row (k >= STEPS reaches into
+ the decisions before; before the episode start: its own start state, the arm at rest)."""
+ if kmax < 1:
+ raise ValueError(f"kmax {kmax}: >= 1 control steps")
+ S = JE.STEPS
+ rb, rt = np.asarray(r["row_ep"], np.int64), np.asarray(r["row_t"], np.int64)
+ cur = np.concatenate((r["row_q"], r["row_cube_pos"], r["row_cube_quat"]), -1).astype(np.float32)
+ out = np.repeat(cur[:, None], kmax, 1)
+ p = rt >= 1
+ if p.any():
+ prev = sub[rb[p], rt[p] - 1] # [n, STEPS, 13]: the previous decision's steps
+ err = float(np.abs(prev[:, S - 1] - cur[p]).max())
+ if err > 1e-4:
+ raise RuntimeError(f"substep log does not match the recorded rows (max {err:.2e})")
+ first = np.zeros(int(rb.max()) + 1, np.int64) # the start row of every episode
+ first[rb[rt == 0]] = np.nonzero(rt == 0)[0]
+ for k in range(1, kmax + 1):
+ i = rt[p] * S - k # global step index of the state (0 = start)
+ st = i <= 0
+ v = sub[rb[p], np.maximum(i - 1, 0) // S, np.maximum(i - 1, 0) % S]
+ out[p, k - 1] = np.where(st[:, None], cur[first[rb[p]]], v)
+ return out
+
+
+class SubstepLog:
+ """The world state after every 20 ms step of every ``JointVecEnv.step`` (feed it with ``step_tap``):
+ ``array()`` -> [B, decisions, STEPS, 13] float32 (q, cube pos, cube quat w x y z)."""
+
+ def __init__(self):
+ self.rows = []
+
+ def __call__(self, ws):
+ self.rows.append(_state13(ws.q, ws.cube_pos, ws.cube_quat).float().cpu())
+
+ def array(self):
+ S = JE.STEPS
+ if len(self.rows) % S:
+ raise RuntimeError(f"{len(self.rows)} logged steps: not whole decisions")
+ a = torch.stack(self.rows, 1).numpy() # [B, D * S, 13]
+ return a.reshape(a.shape[0], -1, S, 13)
+
+
+@contextlib.contextmanager
+def step_tap(env, *fns):
+ """Call each ``fn(ws)`` after every 20 ms world step of ``env.step`` (any caller, e.g. ``run_tasks``); restores
+ ``env.step`` on exit."""
+ had = "step" in vars(env)
+ orig = env.step
+
+ def step(actions=None, targets=None, use_targets=None, step_hook=None):
+ def hook(e, j):
+ for f in fns:
+ f(e.ws)
+ if step_hook is not None:
+ step_hook(e, j)
+ return orig(actions, targets=targets, use_targets=use_targets, step_hook=hook)
+
+ env.step = step
+ try:
+ yield env
+ finally:
+ if had:
+ env.step = orig
+ else:
+ del env.step
+
+
+def _sane(q, cp, cq, dev):
+ """Non-finite rows -> a harmless pose (as ``Actor``)."""
+ q, cp, cq = q.to(dev, torch.float32), cp.to(dev, torch.float32), cq.to(dev, torch.float32)
+ ok = torch.isfinite(q).all(-1) & torch.isfinite(cp).all(-1) & torch.isfinite(cq).all(-1)
+ q = torch.where(ok[:, None], q, torch.zeros_like(q))
+ cp = torch.where(ok[:, None], cp, torch.tensor([0.2, 0.0, 0.015], device=dev))
+ cq = torch.where(ok[:, None], cq, torch.tensor([1.0, 0.0, 0.0, 0.0], device=dev))
+ return q, cp, cq
+
+
+class LagHistory:
+ """Per world the states of the last ``kmax`` control steps (index 0 = now): ``fill`` at an episode start (the arm
+ at rest: every entry = the start state), ``push`` after every 20 ms step, ``get(k)`` [B] -> (q, cube pos, quat).
+
+ ``goal`` (``ImgLagConfig``, real2sim v8): also the goal pose [x, y, yaw] of every entry (``fill`` / ``push`` then
+ need it), and ``at(lag, goal_now)``: the state a real-valued ``lag`` back (interpolated) with the goal of then."""
+
+ def __init__(self, B, kmax, device, goal=False):
+ self.x = torch.zeros(B, int(kmax) + 1, 13, device=device)
+ self.g = torch.zeros(B, int(kmax) + 1, 3, device=device) if goal else None
+ self.ready = False
+
+ def fill(self, idx, q, cp, cq, goal=None):
+ self.x[idx] = _state13(q, cp, cq).to(self.x)[:, None].expand(-1, self.x.shape[1], -1)
+ if self.g is not None:
+ if goal is None:
+ raise ValueError("LagHistory(goal=True).fill: the goal pose is required")
+ self.g[idx] = goal.to(self.g)[:, None].expand(-1, self.g.shape[1], -1)
+ self.ready = True
+
+ def push(self, q, cp, cq, goal=None):
+ self.x = torch.cat((_state13(q, cp, cq).to(self.x)[:, None], self.x[:, :-1]), 1)
+ if self.g is not None:
+ if goal is None:
+ raise ValueError("LagHistory(goal=True).push: the goal pose is required")
+ self.g = torch.cat((goal.to(self.g)[:, None], self.g[:, :-1]), 1)
+
+ def newest(self):
+ return self.x[:, 0]
+
+ def get(self, k):
+ x = self.x[torch.arange(len(self.x), device=self.x.device), k.to(self.x.device).long()]
+ return x[:, :6], x[:, 6:9], x[:, 9:13]
+
+ def at(self, lag, goal_now):
+ """``lag`` [B] float control steps (0 <= lag <= kmax; above kmax - 1 only whole steps): the state ``lag``
+ steps before now, linear between the two neighbouring 20 ms states (q, cube position; cube quaternion nlerp
+ on the same hemisphere); a whole step = that entry exactly. The goal (``goal=True``): ``goal_now`` [B, 3] at
+ lag 0, else the goal of entry floor(lag) (the goal moves only at a decision boundary, after that decision's
+ last push: an image from before the boundary shows the old goal). -> (q, cube pos, cube quat, goal) float32."""
+ if self.g is None:
+ raise ValueError("LagHistory.at needs goal=True")
+ B, dev = len(self.x), self.x.device
+ lag = lag.to(dev, torch.float32).clamp(0.0, float(self.x.shape[1] - 1))
+ k0 = lag.floor().long()
+ a = lag - k0.to(lag)
+ k1 = (k0 + 1).clamp_max(self.x.shape[1] - 1)
+ ar = torch.arange(B, device=dev)
+ s0, s1 = self.x[ar, k0], self.x[ar, k1]
+ w = a[:, None]
+ q = torch.lerp(s0[:, :6], s1[:, :6], w)
+ cp = torch.lerp(s0[:, 6:9], s1[:, 6:9], w)
+ q1 = torch.where(((s0[:, 9:13] * s1[:, 9:13]).sum(-1, keepdim=True) < 0), -s1[:, 9:13], s1[:, 9:13])
+ cq = torch.lerp(s0[:, 9:13], q1, w)
+ cq = cq / cq.norm(dim=-1, keepdim=True).clamp_min(1e-12)
+ whole = (a == 0)[:, None]
+ q, cp, cq = (torch.where(whole, s0[:, sl], v) for sl, v in ((slice(0, 6), q), (slice(6, 9), cp),
+ (slice(9, 13), cq)))
+ g = torch.where((lag == 0)[:, None], goal_now.to(self.g), self.g[ar, k0])
+ return q, cp, cq, g
+
+
+@dataclass
+class ImgLagConfig:
+ """Image latency of the online loop (``OnlineConfig.img_lag``; real2sim v8, 2026-10-23; measurement and method:
+ ~/so101_r2s_claude/v8/latency/: scripts/lag_fit.py, lag_dist.py -> lag_fit.json, lag_boot.json, lag_dist.json).
+ On the robot the images of a query are older than its joint reading by the camera pipeline latency before
+ LeRobot's frame time stamp (26.5 ms, 95 % CI 25-28, fitted on 47,691 consecutive query pairs of 173 robot
+ episodes: thumbnail change vs joint motion between the capture times) + the frame age (uniform 0-33 ms, 30 fps):
+ 28-62 ms (p1-p99), mean 44 ms = 2.2 control steps; the two cameras' ages are uncorrelated (r -0.13) and change
+ from query to query (lag-1 autocorrelation 0.15). The calibration's 42-48 ms (teleop recordings,
+ ``time_offset_frames``) is the same latency + the mean age of the recording loop.
+
+ Per world (per camera with ``per_camera``) a lag U(lo_ms, hi_ms) is drawn at every episode start and drawn again at
+ each decision with probability ``redraw_p`` (0 = once per episode; the redraw decision is per world, all its
+ cameras together); the student's images show the world ``lag /
+ 20 ms`` control steps before the decision (``LagHistory.at``: interpolated between the 20 ms states, the goal as it
+ was then), ``quantize``: whole steps only (the lag rounded). q, qdot and the labels stay current; the aux targets
+ follow the image state (first camera). ``per_camera``: one render call per camera (the later calls keep the first
+ call's light and intrinsics: ``DRViews.render(keep=True)``), so the render time grows with the cameras. A goal
+ jump (``OnlineConfig.goal_jump``) that the lagged images do not show yet: no buffer sample that decision (its label
+ is for the new goal). Replaces the student's integer lag (``ViralConfig.lag`` / ``lag_range``) in the online loop;
+ the evaluation keeps ``ViralConfig.lag``."""
+ lo_ms: float = 0.0
+ hi_ms: float = 0.0
+ redraw_p: float = 1.0
+ per_camera: bool = False
+ quantize: bool = False
+
+ MAX_MS = 400.0
+
+ @staticmethod
+ def is_on(d) -> bool:
+ """An ``OnlineConfig.img_lag`` dict turns the option on when it has any key besides "note"."""
+ return bool(set(dict(d or {})) - {"note"})
+
+ @staticmethod
+ def from_dict(d):
+ d = dict(d or {})
+ known = set(ImgLagConfig.__dataclass_fields__)
+ bad = sorted(set(d) - known - {"note"})
+ if bad:
+ raise ValueError(f"unknown img_lag keys {bad}")
+ miss = [k for k in ("lo_ms", "hi_ms") if k not in d]
+ if ImgLagConfig.is_on(d) and miss: # (defaults 0 / 0 would silently give no lag and drop lag_range)
+ raise ValueError(f"img_lag: give lo_ms and hi_ms explicitly (missing {miss})")
+ c = ImgLagConfig(**{k: v for k, v in d.items() if k in known})
+ c.lo_ms, c.hi_ms, c.redraw_p = float(c.lo_ms), float(c.hi_ms), float(c.redraw_p)
+ c.per_camera, c.quantize = bool(c.per_camera), bool(c.quantize)
+ if not 0.0 <= c.lo_ms <= c.hi_ms <= ImgLagConfig.MAX_MS:
+ raise ValueError(f"img_lag lo_ms {c.lo_ms}, hi_ms {c.hi_ms}: 0 <= lo <= hi <= {ImgLagConfig.MAX_MS} ms")
+ if not 0.0 <= c.redraw_p <= 1.0:
+ raise ValueError(f"img_lag redraw_p {c.redraw_p}: a probability in [0, 1]")
+ return c
+
+ @property
+ def step_ms(self):
+ return 1000.0 * JE.CONTROL_DT
+
+ @property
+ def kmax(self):
+ """Steps of history needed: floor(hi / 20 ms) + 1 (the interpolation's older neighbour); the ring buffer has
+ kmax + 1 entries (index 0 = now)."""
+ return int(math.floor(self.hi_ms / self.step_ms + 1e-9)) + 1
+
+ def draw(self, n, cams, gen, device):
+ """[n, cams] float32 lags in control steps."""
+ u = torch.rand(n, cams, device=device, generator=gen)
+ x = (self.lo_ms + (self.hi_ms - self.lo_ms) * u) / self.step_ms
+ return torch.round(x) if self.quantize else x
+
+
+# ---- real2sim: robot-like qdot ---------------------------------------------------------------------------------------
+QD_TICK = 2 * math.pi / 4096 # STS3215 position step (rad): the robot's q is quantised to it
+
+
+def qd_weights(window, dt=JE.CONTROL_DT):
+ """[window] float64 least-squares slope weights over states i = 0 (now) .. window - 1 steps back (``dt`` apart):
+ slope = sum_i w_i (x_i - x_0) (sum w_i = 0, so the reference x_0 changes nothing but keeps a still arm at exactly
+ 0)."""
+ if int(window) < 2:
+ raise ValueError(f"qd window {window}: >= 2 states")
+ t = -torch.arange(int(window), dtype=torch.float64) * dt
+ tc = t - t.mean()
+ return tc / (tc ** 2).sum()
+
+
+def qd_ticks(q):
+ """q (rad) -> the robot's position in encoder steps (float64 integers; non-finite -> 0)."""
+ return torch.round(torch.nan_to_num(q.to(torch.float64), 0.0, 0.0, 0.0) / QD_TICK)
+
+
+def robot_qd(ticks, w):
+ """The robot's qdot (``hw_lib.QdotEstimator``): ticks [B, W, 6] (index 0 = now, ``qd_ticks``), weights [W]
+ (``qd_weights``) -> [B, 6] float64 rad/s, steps of QD_TICK x the weights, exactly 0 when the ticks do not change."""
+ return ((ticks - ticks[:, :1]) * w.to(ticks)[None, :, None]).sum(1) * QD_TICK
+
+
+class StudentSet:
+ """``joint_teacher.run_tasks`` record files (``row_*``, ``ep_row_start``, ``length``, goals) on one device. A sample
+ = one decision boundary: render inputs, robot [q, qd], chunk target [K, 6] = (lab[r] ++ lab[r + 1] ...) - q[r] with
+ validity (inside the episode), aux targets. Validation: ``val_frac`` of the FIRST file's episodes (seeded)."""
+
+ def __init__(self, paths, device="cuda", chunk=10, val_frac=0.03, seed=0, max_files=None, lag=0):
+ """``lag`` > 0: also the states 1..lag control steps before each row (image lag): the file's ``row_lag``
+ (recorded, ``lag_rows``), else linear interpolation between the row and the previous row of its episode
+ (q, cube position; quaternion nlerp; the first row of an episode: the row itself) (``lag_exact`` per file)."""
+ if isinstance(paths, (str, Path)):
+ paths = [paths]
+ paths = list(paths)[-max_files:] if max_files else list(paths)
+ keys = ("row_q", "row_qd", "row_cube_pos", "row_cube_quat", "row_lab", "row_ep", "length", "ep_row_start",
+ "goal_xy", "goal_yaw", "src", "lenient", "success")
+ parts, e0, r0 = {k: [] for k in keys}, 0, 0
+ is_val = []
+ lag = int(lag)
+ lag_parts, self.lag_exact = [], []
+ for fi, p in enumerate(paths):
+ z = np.load(Path(p).expanduser())
+ if "goal_jumps" in z.files and np.asarray(z["goal_jumps"]).any():
+ raise ValueError(f"{p}: episodes with goal jumps (StudentSet reads one goal per episode)")
+ E = len(z["length"])
+ if lag > 0:
+ if "row_lag" in z.files and z["row_lag"].shape[1] >= lag:
+ lag_parts.append(z["row_lag"][:, :lag].astype(np.float32))
+ self.lag_exact.append(True)
+ else:
+ lag_parts.append(lag_interp(z, lag))
+ self.lag_exact.append(False)
+ for k in keys:
+ v = z[k]
+ if k == "row_ep":
+ v = v.astype(np.int64) + e0
+ if k == "ep_row_start":
+ v = v.astype(np.int64) + r0
+ parts[k].append(v)
+ iv = np.zeros(E, bool)
+ if fi == 0 and val_frac > 0:
+ rng = np.random.default_rng(seed)
+ iv[rng.permutation(E)[: int(round(val_frac * E))]] = True
+ is_val.append(iv)
+ e0 += E
+ r0 += len(z["row_ep"])
+ d = {k: np.concatenate(v) for k, v in parts.items()}
+ self.dev, self.chunk = torch.device(device), int(chunk)
+ t = lambda x, dt=torch.float32: torch.as_tensor(np.ascontiguousarray(x), dtype=dt, device=self.dev) # noqa
+ self.q, self.qd = t(d["row_q"]), t(d["row_qd"])
+ self.cube_pos, self.cube_quat = t(d["row_cube_pos"]), t(d["row_cube_quat"])
+ self.lab = t(d["row_lab"]) # [N, 5, 6] absolute
+ self.ep = t(d["row_ep"], torch.long)
+ self.ep_len = t(d["length"], torch.long)
+ self.ep_start = t(d["ep_row_start"], torch.long)
+ self.goal_pose = torch.cat((t(d["goal_xy"]), t(d["goal_yaw"])[:, None]), -1)
+ self.src = t(d["src"], torch.long)
+ self.robot = torch.cat((self.q, self.qd), -1)
+ iv = t(np.concatenate(is_val), torch.bool)[self.ep]
+ self.train_rows = torch.nonzero(~iv).flatten()
+ self.val_rows = torch.nonzero(iv).flatten()
+ self.n_eps = len(self.ep_len)
+ self.n_rows = len(self.q)
+ self.paths = [str(p) for p in paths]
+ self.lag_x = t(np.concatenate(lag_parts)) if lag > 0 else None # [N, lag, 13] q, cube pos, quat
+
+ def targets(self, rows):
+ K, S = self.chunk, JE.STEPS
+ nb = (K + S - 1) // S
+ e = self.ep[rows]
+ last = self.ep_start[e] + self.ep_len[e] - 1
+ tg, ok = [], []
+ for b in range(nb):
+ r = rows + b
+ inside = r <= last
+ lab = self.lab[torch.minimum(r, last)]
+ tg.append(lab)
+ ok.append(inside[:, None].expand(-1, S))
+ tgt = torch.cat(tg, 1)[:, :K] - self.q[rows][:, None, :]
+ return tgt, torch.cat(ok, 1)[:, :K]
+
+ def batch(self, rows, lag=None):
+ """``lag`` [n] long (0 = now): the render inputs ``img_q``, ``img_cube_pos``, ``img_cube_quat`` and the aux
+ targets come from the state that many control steps before the row; q / qd / targets stay current."""
+ tgt, valid = self.targets(rows)
+ gp = self.goal_pose[self.ep[rows]]
+ q, cp, cq = self.q[rows], self.cube_pos[rows], self.cube_quat[rows]
+ if lag is not None:
+ if self.lag_x is None or int(lag.max()) > self.lag_x.shape[1]:
+ raise ValueError("StudentSet built without (enough) lag states")
+ k = lag.to(self.dev).long()
+ x = self.lag_x[rows, (k - 1).clamp_min(0)]
+ has = (k > 0)[:, None]
+ q, cp, cq = torch.where(has, x[:, :6], q), torch.where(has, x[:, 6:9], cp), torch.where(has, x[:, 9:13], cq)
+ return dict(q=self.q[rows], cube_pos=self.cube_pos[rows], cube_quat=self.cube_quat[rows], goal_pose=gp,
+ robot=self.robot[rows], target=tgt, valid=valid, aux=aux_targets(gp, cp), img_q=q,
+ img_cube_pos=cp, img_cube_quat=cq)
+
+ def stats(self, floor=1e-3, robot_floor=1e-2, n=200_000, seed=0):
+ g = torch.Generator(device=self.dev).manual_seed(seed)
+ rows = self.train_rows[torch.randint(len(self.train_rows), (min(n, len(self.train_rows)),), device=self.dev,
+ generator=g)]
+ b = self.batch(rows)
+ v = b["valid"][..., None].float()
+ cnt = v.sum(0).clamp_min(1)
+ mu = (b["target"] * v).sum(0) / cnt
+ sd = (((b["target"] - mu) ** 2 * v).sum(0) / cnt).sqrt().clamp_min(floor)
+ x = b["robot"]
+ return dict(robot_mean=x.mean(0).cpu(), robot_std=x.std(0).clamp_min(robot_floor).cpu(), tgt_mean=mu.cpu(),
+ tgt_std=sd.cpu(), aux_mean=b["aux"].mean(0).cpu(), aux_std=b["aux"].std(0).clamp_min(1e-3).cpu())
+
+ def sample(self, n, gen=None, split="train"):
+ rows = self.train_rows if split == "train" else self.val_rows
+ return rows[torch.randint(len(rows), (int(n),), device=self.dev, generator=gen)]
+
+
+# ---- training -----------------------------------------------------------------------------------------------------------
+def normalise(st, tgt):
+ return (tgt - st.tgt_mean) / st.tgt_std
+
+
+def denormalise(st, p):
+ return p * st.tgt_std + st.tgt_mean
+
+
+@torch.no_grad()
+def val_metrics(st, data: StudentSet, views: DRViews, rows, bs=256):
+ e1, c1, ea, ca = 0.0, 0.0, 0.0, 0.0
+ eb, cb = torch.zeros(2, device=data.dev), 0
+ lag = int(st.cfg.lag) if data.lag_x is not None else 0
+ for s in range(0, len(rows), bs):
+ r_ = rows[s:s + bs]
+ b = data.batch(r_, lag=torch.full((len(r_),), lag, device=data.dev) if lag > 0 else None)
+ img = to_input(views.render(b["img_q"], b["img_cube_pos"], b["img_cube_quat"], b["goal_pose"]), fx=views.fx)
+ with torch.autocast(data.dev.type, dtype=torch.bfloat16, enabled=st.cfg.amp):
+ p = denormalise(st, st.predict(img, b["robot"]))
+ pa = st.predict_aux(img)
+ err = (p - b["target"]).abs() * b["valid"][..., None]
+ e1 += float(err[:, :st.cfg.n_exec].sum())
+ c1 += float(b["valid"][:, :st.cfg.n_exec].sum()) * 6
+ ea += float(err.sum())
+ ca += float(b["valid"].sum()) * 6
+ eb += (pa[:, :2] - b["aux"][:, :2]).norm(dim=-1).sum() * torch.tensor([1.0, 0.0], device=data.dev) + \
+ (pa[:, 4:7] - b["aux"][:, 4:7]).norm(dim=-1).sum() * torch.tensor([0.0, 1.0], device=data.dev)
+ cb += len(b["q"])
+ return dict(val_mae_exec_mrad=1e3 * e1 / max(c1, 1), val_mae_chunk_mrad=1e3 * ea / max(ca, 1),
+ val_block_xy_mm=float(eb[0]) / max(cb, 1) * 1e3, val_cube_mm=float(eb[1]) / max(cb, 1) * 1e3)
+
+
+def train(data: StudentSet, views: DRViews, cfg: ViralConfig, out_dir, max_steps=6000, init_from=None,
+ log=log_default, val_n=1024, val_every=1000, log_every=200, device="cuda", extra_meta=None):
+ """Train (or fine-tune ``init_from``: weights and normalisation) -> student (eval mode); writes out_dir/{meta.json,
+ learning_curve.csv, last.pt}."""
+ if getattr(cfg, "lastcmd", False):
+ raise NotImplementedError("ViralConfig.lastcmd: the online loop only (round files have no executed targets)")
+ if cfg.cmd_in or cfg.img_hist:
+ raise ValueError("cmd_in / img_hist: the online loop only (round files have no executed targets or image links)")
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ cuda = torch.device(device).type == "cuda"
+ sync = torch.cuda.synchronize if cuda else (lambda: None)
+ torch.manual_seed(cfg.seed)
+ gen = torch.Generator(device=device).manual_seed(cfg.seed)
+ if init_from:
+ st, _ = load_student(init_from, device)
+ st.cfg = cfg
+ else:
+ st = ViralNet(cfg, data.stats(), pretrained=True).to(device)
+ st.train()
+ drc = DRConfig.from_dict(cfg.dr)
+ views.dr = drc
+ bb = st.backbone_params()
+ bb_ids = {id(p) for p in bb}
+ rest = [p for p in st.parameters() if p.requires_grad and id(p) not in bb_ids]
+ opt = torch.optim.AdamW([dict(params=rest, lr=cfg.lr), dict(params=bb, lr=cfg.lr_backbone)],
+ weight_decay=cfg.weight_decay)
+ base = [g["lr"] for g in opt.param_groups]
+ vgen = torch.Generator(device=device).manual_seed(cfg.seed + 1)
+ vrows = data.sample(min(val_n, len(data.val_rows)), vgen, "val") if len(data.val_rows) else None
+ meta = dict(cfg=cfg_dict(cfg), files=data.paths, n_eps=data.n_eps, rows=data.n_rows, train_rows=len(data.train_rows),
+ init_from=str(init_from or ""), **(extra_meta or {}))
+ (out / "meta.json").write_text(json.dumps(meta, indent=1, default=str))
+ f = open(out / "learning_curve.csv", "w", newline="")
+ wr = None
+ t0 = time.time()
+ t_render = t_train = 0.0
+ buf, pos = None, 0
+ agg = {}
+ per_buf = max(1, int(cfg.reuse) * cfg.render_batch // cfg.batch)
+ lo, hi = (int(v) for v in cfg.lag_range)
+ if hi > 0 and data.lag_x is None:
+ raise ValueError("cfg.lag_range needs a StudentSet with lag states (StudentSet(..., lag=cfg.lag_max))")
+ for step in range(1, max_steps + 1):
+ if buf is None or pos >= per_buf:
+ tr = time.time()
+ rows_ = data.sample(cfg.render_batch, gen)
+ lag = torch.randint(lo, hi + 1, (len(rows_),), device=data.dev, generator=gen) if hi > 0 else None
+ b = data.batch(rows_, lag=lag)
+ n = len(b["q"])
+ ndr = int(round(cfg.dr_frac * n)) if drc.on else 0
+ iq, icp, icq = b["img_q"], b["img_cube_pos"], b["img_cube_quat"]
+ if ndr >= n:
+ b["rgb"] = views.render(iq, icp, icq, b["goal_pose"], dr=views.draw(n))
+ elif ndr == 0:
+ b["rgb"] = views.render(iq, icp, icq, b["goal_pose"])
+ else:
+ r1 = views.render(iq[:ndr], icp[:ndr], icq[:ndr], b["goal_pose"][:ndr], dr=views.draw(ndr))
+ r2 = views.render(iq[ndr:], icp[ndr:], icq[ndr:], b["goal_pose"][ndr:])
+ b["rgb"] = torch.cat((r1, r2))
+ b["aug"] = torch.arange(n, device=data.dev) < ndr
+ b["tgt_n"] = normalise(st, b["target"])
+ b["aux_n"] = (b["aux"] - st.aux_mean) / st.aux_std
+ sync()
+ t_render += time.time() - tr
+ buf, pos = b, 0
+ tt = time.time()
+ if cfg.reuse <= 1:
+ sl = slice(pos * cfg.batch, (pos + 1) * cfg.batch)
+ else:
+ sl = torch.randperm(cfg.render_batch, device=data.dev, generator=gen)[:cfg.batch]
+ pos += 1
+ rgb = buf["rgb"][sl]
+ aug = buf["aug"][sl]
+ img = to_input(rgb, drc if bool(aug.any()) else None, gen, fx=views.fx)
+ if bool(aug.any()) and not bool(aug.all()):
+ img = torch.where(aug[:, None, None, None, None], img, to_input(rgb, fx=views.fx, fx_random=False))
+ frac = min(1.0, step / max(1, cfg.warmup))
+ if step > cfg.warmup:
+ u = (step - cfg.warmup) / max(1, max_steps - cfg.warmup)
+ frac = 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * u))
+ for g_, lr0 in zip(opt.param_groups, base):
+ g_["lr"] = lr0 * frac
+ with torch.autocast(torch.device(device).type, dtype=torch.bfloat16, enabled=cfg.amp):
+ loss, info = st.loss(img, buf["robot"][sl], buf["tgt_n"][sl], buf["valid"][sl], buf["aux_n"][sl])
+ opt.zero_grad(set_to_none=True)
+ loss.backward()
+ gn = torch.nn.utils.clip_grad_norm_(st.parameters(), cfg.grad_clip)
+ opt.step()
+ sync()
+ t_train += time.time() - tt
+ for k, v in dict(loss=float(loss.detach()), **info).items():
+ agg[k] = agg.get(k, 0.0) + v
+ agg["n"] = agg.get("n", 0) + 1
+ do_val = vrows is not None and (step % val_every == 0 or step == max_steps)
+ if step % log_every == 0 or do_val:
+ n_ = agg.pop("n")
+ row = dict(step=step, wall_min=round((time.time() - t0) / 60, 3), **{k: v / n_ for k, v in agg.items()},
+ grad_norm=float(gn), lr=opt.param_groups[0]["lr"], render_s=round(t_render, 1),
+ train_s=round(t_train, 1), gpu_gb=round(torch.cuda.max_memory_allocated() / 1e9, 2) if cuda else 0)
+ agg = {}
+ if do_val:
+ st.eval()
+ row.update(val_metrics(st, data, views, vrows))
+ st.train()
+ if wr is None:
+ keys = list(row) + [k for k in ("val_mae_exec_mrad", "val_mae_chunk_mrad", "val_block_xy_mm",
+ "val_cube_mm") if k not in row]
+ wr = csv.DictWriter(f, fieldnames=keys, extrasaction="ignore")
+ wr.writeheader()
+ wr.writerow(row)
+ f.flush()
+ log(json.dumps({k: (round(v, 4) if isinstance(v, float) else v) for k, v in row.items()}))
+ st.eval()
+ save_student(st, out / "last.pt", step=max_steps, wall_min=(time.time() - t0) / 60)
+ f.close()
+ (out / "train_summary.json").write_text(json.dumps(dict(steps=max_steps, wall_min=(time.time() - t0) / 60,
+ render_s=t_render, train_s=t_train,
+ views_per_s=views.views / max(views.seconds, 1e-9))))
+ return st
+
+
+# ---- the student as a driver ---------------------------------------------------------------------------------------------
+# evaluation only (real2sim debugging, 2026-10-22): the evaluation Actor's qdot input times this gain (env
+# NEDM_SO101_EVAL_QD_GAIN; 1 = off): tests whether a slow arm's small measured qdot makes the student command smaller
+# steps (speed follows the measured speed). Not used in training or on the robot.
+EVAL_QD_GAIN = float(os.environ.get("NEDM_SO101_EVAL_QD_GAIN", "1"))
+
+class Actor:
+ """``run_tasks`` student callback: renders the worlds (``dr``: per-world draws fixed for the episode, or None =
+ nominal visuals), feeds [q, qdot] -> absolute targets [B, 5, 6] of the executed part of the chunk (jaw target
+ ``jaw_lead`` steps ahead).
+
+ Image lag (real2sim): the images show the state ``lag`` control steps before the decision (default the student's
+ ``cfg.lag``; ``lag_range`` (lo, hi): drawn per world per episode instead); q and qdot stay current. Lag > 0 needs
+ the env's 20 ms states: run the episodes inside ``with step_tap(env, actor.push)`` (``needs_tap``).
+
+ ``qd_window`` > 0 (evaluation of the robot-like qdot, ``OnlineConfig.qd_robot_p``): the qdot input is the robot's
+ slope over the last ``qd_window`` 20 ms states of the quantised q (``robot_qd``; needs the tap as well, else the
+ second decision raises); 0 = off. ``qd_log``: that input per decision ([B, 6] float32 on the CPU; evaluation rows
+ ``row_qd_input``).
+
+ Last-command input (``student.cfg.lastcmd``): set ``env`` (``bind(env)``: the ``JointVecEnv`` that ``run_tasks``
+ steps) before the episodes; the first decision after ``reset`` gets 0, every later one ``lastcmd_raw`` of
+ ``env.u_exe`` (the targets of the decision before, after the action layer); a decision without exactly one
+ ``env.step`` since the last one raises.
+
+ Studentlab inputs: ``cfg.cmd_in`` needs the env (``bind(env)``: its ``u_exe``, the targets the action layer
+ executed in the last decision); ``cfg.img_hist`` keeps the last decision's rendered images. Both start from zero /
+ the current images at the first call after ``reset``. ``light_redraw_p`` < 1 (randomised visuals): per decision
+ the probability of a new per-call render state (random light and intrinsics, ``DRViews.render(keep=)``), else the
+ last one stays (the robot's frames share light and intrinsics); an image-history student gets the current images
+ as its previous ones when the state changed (as ``OnlineDAgger``). 1 = a new draw every decision (the old
+ behaviour)."""
+
+ def __init__(self, student: ViralNet, views: DRViews, randomise=False, jaw_lead=None, device="cuda", lag=None,
+ lag_range=None, seed=0, qd_window=0, light_redraw_p=1.0):
+ self.st, self.views, self.dev = student, views, torch.device(device)
+ self.randomise = bool(randomise)
+ self.jaw_lead = student.cfg.jaw_lead if jaw_lead is None else int(jaw_lead)
+ self.dr = None
+ self.t_render = self.t_model = 0.0
+ self.calls = 0
+ self.lag = int(student.cfg.lag if lag is None else lag)
+ self.lag_range = tuple(int(v) for v in lag_range) if lag_range is not None and lag_range[1] > 0 else None
+ self.kmax = max(self.lag, self.lag_range[1] if self.lag_range else 0)
+ self.qd_window = int(qd_window)
+ self.qd_w = qd_weights(self.qd_window).to(self.dev) if self.qd_window > 0 else None
+ self.qd_hist = None # [B, W, 6] q in encoder ticks (index 0 = now)
+ self.qd_log = [] # per decision the robot-like qdot input [B, 6] (qd_window > 0)
+ self.needs_tap = self.kmax > 0 or self.qd_window > 0
+ self.hist = None
+ self.lag_gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 4243)
+ self.q_offset = None # [6] rad: robot input q + q_offset and targets in that frame (JointVecEnv.set_table)
+ self.env = None # cmd_in / lastcmd: the env whose u_exe holds the last decision's executed targets
+ # (``bind``)
+ self.lastcmd = bool(getattr(student.cfg, "lastcmd", False))
+ self.lc_dec = None # lastcmd: env.decisions at the last decision (None: an episode start)
+ self.n_dec = 0 # decisions since ``reset``
+ self.prev_rgb = None # img_hist: the last decision's rendered images
+ self.light_redraw_p = float(light_redraw_p)
+ if not 0.0 <= self.light_redraw_p <= 1.0:
+ raise ValueError(f"light_redraw_p {light_redraw_p}: a probability in [0, 1]")
+ self.redraw_gen = torch.Generator().manual_seed(int(seed) + 4249) if self.light_redraw_p < 1.0 else None
+ self.call_id = None # the views' per-call state id at the last decision
+ self.state_changes = 0 # decisions (after the first) whose per-call render state differs from the last one
+
+ def bind(self, env):
+ self.env = env
+ return self
+
+ def reset(self, B):
+ self.dr = self.views.draw(B) if self.randomise else None
+ self.n_dec = 0
+ self.prev_rgb = None
+ self.call_id = None
+ self.rhist = None
+ self.qd_hist = None
+ self.qd_log = []
+ self.lc_dec = None
+ if self.kmax > 0:
+ self.hist = LagHistory(B, self.kmax, self.dev)
+ if self.lag_range:
+ self.k = torch.randint(self.lag_range[0], self.lag_range[1] + 1, (B,), device=self.dev,
+ generator=self.lag_gen)
+ else:
+ self.k = torch.full((B,), self.lag, dtype=torch.long, device=self.dev)
+
+ def push(self, ws):
+ """After every 20 ms world step (``step_tap``)."""
+ if self.hist is not None and self.hist.ready:
+ self.hist.push(*_sane(ws.q, ws.cube_pos, ws.cube_quat, self.dev))
+ if self.qd_hist is not None:
+ self.qd_hist = torch.cat((qd_ticks(ws.q.to(self.dev))[:, None], self.qd_hist[:, :-1]), 1)
+
+ @torch.no_grad()
+ def __call__(self, ws, goal_pose, k=None):
+ t0 = time.time()
+ q = ws.q.to(self.dev, torch.float32)
+ cp, cq = ws.cube_pos.to(self.dev, torch.float32), ws.cube_quat.to(self.dev, torch.float32)
+ ok = torch.isfinite(q).all(-1) & torch.isfinite(cp).all(-1) & torch.isfinite(cq).all(-1)
+ q = torch.where(ok[:, None], q, torch.zeros_like(q))
+ cp = torch.where(ok[:, None], cp, torch.tensor([0.2, 0.0, 0.015], device=self.dev))
+ cq = torch.where(ok[:, None], cq, torch.tensor([1.0, 0.0, 0.0, 0.0], device=self.dev))
+ iq, icp, icq = q, cp, cq
+ if self.hist is not None:
+ if not self.hist.ready: # the first decision: the arm at rest since the start
+ self.hist.fill(torch.arange(len(q), device=self.dev), q, cp, cq)
+ elif float((self.hist.newest() - _state13(q, cp, cq)).abs().max()) > 1e-4:
+ raise RuntimeError("image lag: the 20 ms states are missing (run the episodes inside step_tap(env, "
+ "actor.push))")
+ iq, icp, icq = self.hist.get(self.k)
+ kw = {}
+ if self.redraw_gen is not None and self.dr is not None and self.n_dec > 0 and \
+ bool(torch.rand(1, generator=self.redraw_gen) >= self.light_redraw_p):
+ kw["keep"] = True # the last decision's random light / intrinsics stay
+ rgb = self.views.render(iq, icp, icq, goal_pose.to(self.dev, torch.float32), dr=self.dr, **kw)
+ cid = getattr(self.views, "call_id", None)
+ changed = cid is not None and self.call_id is not None and cid != self.call_id
+ self.call_id = cid
+ self.state_changes += int(changed)
+ img = to_input(rgb, fx=self.views.fx)
+ if self.dev.type == "cuda":
+ torch.cuda.synchronize()
+ t1 = time.time()
+ qd = ws.qd.to(self.dev, torch.float32).nan_to_num()
+ if self.qd_w is not None: # the robot's qdot estimate (the first decision: the arm at rest, 0)
+ tk = qd_ticks(ws.q.to(self.dev))
+ if self.qd_hist is None:
+ self.qd_hist = tk[:, None].expand(-1, self.qd_window, -1).clone()
+ elif not torch.equal(self.qd_hist[:, 0], tk):
+ raise RuntimeError("robot qdot: the 20 ms states are missing (run the episodes inside step_tap(env, "
+ "actor.push))")
+ qd = robot_qd(self.qd_hist, self.qd_w).float()
+ self.qd_log.append(qd.cpu())
+ if self.q_offset is not None: # the policy's joint frame (images stay the true state)
+ q = q + torch.as_tensor(self.q_offset, dtype=q.dtype, device=self.dev)
+ if EVAL_QD_GAIN != 1.0: # evaluation only (real2sim debugging): the student's qdot input x gain
+ qd = qd * EVAL_QD_GAIN
+ robot = torch.cat((q, qd), -1)
+ H = int(self.st.cfg.hist)
+ if H:
+ if self.rhist is None:
+ self.rhist = robot[:, None, :].expand(-1, H, -1).clone()
+ now = robot
+ robot = torch.cat((now, self.rhist.reshape(len(now), -1)), -1)
+ self.rhist = torch.cat((now[:, None, :], self.rhist[:, :-1]), 1)
+ if getattr(self.st.cfg, "cmd_in", False): # the last decision's executed targets - the measured q now
+ if self.env is None:
+ raise RuntimeError("cmd_in: bind the env (Actor.bind(env)) for its executed targets")
+ u = getattr(self.env, "u_exe", None)
+ qm = ws.q.to(self.dev, torch.float32).nan_to_num()
+ if self.n_dec == 0 or u is None:
+ cmd = torch.zeros(len(q), int(self.st.cfg.n_exec) * 6, device=self.dev)
+ else:
+ cmd = (u.to(self.dev, torch.float32) - qm[:, None, :]).nan_to_num().reshape(len(q), -1)
+ robot = torch.cat((robot, cmd), -1)
+ if self.lastcmd: # the student's last executed command (0 at the episode start; after cmd)
+ robot = torch.cat((robot, self.lastcmd_input(ws).to(robot)), -1)
+ prev = None
+ if getattr(self.st.cfg, "img_hist", False): # the last decision's images (the current ones at the first
+ own = self.prev_rgb is None or changed # call and after a change of the per-call render state)
+ prev = img if own else to_input(self.prev_rgb, fx=self.views.fx)
+ self.prev_rgb = rgb
+ out = []
+ for s in range(0, img.shape[0], 256):
+ with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=self.st.cfg.amp):
+ p_ = self.st.predict(img[s:s + 256], robot[s:s + 256]) if prev is None else \
+ self.st.predict(img[s:s + 256], robot[s:s + 256], prev[s:s + 256])
+ out.append(denormalise(self.st, p_))
+ self.n_dec += 1
+ delta = torch.cat(out)
+ if self.dev.type == "cuda":
+ torch.cuda.synchronize()
+ self.t_render += t1 - t0
+ self.t_model += time.time() - t1
+ self.calls += 1
+ u = q[:, None, :] + delta # [B, K, 6]
+ K, n = u.shape[1], self.st.cfg.n_exec
+ jj = torch.arange(n, device=self.dev)
+ kk = (jj + self.jaw_lead).clamp_max(K - 1)
+ ex = torch.cat((u[:, jj, :5], u[:, kk, 5:]), -1)
+ return ex.to(ws.q.device, torch.float64)
+
+ def lastcmd_input(self, ws):
+ """[B, 12] float64 raw last-command input of this decision (``lastcmd_raw``; class docstring)."""
+ e = self.env
+ if e is None:
+ raise RuntimeError("lastcmd student: set actor.env (Actor.bind(env)) = the JointVecEnv that runs the "
+ "episodes")
+ B = ws.q.shape[0]
+ if self.lc_dec is None:
+ out = lastcmd_zeros(B, self.dev)
+ else:
+ if e.u_exe is None or int(e.decisions) != self.lc_dec + int(e.B) or e.u_exe.shape[0] != B:
+ raise RuntimeError("lastcmd: the env did not step exactly once since the last decision (actor.env is "
+ "not the env that runs the episodes?)")
+ out = lastcmd_raw(e.u_exe[:, -1], e.u_exe[:, -2], ws.q.to(e.u_exe.device)).to(self.dev)
+ self.lc_dec = int(e.decisions)
+ return out
+
+
+# ---- VIRAL-style online DAgger --------------------------------------------------------------------------------------------
+@dataclass
+class OnlineConfig:
+ """VIRAL's loop (``viral_doorman_code.md`` sec. 3): every decision all worlds are rendered once, the student acts in
+ the student slots, the JT labels every world, the samples enter a GPU replay buffer and ``steps_per_iter`` training
+ steps run. Slots ``[0, teacher_share * envs)`` are JT-driven for the whole run (VIRAL: fixed env indices), the first
+ ``noise_share`` of them with Gaussian noise of ``noise`` x the JT's PPO std on its normalised action (DART)."""
+ envs: int = 1024
+ teacher_share: float = 0.5
+ noise_share: float = 0.5
+ noise: float = 1.0
+ nominal_share: float = 0.2 # slots drawn with the scene's own colours and camera poses
+ default_light_p: float = 0.25 # per decision: probability of the scene's own light (else a random one)
+ buffer: int = 40000 # replay samples (uint8 images on the GPU)
+ steps_per_iter: int = 8 # training steps per decision (batch = ViralConfig.batch)
+ lr: float = 1e-4 # constant (VIRAL: 2e-4 constant)
+ lr_backbone: float = 5e-5
+ iterations: int = 5000
+ eval_every: int = 500
+ save_every: int = 250
+ log_every: int = 25
+ warm_teacher_only: int = 0 # first iterations: every slot JT-driven (buffer fill)
+ lr_decay_start: int = -1 # >= 0: from this iteration the learning rates fall linearly (cosine-free) ...
+ lr_final_frac: float = 0.1 # ... to this fraction at the last iteration
+ # joint-reading offset (real2sim: a joint-map / table-height error of the real robot): with probability q_bias_p
+ # per world per episode, the student's q INPUT is the true q + U(-h, h) per joint (q_bias_deg = 6 half-widths,
+ # deg; jaw normally 0). The labels, the buffer's q (relative targets) and the student's executed targets stay in
+ # the true frame (target = true q + predicted delta = what a robot whose joint map is off by the same offset does).
+ q_bias_deg: tuple = ()
+ q_bias_p: float = 0.0
+ # robot timing and servo (real2sim; all off by default): the online env's robot dynamics stage
+ # (``JE.RobotDynConfig`` dict: delay, gain, lag, sag, noise, the guard's integral correction; {} = off), drawn per
+ # world per episode; the JT labels the reached states
+ dyn: dict = field(default_factory=dict)
+ dyn_student_only: bool = False # the stage only in the student-driven slots (the JT-driven slots stay nominal)
+ pause: dict = field(default_factory=dict) # the robot's hold state (``JE.PauseConfig``; {} = off)
+ # robot-like qdot of the student's INPUT (acting and the buffer's robot state) with probability qd_robot_p per world
+ # per episode: the least-squares slope over the last qd_window 20 ms states of q quantised to the STS3215 step
+ # 2 pi / 4096 (``robot_qd``; the robot's ``QdotEstimator``): exactly 0 when the arm is still
+ qd_robot_p: float = 0.0
+ qd_window: int = 3
+ # training episodes: horizon (20 ms steps) and the hold_cap rule (s held in the air; ``JE.hold_cap_kw``), longer for
+ # slow worlds; hold_obs_s: the held-time scale of the JT's observation (0 with a new cap = the old envs' 3.5 s, the
+ # scale of every run so far; jt_h110 was trained with 2.5 s; a 20 s scale breaks it)
+ horizon: int = 400
+ hold_cap_s: float = 3.5
+ hold_obs_s: float = 0.0
+ # the student's image lag range for this run (``ViralConfig.lag_range``, saved with the checkpoints; () = keep the
+ # student's own, e.g. from --config / --set)
+ lag_range: tuple = ()
+ # the loss-side qdot noise (``ViralConfig.qd_noise``): None = as before; a share p -> per sample the noise times
+ # U(0, 1), exactly 0 for the share p of the samples (the robot's exact-zero qdot)
+ qd_noise_zero_p: float | None = None
+ # real2sim (speed follows the measured speed): training-only per-sample factor on the student's qdot INPUT,
+ # U(qd_in_lo, qd_in_hi), exactly 0 for the share qd_in_zero_p (1, 1, 0 = off); acting keeps the measured qdot
+ qd_in_lo: float = 1.0
+ qd_in_hi: float = 1.0
+ qd_in_zero_p: float = 0.0
+ # real2sim: in robot-dynamics worlds (``dyn``), the JT labels with the commanded speed (the last decision's
+ # action-layer target change / 20 ms) in its qdot observation, so its labels keep the nominal pace on a slow arm
+ relabel_cmd_speed: bool = False
+ # ... only in the place phase (> 0): the cube held, lifted and within relabel_near_m (xy) of the goal; the grasp and
+ # the carry keep the measured-speed labels (robot 10-22: relabel everywhere carried the cube ~4 cm lower and grasped
+ # worse); 0 = everywhere
+ relabel_near_m: float = 0.0
+ # ... not in the grasp zone (> 0): no relabel while the cube is not held and the grasp point is within
+ # relabel_grasp_zone_m (xy) of it (grasp diagnosis 2026-10-23: relabel at the cube -> the student hovers above an
+ # off-centre cube with the jaw open on the robot); the approach, lift, carry and place keep the relabel; 0 = off
+ relabel_grasp_zone_m: float = 0.0
+ # the student must have the last-command input (``ViralConfig.lastcmd``, e.g. --config viral_r2s_v1_lastcmd.json):
+ # a guard against a launch with the wrong student config (the input itself follows the student's config)
+ require_lastcmd: bool = False
+ # studentlab (2026-10-22): goal jumps in the online env (``JE.GoalJumpConfig`` dict; {} = off): the goal moves
+ # while the cube is held near it, so the cube is past (or before) the new goal; the rendered goal, the JT
+ # observation and the aux targets read the moved goal from the next decision on; the sample of the decision
+ # before a jump gets no second-half label (``valid2`` False: its images showed the old goal)
+ goal_jump: dict = field(default_factory=dict)
+ # studentlab review (2026-10-23): per decision the probability of a NEW per-call render state (the light choice
+ # ``default_light_p``, the random lights and the random intrinsics; one state for all worlds of a call); else the
+ # last decision's state stays (``DRViews.render(keep=)``). 1 = a new draw every decision (the old behaviour). For
+ # the image history (``ViralConfig.img_hist``): the robot's consecutive frames share light and intrinsics, so a
+ # pair of images should as well; when the state changes, the decision's previous images are its current ones
+ # (acting) and its buffer link is cut (training), as at an episode start. Also used by the in-run evaluation.
+ light_redraw_p: float = 1.0
+ # real2sim (2026-10-23): the wrist-roll target cap of the online env (sim deg; ``JE.JointEnvConfig.roll_hi_deg``,
+ # the real roll ends at +101.2 sim deg); the JT's labels get the same cap, task rows whose start roll is above it
+ # are dropped from the pool, and the in-run evaluations use it too. None = off
+ roll_hi_deg: float | None = None
+ # real2sim v8 (2026-10-23; off by default): table height / tilt randomisation of the student's JOINT INPUT
+ # (``nedm.so101_policy.table_bias``, ``TableBiasConfig`` dict; {} = off): per world per episode with probability p
+ # a table plane (drop at x_ref, slopes in x / y); per decision the student reads q_obs = Phi(q), the joints whose
+ # gripper is at the same place relative to a world lying on that plane (under a lower table: FK lower by the drop
+ # under the gripper, the same gripper rotation; exact on the 3 pitch joints). Every joint quantity of the student
+ # is in that observed frame (``table_frame``): q input (+ the q_bias draw), qdot input J_Phi qdot, history, cmd /
+ # last-command inputs, the buffer's q and labels (Phi(q), Phi(teacher label)); its applied targets are
+ # Phi^-1(Phi(q) + predicted delta). Physics, the action layer and the teacher stay true; images and the aux
+ # targets too unless ``table_render``. Training samples are exact (a world whose map rows are not all exact adds
+ # no sample that decision; ``table_frame``). A dict with only a "note" is off (``table_bias.is_on``).
+ table_bias: dict = field(default_factory=dict)
+ # ... and the goal plate ("mat") thickness of the TRAINING renders (real scene only; () = off): per world per
+ # episode U(lo, hi) mm in the non-nominal slots (the real plate 3.9 mm, the scenes 1 mm), visual only
+ # (``RealDR.plate_thickness``: a cube over the plate that the jaws do not hold is drawn on its top; a held cube at
+ # its physics pose, sinking into a thicker plate); the training views get it from ``online_views_cfg``, the
+ # student's saved config and the evaluation views do not
+ plate_mm: tuple = ()
+ # ... and consistent images for the table planes (needs table_bias and a real scene without its own table_plane;
+ # False = off): in the worlds with a plane the training renders draw the arm at the student's reading (Phi of the
+ # image state, also with image lag) and the world on the plane (the cube sheared by the plane height under it and
+ # tilted with the plane; plate, floor, mat, walls, strip and ceiling on the plane; ``SO101Scene`` world_plane), so
+ # images and joint reading agree as on the robot (the arm in the image IS the reading); the aux cube target is the
+ # drawn cube (z + plane height). Off: the true arm and the sim-height world (the image-vs-reading mismatch tells
+ # the drop, a cue that exists only in sim)
+ table_render: bool = False
+ # real2sim v12 (2026-10-26): the action-layer floor of the online env with ``table_bias``: "true" (default, the v8
+ # coupling rule) = FLOOR above the TRUE (sim) table in every world, i.e. above the plane in the student's observed
+ # frame (robot: floor mode plane); "observed" = flat FLOOR above z = 0 of the OBSERVED frame, the robot's flat
+ # arm-frame floor: the online env's floor raised by -plane at the grasp point (``JE.JointEnvConfig.floor_raise`` =
+ # ``JE.raise_of_table``; every slot, student and JT), needs ``table_bias`` with a fixed ``plane``; the labelling JT
+ # must have been trained with the same floor raise (vision_viral.py online checks its env record); the checkpoint
+ # records it (``ckpt_record``: v8_online.student_floor) and the robot deploys it with the flat floor
+ # (``hw_lib.student_floor_mode``)
+ student_floor: str = "true"
+ # real2sim v8 (2026-10-23): the robot's image latency (``ImgLagConfig`` dict: lo_ms, hi_ms, redraw_p, per_camera,
+ # quantize; {} = off, the student's integer lag as before): a lag in ms per world (and camera), drawn again per
+ # decision, the images rendered from the interpolated past state and goal; replaces lag_range in this run
+ img_lag: dict = field(default_factory=dict)
+ # real2sim v12 visual fix (2026-10-26; {} = off): the gripper-look randomisation of the TRAINING renders
+ # (``nedm.render.gripper_look.GripperLookDR`` dict, ``RealDR.gripper_look``; per world per episode: albedo of the
+ # camera bracket plate and the servo bracket, the scene's fitted screws, extra marks, a bright plate top edge);
+ # the training views get it from ``online_views_cfg`` (as plate_mm), the student's saved config, the evaluation
+ # views and the robot do not; the nominal slots (nominal_share) keep the scene's look
+ gripper_look: dict = field(default_factory=dict)
+ # ... and a guard ("" = off): the run refuses a student whose scene file (sha256, after pin_real) is not this one
+ # (a held-out variant must not train on the fitted real look; a real-look variant must have it)
+ require_scene_sha256: str = ""
+
+ @staticmethod
+ def from_dict(d):
+ d = dict(d or {})
+ known = set(OnlineConfig.__dataclass_fields__)
+ bad = sorted(set(d) - known - {"note"})
+ if bad:
+ raise ValueError(f"unknown online config keys {bad}")
+ if d.get("table_bias"):
+ from nedm.so101_policy.table_bias import TableBiasConfig
+ TableBiasConfig.from_dict(d["table_bias"]) # validate now
+ if d.get("table_render"):
+ from nedm.so101_policy.table_bias import is_on
+ if not is_on(d.get("table_bias")):
+ raise ValueError("table_render: needs table_bias (the planes to draw)")
+ d["table_render"] = bool(d["table_render"])
+ if d.get("student_floor", "true") != "true":
+ if d["student_floor"] != "observed":
+ raise ValueError(f"student_floor {d['student_floor']!r}: 'true' (default) or 'observed'")
+ from nedm.so101_policy.table_bias import TableBiasConfig, is_on
+ if not is_on(d.get("table_bias")) or not TableBiasConfig.from_dict(d["table_bias"]).plane:
+ raise ValueError("student_floor observed: needs table_bias with a fixed plane (table_bias.plane; one "
+ "floor raise for all worlds)")
+ # the floor raise -plane within the env's limits (JE.FLOOR_RAISE_MAX, tighter than the plane's own): fail
+ # here, not when the online env is built (v12 review finding 6)
+ JE.raise_of_table(TableBiasConfig.from_dict(d["table_bias"]).plane)
+ if d.get("plate_mm"):
+ d["plate_mm"] = tuple(float(v) for v in d["plate_mm"])
+ if len(d["plate_mm"]) != 2 or not 0.0 < d["plate_mm"][0] <= d["plate_mm"][1] <= 20.0:
+ raise ValueError(f"plate_mm {list(d['plate_mm'])}: (lo, hi) mm with 0 < lo <= hi <= 20")
+ if ImgLagConfig.is_on(d.get("img_lag")):
+ ImgLagConfig.from_dict(d["img_lag"]) # validate now
+ if d.get("lag_range"):
+ raise ValueError("online config: img_lag replaces lag_range in the online loop; set only one")
+ if d.get("lag_range"):
+ d["lag_range"] = tuple(int(v) for v in d["lag_range"])
+ if len(d["lag_range"]) != 2 or not 0 <= d["lag_range"][0] <= d["lag_range"][1]:
+ raise ValueError(f"online lag_range {d['lag_range']}: (lo, hi) control steps, 0 <= lo <= hi")
+ if d.get("goal_jump"):
+ JE.goal_jump_config(d["goal_jump"]) # validate now
+ if "light_redraw_p" in d and not 0.0 <= float(d["light_redraw_p"]) <= 1.0:
+ raise ValueError(f"light_redraw_p {d['light_redraw_p']}: a probability in [0, 1]")
+ if d.get("roll_hi_deg") is not None:
+ d["roll_hi_deg"] = JE.roll_hi_config(d["roll_hi_deg"]) # validate now
+ if d.get("gripper_look"):
+ from nedm.render.gripper_look import GripperLookDR
+ GripperLookDR.from_dict(d["gripper_look"]) # validate now
+ if d.get("require_scene_sha256") and not (isinstance(d["require_scene_sha256"], str)
+ and len(d["require_scene_sha256"]) == 64):
+ raise ValueError(f"require_scene_sha256 {d['require_scene_sha256']!r}: a sha256 hex string or ''")
+ return OnlineConfig(**{k: v for k, v in d.items() if k in known})
+
+
+def check_scene_requirement(cfg: ViralConfig, ocfg: OnlineConfig) -> None:
+ """``OnlineConfig.require_scene_sha256`` (v12 visual fix; '' = no check): the student's scene file (its pinned
+ sha256, after ``pin_real``) must be the named one, else ValueError (e.g. a held-out run on the real-look scene, or a
+ real-look run with the old scene because of a wrong --config / R2S_SCENE)."""
+ want = getattr(ocfg, "require_scene_sha256", "") or ""
+ if want and (cfg.scene_sha256 or "") != want:
+ raise ValueError(f"online config require_scene_sha256 {want[:12]}: the student's scene {cfg.scene!r} has "
+ f"sha256 {(cfg.scene_sha256 or '-')[:12]} (wrong --config / R2S_SCENE?)")
+
+
+def online_floor_raise(ocfg: OnlineConfig):
+ """The online env's floor raise (``JE.JointEnvConfig.floor_raise``; None = off): -plane of the fixed table plane
+ (``JE.raise_of_table``) with ``student_floor`` "observed", else None (a zero plane: None)."""
+ if getattr(ocfg, "student_floor", "true") != "observed":
+ return None
+ from nedm.so101_policy.table_bias import TableBiasConfig
+ return JE.raise_of_table(TableBiasConfig.from_dict(ocfg.table_bias).plane)
+
+
+def online_views_cfg(cfg: ViralConfig, ocfg: OnlineConfig) -> ViralConfig:
+ """The student config of the online loop's TRAINING views (``make_views``): ``cfg`` itself, or a copy whose
+ ``real_dr`` adds the plate thickness randomisation (``ocfg.plate_mm`` -> ``RealDR.plate_thickness``, m) and / or
+ the gripper look (v12, ``ocfg.gripper_look`` -> ``RealDR.gripper_look``, replacing a student's own). The student
+ keeps ``cfg`` (its checkpoints and the evaluation views never see the options)."""
+ look = dict(getattr(ocfg, "gripper_look", None) or {})
+ if not ocfg.plate_mm and not look:
+ return cfg
+ if not cfg.scene:
+ raise ValueError("plate_mm / gripper_look: the real scene only (ViralConfig.scene)")
+ from dataclasses import replace as _rep
+ over = {}
+ if ocfg.plate_mm:
+ lo, hi = (float(v) * 1e-3 for v in ocfg.plate_mm)
+ over["plate_thickness"] = [lo, hi]
+ rdr = _merge(cfg.real_dr or {}, over)
+ if look:
+ rdr["gripper_look"] = look
+ return _rep(cfg, real_dr=rdr)
+
+
+class ReplayBuffer:
+ """Ring buffer of student samples on one device: rgb uint8 [C, cams, H, W, 3], q, qd, labels of this decision
+ and of the next one (absolute targets [5, 6] each; ``valid2`` = the next decision is in the same episode), aux
+ targets, and whether per-image colour augmentation applies (``aug``: not for nominal-slot samples).
+
+ ``prev_link`` (image history, ``ViralConfig.img_hist``): per sample the slot of the same world's previous-decision
+ sample (``prev``; -1 = none: an episode start) and that sample's id (``prev_sid``); every sample gets a running id
+ (``sid``). ``prev_valid(i)``: the previous sample exists (same episode) and its slot was not overwritten since."""
+
+ def __init__(self, cap, cams, res, device, robot_dim=12, prev_link=False):
+ f = dict(device=device)
+ self.cap, self.n, self.ptr = int(cap), 0, 0
+ self.sid = self.prev = self.prev_sid = None
+ if prev_link:
+ self.sid = torch.full((self.cap,), -1, dtype=torch.long, **f)
+ self.prev = torch.full((self.cap,), -1, dtype=torch.long, **f)
+ self.prev_sid = torch.full((self.cap,), -1, dtype=torch.long, **f)
+ self.count = 0
+ self.rgb = torch.zeros(self.cap, cams, res, res, 3, dtype=torch.uint8, **f)
+ self.q = torch.zeros(self.cap, 6, **f)
+ self.robot = torch.zeros(self.cap, robot_dim, **f)
+ self.lab1 = torch.zeros(self.cap, JE.STEPS, 6, **f)
+ self.lab2 = torch.zeros(self.cap, JE.STEPS, 6, **f)
+ self.valid2 = torch.zeros(self.cap, dtype=torch.bool, **f)
+ self.aux = torch.zeros(self.cap, AUX_DIM, **f)
+ self.aug = torch.zeros(self.cap, dtype=torch.bool, **f)
+
+ def add(self, rgb, q, robot, lab, aux, aug, prev=None):
+ """-> the slots [n]. ``prev`` [n] long (``prev_link``): slots of the same worlds' previous samples (-1: none)."""
+ n = rgb.shape[0]
+ idx = (self.ptr + torch.arange(n, device=rgb.device)) % self.cap
+ if self.sid is not None: # read the previous samples' ids BEFORE this write may overwrite them
+ p = torch.full((n,), -1, dtype=torch.long, device=rgb.device) if prev is None else \
+ prev.to(rgb.device, torch.long)
+ psid = torch.where(p >= 0, self.sid[p.clamp_min(0)], torch.full_like(p, -1))
+ self.rgb[idx], self.q[idx], self.robot[idx], self.lab1[idx] = rgb, q.float(), robot.float(), lab.float()
+ self.valid2[idx] = False
+ self.aux[idx], self.aug[idx] = aux.float(), aug
+ if self.sid is not None:
+ self.sid[idx] = self.count + torch.arange(n, device=rgb.device)
+ self.count += n
+ self.prev[idx], self.prev_sid[idx] = p, psid
+ self.ptr = int((self.ptr + n) % self.cap)
+ self.n = min(self.cap, self.n + n)
+ return idx
+
+ def sample(self, b, gen=None):
+ return torch.randint(self.n, (int(b),), device=self.rgb.device, generator=gen)
+
+ def prev_valid(self, i):
+ """[len(i)] bool: sample i has its world's previous-decision sample in the buffer (same episode, not
+ overwritten)."""
+ p = self.prev[i]
+ return (self.prev_sid[i] >= 0) & (self.sid[p.clamp_min(0)] == self.prev_sid[i])
+
+ def prev_rgb(self, i):
+ """The previous-decision images of samples i (their own images where ``prev_valid`` is False)."""
+ ok = self.prev_valid(i)
+ return torch.where(ok[:, None, None, None, None], self.rgb[self.prev[i].clamp_min(0)], self.rgb[i]), ok
+
+
+def relabel_mask(o, env):
+ """[B] bool: the worlds whose JT label gets the commanded speed (``OnlineConfig.relabel_cmd_speed``): robot-dynamics
+ worlds, not the first decision of an episode (``env.u_exe`` still holds the previous episode's targets after an
+ auto reset), only in the place phase if ``relabel_near_m`` > 0, and not in the grasp zone if
+ ``relabel_grasp_zone_m`` > 0."""
+ m = env.dyn.on & (env.ep_len > 0)
+ F = env.task.F
+ if o.relabel_near_m > 0 and F is not None: # place phase only
+ m = m & F["held"] & env.task.tr.lifted & ((F["c"][:, :2] - env.task.goal_xy).norm(dim=-1) < o.relabel_near_m)
+ if o.relabel_grasp_zone_m > 0 and F is not None: # not at the grasp
+ m = m & ~(~F["held"] & (F["dxy"] < o.relabel_grasp_zone_m))
+ return m
+
+
+class OnlineDAgger:
+ """The online loop (``OnlineConfig``). Tasks: the start states and goals of a task table (``state_*``, goal_xy,
+ goal_yaw), drawn uniformly at every reset. Image lag (``st.cfg.lag_range``, else ``st.cfg.lag``): drawn per world
+ per episode; every world's 20 ms states feed a ``LagHistory`` (``JointVecEnv.step`` hook). Robot timing / servo
+ (``OnlineConfig.dyn``: the env's ``RobotDyn``) and robot-like qdot inputs (``qd_robot_p``: per-world tick history of
+ the 20 ms states, same hook) are drawn per world per episode as well. Last-command input (``st.cfg.lastcmd``): every
+ world's (student and teacher slots) ``lastcmd_raw`` of the env's ``u_exe``, 0 at its episode start (``lc_fresh``),
+ in the acting input and the buffer's robot vector (``ViralConfig.robot_dim``). Wrist-roll cap
+ (``OnlineConfig.roll_hi_deg``): the env caps every executed target, the JT's labels are capped the same way (the
+ student never learns a roll above the cap), task rows that start above it leave the pool. Image latency
+ (``OnlineConfig.img_lag``, ``ImgLagConfig``; real2sim v8): instead of the student's integer lag, a lag in ms per
+ world (and camera), drawn at the episode start and again per decision (``redraw_p``), the images rendered from the
+ interpolated past state and goal (``LagHistory.at``; ``lag_x`` [N, 1 or C] control steps)."""
+
+ def __init__(self, st: ViralNet, jt, tasks, nrd_ckpt, views: DRViews, ocfg: OnlineConfig, device="cuda", seed=0,
+ log=log_default, world="nrd"):
+ """``world``: the online env's world (``nrd``; tests: ``kin``)."""
+ if ocfg.require_lastcmd and not getattr(st.cfg, "lastcmd", False):
+ raise ValueError("online config require_lastcmd: the student has no last-command input "
+ "(ViralConfig.lastcmd; --config viral_r2s_v1_lastcmd.json)")
+ self.st, self.jt, self.views, self.o, self.dev, self.log = st, jt, views, ocfg, torch.device(device), log
+ N = int(ocfg.envs)
+ cfg = JE.JointEnvConfig(world=world, num_envs=N, device=device, ckpts=[str(nrd_ckpt)], auto_reset=True,
+ stagger=True, starts="", seed=seed, horizon=int(ocfg.horizon), dyn=ocfg.dyn or None,
+ pause=ocfg.pause or None, goal_jump=ocfg.goal_jump or None,
+ roll_hi_deg=ocfg.roll_hi_deg, floor_raise=online_floor_raise(ocfg),
+ **JE.hold_cap_kw(ocfg.hold_cap_s, ocfg.hold_obs_s))
+ self.env = JE.JointVecEnv(cfg, jt.codec)
+ f64 = dict(dtype=torch.float64, device=self.dev)
+ self.env.bank = {k: torch.as_tensor(tasks[f"state_{k}"], **f64) for k in
+ ("q", "qd", "cube_pos", "cube_quat", "cube_v", "cube_w")}
+ nt = len(tasks["seeds"])
+ self.env.pool = dict(i=torch.arange(nt, device=self.dev), goal_xy=torch.as_tensor(tasks["goal_xy"], **f64),
+ goal_yaw=torch.as_tensor(tasks["goal_yaw"], **f64))
+ self.roll_cap = self.env.roll_cap() # the wrist-roll cap (rad; None = off): labels, pool, statistics
+ if self.roll_cap is not None: # no start above the cap (no row: the pool and its draws stay)
+ keep = ~(self.env.bank["q"][:, JE.ROLL] > self.roll_cap)
+ if not bool(keep.all()):
+ ki = keep.nonzero().flatten()
+ self.env.pool = {k: v[ki] for k, v in self.env.pool.items()}
+ self.env.roll_dropped = int((~keep).sum()) # the record (roll_info: bank_dropped = task rows here)
+ log(f"roll cap {ocfg.roll_hi_deg:g} deg: {int((~keep).sum())} of {nt} training tasks start above it "
+ f"(dropped); labels capped")
+ self.gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 5)
+ nt_ = int(round(ocfg.teacher_share * N))
+ slot = torch.arange(N, device=self.dev)
+ self.teacher = slot < nt_
+ self.noisy = slot < int(round(ocfg.noise_share * nt_))
+ if ocfg.dyn_student_only and self.env.dyn is not None:
+ self.env.dyn.set_eligible(~self.teacher)
+ self.nominal = torch.rand(N, device=self.dev, generator=self.gen) < ocfg.nominal_share
+ self.H = int(st.cfg.hist)
+ self.n_cmd = int(st.cfg.n_exec) * 6 if getattr(st.cfg, "cmd_in", False) else 0 # cmd input (studentlab)
+ self.img_hist = bool(getattr(st.cfg, "img_hist", False)) # image history (studentlab)
+ self.LC = bool(getattr(st.cfg, "lastcmd", False)) # last-command input (real2sim)
+ self.lc_fresh = torch.ones(N, dtype=torch.bool, device=self.dev) # lastcmd: no command yet in the episode
+ # robot vector [q, qd, history, (cmd), (lastcmd)] = 12 (1 + H) + n_cmd + 12 LC (ViralConfig.robot_dim)
+ self.buf = ReplayBuffer(ocfg.buffer, len(st.cfg.cameras), st.cfg.res, self.dev, st.cfg.robot_dim,
+ prev_link=self.img_hist)
+ self.rhist = torch.zeros(N, max(self.H, 1), 12, device=self.dev)
+ self.fresh = torch.ones(N, dtype=torch.bool, device=self.dev) # the next decision starts an episode
+ self.prev_rgb = None # img_hist: the last decision's images
+ self.last = {} # the last decision's inputs (tests)
+ self.light_prev = None # light_redraw_p < 1: the last light
+ self.redraw_gen = torch.Generator().manual_seed(int(seed) + 919) if float(ocfg.light_redraw_p) < 1.0 else None
+ self.call_id = None # the views' per-call state id
+ if self.img_hist and self.redraw_gen is None and getattr(views, "call_id", None) is not None:
+ log("NOTE: img_hist with light_redraw_p 1: a new light / intrinsics draw at most decisions, so most image "
+ "pairs are cut (previous images = current ones); light_redraw_p 0.1 keeps ~91 % of them")
+ self.kmax = int(st.cfg.lag_max)
+ self.lag_hist = LagHistory(N, self.kmax, self.dev) if self.kmax > 0 else None
+ lo, hi = (int(v) for v in st.cfg.lag_range)
+ self.lag_lo, self.lag_hi = (lo, hi) if hi > 0 else (int(st.cfg.lag), int(st.cfg.lag))
+ self.lagk = torch.zeros(N, dtype=torch.long, device=self.dev)
+ self.lag_gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 77)
+ self.il = ImgLagConfig.from_dict(ocfg.img_lag) if ImgLagConfig.is_on(ocfg.img_lag) else None # v8 img lag
+ self.lag_x = None # [N, 1 or C] float control steps (img_lag)
+ self.stale = 0 # img_lag + goal jumps: decisions left out (old goal shown)
+ if self.il is not None:
+ self.kmax = self.il.kmax
+ self.lag_hist = LagHistory(N, self.kmax, self.dev, goal=True)
+ self.lag_x = torch.zeros(N, len(st.cfg.cameras) if self.il.per_camera else 1, device=self.dev)
+ self.il_gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 177)
+ log(f"image lag: img_lag {asdict(self.il)} (history {self.kmax} steps) replaces the student's lag "
+ f"{st.cfg.lag} / lag_range {list(st.cfg.lag_range)} in the online loop")
+ self.qb = torch.zeros(N, 6, device=self.dev) # per-world offset of the student's q input (rad)
+ self.qb_h = None
+ if ocfg.q_bias_p > 0 and ocfg.q_bias_deg:
+ if len(ocfg.q_bias_deg) != 6:
+ raise ValueError("q_bias_deg: 6 half-widths (deg)")
+ self.qb_h = torch.deg2rad(torch.tensor([float(v) for v in ocfg.q_bias_deg], device=self.dev))
+ self.qb_gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 91)
+ self.tb = None # v8: table height / tilt of the student's q input (OnlineConfig.table_bias)
+ self.tb_render = False # ... and the consistent images (OnlineConfig.table_render)
+ from nedm.so101_policy import table_bias as TBI
+ if TBI.is_on(ocfg.table_bias):
+ from nedm.so101_policy.kin import SO101Kin
+ self.tb = TBI.TableBiasConfig.from_dict(ocfg.table_bias)
+ self.tb_gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 97)
+ self.tb_plane = torch.zeros(N, 3, dtype=torch.float64, device=self.dev) # per world (zeros: off)
+ self.tb_on = torch.zeros(N, dtype=torch.bool, device=self.dev)
+ self.tb_kin = SO101Kin(self.dev)
+ # log statistics since the last log row (``tb_note``): largest residual of the rows below TOL (frame map,
+ # applied targets), counts [rows above TOL, rows] of the planed worlds (frame map, student-slot applied
+ # targets), [samples skipped, samples] (a world whose frame map was not exact)
+ self.tb_res = torch.zeros(2, dtype=torch.float64, device=self.dev)
+ self.tb_cnt = torch.zeros(6, dtype=torch.long, device=self.dev)
+ self.tb_render = bool(ocfg.table_render)
+ if self.tb_render and not getattr(views, "table_render_ok", False):
+ raise ValueError("table_render: the training views must draw per-world table planes (DRViews of a real "
+ "scene without its own table_plane)")
+ log(f"table bias of the student's q input: {json.dumps(self.tb.to_dict())}"
+ + (" + consistent images (arm at the reading, world on the plane)" if self.tb_render else ""))
+ if self.env.cfg.floor_raise is not None or getattr(ocfg, "student_floor", "true") != "true":
+ log(f"student floor {ocfg.student_floor}: the online env's floor 1.5 mm above z = "
+ f"{self.env.cfg.floor_raise} (c0 + c1 x + c2 y at the grasp point, true frame; None = z 0) = flat "
+ "in the observed frame (the robot's flat floor)")
+ elif ocfg.table_render:
+ raise ValueError("table_render: needs table_bias")
+ if ocfg.plate_mm and not getattr(views, "plate_on", False):
+ raise ValueError("plate_mm: the training views need the plate thickness randomisation "
+ "(make_views(online_views_cfg(st.cfg, ocfg), ...))")
+ if getattr(ocfg, "gripper_look", None):
+ from nedm.render.gripper_look import GripperLookDR
+ if GripperLookDR.from_dict(ocfg.gripper_look).on and not getattr(views, "look_on", False):
+ raise ValueError("gripper_look: the training views need the gripper-look randomisation "
+ "(make_views(online_views_cfg(st.cfg, ocfg), ...))")
+ self.qd_rob = torch.zeros(N, dtype=torch.bool, device=self.dev) # worlds with the robot-like qdot input
+ self.qd_hist = None # [N, W, 6] q in encoder ticks, 0 = now
+ if ocfg.qd_robot_p > 0:
+ self.qd_w = qd_weights(ocfg.qd_window).to(self.dev)
+ self.qd_hist = torch.zeros(N, int(ocfg.qd_window), 6, dtype=torch.float64, device=self.dev)
+ self.qd_gen = torch.Generator(device=self.dev).manual_seed(int(seed) + 131)
+ if ocfg.qd_noise_zero_p is not None and not 0.0 <= float(ocfg.qd_noise_zero_p) <= 1.0:
+ raise ValueError(f"qd_noise_zero_p {ocfg.qd_noise_zero_p}: a share in [0, 1] (None = off)")
+ self.drc = DRConfig.from_dict(st.cfg.dr)
+ views.dr = self.drc
+ self.dr = None
+ self.prev_slot = torch.full((N,), -1, dtype=torch.long, device=self.dev)
+ bb = st.backbone_params()
+ bb_ids = {id(p) for p in bb}
+ rest = [p for p in st.parameters() if p.requires_grad and id(p) not in bb_ids]
+ self.opt = torch.optim.AdamW([dict(params=rest, lr=ocfg.lr), dict(params=bb, lr=ocfg.lr_backbone)],
+ weight_decay=st.cfg.weight_decay)
+ self.it = 0
+ self.samples = 0
+ self.stats = dict(ep_student=0, len_student=0, ep_teacher=0, len_teacher=0)
+ if self.env.goal_jump is not None: # episodes with >= 1 goal jump (and their lenient successes)
+ self.stats.update(ep_jump_student=0, len_jump_student=0, ep_jump_teacher=0, len_jump_teacher=0)
+ if self.img_hist: # in-episode image pairs, and those with the same per-call render state
+ self.stats.update(img_pairs=0, img_pairs_same=0)
+ if self.roll_cap is not None: # episodes whose commanded wrist roll went above the cap
+ self.stats.update(roll_over_student=0, roll_over_teacher=0)
+
+ def _lag_reset(self, idx):
+ """Episode start of worlds ``idx`` (the env already holds their start states): lag draw, history = start."""
+ if self.lag_hist is None:
+ return
+ ws = self.env.ws
+ q, cp, cq = _sane(ws.q[idx], ws.cube_pos[idx], ws.cube_quat[idx], self.dev)
+ if self.il is not None: # img_lag: history = start state and goal, a new lag per world (camera)
+ self.lag_hist.fill(idx, q, cp, cq, self._goal_pose()[idx])
+ self.lag_x[idx] = self.il.draw(len(idx), self.lag_x.shape[1], self.il_gen, self.dev)
+ return
+ self.lag_hist.fill(idx, q, cp, cq)
+ self.lagk[idx] = torch.randint(self.lag_lo, self.lag_hi + 1, (len(idx),), device=self.dev,
+ generator=self.lag_gen)
+
+ def _goal_pose(self, task=None):
+ """[N, 3] float32 goal pose (x, y, yaw) of every world (as rendered)."""
+ task = self.env.task if task is None else task
+ return torch.cat((task.goal_xy, task.goal_yaw[:, None]), -1).float()
+
+ def _lag_redraw(self):
+ """img_lag, decision start: every world (camera) draws a new lag with probability redraw_p (the same random
+ numbers are used whatever the share is)."""
+ il = self.il
+ if il is None or il.redraw_p <= 0.0:
+ return
+ N, C = self.lag_x.shape
+ m = torch.rand(N, device=self.dev, generator=self.il_gen) < il.redraw_p
+ self.lag_x = torch.where(m[:, None], il.draw(N, C, self.il_gen, self.dev), self.lag_x)
+
+ def _lag_states(self, gp):
+ """img_lag: per lag column (1, or one per camera with ``per_camera``) the image state ``lag_x`` steps back
+ (``LagHistory.at``: q, cube position, cube quaternion, goal pose of then) -> list of tuples."""
+ return [self.lag_hist.at(self.lag_x[:, c], gp) for c in range(self.lag_x.shape[1])]
+
+ def _render_lagged(self, gp, light, kw, states=None, iqs=None, rkw=None):
+ """img_lag: the images of every world from its state ``lag_x`` steps back (``LagHistory.at``; ``states``: the
+ ``_lag_states`` already taken) -> (rgb, cube position and goal pose of the (first camera's) image state, [N]
+ bool: every camera shows the current goal). ``per_camera``: one render call per camera; the later calls keep
+ the first call's light and intrinsics. ``iqs`` (v8 ``table_render``): per lag column the arm state to draw
+ instead (Phi of the image state); ``rkw``: the other render inputs (``plane``, ``held``)."""
+ states = self._lag_states(gp) if states is None else states
+ rkw = rkw or {}
+ if len(states) == 1:
+ iq, icp, icq, igp = states[0]
+ iq = iq if iqs is None else iqs[0]
+ rgb = self.views.render(iq, icp, icq, igp, dr=self.dr, light=light, **kw, **rkw)
+ return rgb, icp, igp, (igp == gp).all(-1)
+ outs, icp, igp, cur = [], None, None, None
+ for c, (iq, cp_c, icq, gp_c) in enumerate(states):
+ iq = iq if iqs is None else iqs[c]
+ r = self.views.render(iq, cp_c, icq, gp_c, dr=self.dr, light=light, **(kw if c == 0 else dict(keep=True)),
+ **rkw)
+ outs.append(r[:, c].clone())
+ same = (gp_c == gp).all(-1)
+ if c == 0:
+ icp, igp, cur = cp_c, gp_c, same
+ else:
+ cur = cur & same
+ return torch.stack(outs, 1), icp, igp, cur
+
+ def _bias_reset(self, idx):
+ """Episode start of worlds ``idx``: draw the offset of the student's q input (``OnlineConfig.q_bias_*``) and
+ the world's table plane (``OnlineConfig.table_bias``; own generator)."""
+ if getattr(self, "tb", None) is not None:
+ from nedm.so101_policy import table_bias as TBI
+ pl, on = TBI.sample(len(idx), self.tb, self.tb_gen, self.dev)
+ self.tb_plane[idx], self.tb_on[idx] = pl, on
+ if self.qb_h is None:
+ return
+ n = len(idx)
+ on = torch.rand(n, device=self.dev, generator=self.qb_gen) < self.o.q_bias_p
+ u = torch.rand(n, 6, device=self.dev, generator=self.qb_gen) * 2 - 1
+ self.qb[idx] = u * self.qb_h[None] * on[:, None]
+
+ def table_frame(self, q, qf, qd, lab, u_exe=None, iq=None, u_used=None):
+ """The observed (table) frame of this decision (``OnlineConfig.table_bias``; ``table_bias`` module docstring):
+ one batched Phi under each world's plane of the true q [N, 6] (float64, finite; ``qf`` = its float32 input
+ copy), of the labels [N, 5, 6], of the last decision's executed targets [N, 5, 6] (the cmd / last-command
+ inputs; None: not needed; ``u_used`` [N] bool: the worlds whose inputs use them, not at an episode start) and
+ of the lagged image state ``iq`` [G N, 6] (``table_render`` with image lag; G = 1, or one block of N rows per
+ lag column of ``OnlineConfig.img_lag`` per_camera; None: not needed); the qdot reading J_Phi qd analytic
+ (``table_bias.observe_qd``) -> dict b [N, 6] float32 (reading - q), b64, q [N, 6] float32 (the reading qf + b),
+ q64 [N, 6] float64 (Phi(q)), qd [N, 6] float32, lab [N, 5, 6] float64, u_exe [N, 5, 6] float64 or None, iq
+ [G N, 6] float32 (Phi(iq); None if not asked), skip [N] bool (a world
+ with a plane whose map rows are not all exact, ``table_bias.EXACT``: no training sample this decision),
+ lab_bad [N] bool (its label rows are not exact: it does not complete the previous sample). Rows above
+ ``table_bias.TOL`` (no image) are acting-only fallbacks: x + b. Worlds without a plane get every value back as
+ given."""
+ from nedm.so101_policy import table_bias as TBI
+ N, f64 = qf.shape[0], torch.float64
+ pl, on = self.tb_plane, self.tb_on
+ K = lab.shape[1]
+ rows, planes = [q, lab.reshape(-1, 6).to(f64)], [pl, pl.repeat_interleave(K, 0)]
+ ons = [on, on.repeat_interleave(K)] # rows of the worlds with a plane (statistics)
+ if u_exe is not None:
+ rows.append(u_exe.to(self.dev, f64).reshape(-1, 6))
+ planes.append(pl.repeat_interleave(u_exe.shape[1], 0))
+ ons.append(on.repeat_interleave(u_exe.shape[1]))
+ G = 0 if iq is None else iq.shape[0] // N # image-state blocks (img_lag per_camera: one per camera)
+ if iq is not None:
+ if iq.shape[0] != G * N:
+ raise ValueError(f"table_frame: iq rows {iq.shape[0]} not a multiple of {N} worlds")
+ rows.append(iq.to(self.dev, f64))
+ planes.append(pl if G == 1 else pl.repeat(G, 1))
+ ons.append(on if G == 1 else on.repeat(G))
+ out, res = TBI.observe(self.tb_kin, torch.cat(rows), torch.cat(planes))
+ bad, inexact = res > TBI.TOL, res > TBI.EXACT # no image (acting fallback) / not exact (no training)
+ q64 = out[:N]
+ b64 = q64 - q
+ qd_obs = torch.where(on[:, None], TBI.observe_qd(self.tb_kin, q, qd.to(f64), pl, q64), qd.to(f64)).to(qd.dtype)
+ k1 = N + N * K
+ k2 = k1 + (0 if u_exe is None else u_exe.shape[0] * u_exe.shape[1])
+
+ def mapped(x, lo, hi): # rows [lo, hi) of the batch, fallback x + b where they have no image
+ m = bad[lo:hi].reshape(x.shape[:-1])[..., None]
+ return torch.where(m, x.to(f64) + b64[:, None, :], out[lo:hi].reshape(x.shape))
+
+ per = lambda m, lo, hi: m[lo:hi].reshape(N, -1).any(-1) # noqa: E731
+ lab_bad = per(inexact, N, k1)
+ skip = inexact[:N] | lab_bad
+ if u_exe is not None:
+ skip = skip | (per(inexact, k1, k2) & (torch.ones_like(on) if u_used is None else u_used))
+ iq_obs = None
+ if iq is not None:
+ skip = skip | inexact[k2:].reshape(G, N).any(0)
+ bg = b64 if G == 1 else b64.repeat(G, 1)
+ iq_obs = torch.where(bad[k2:, None], iq.to(self.dev, f64) + bg, out[k2:]).float()
+ self.tb_note(res, torch.cat(ons), frame=True, skip=(skip & on, on))
+ return dict(b=b64.float(), b64=b64, q=qf + b64.float(), q64=q64, qd=qd_obs, lab=mapped(lab, N, k1),
+ u_exe=None if u_exe is None else mapped(u_exe, k1, k2), iq=iq_obs, skip=skip & on,
+ lab_bad=lab_bad & on)
+
+ def table_applied(self, u_obs, si, b64):
+ """Applied (true-frame) targets of the student slots ``si``: Phi^-1 of their observed-frame targets u_obs
+ [n, n_exec, 6] (``table_bias.to_true``; the jaw unchanged); rows without a preimage (near the reach limit,
+ residual above ``table_bias.TOL``): u_obs - b of the decision (``b64`` [n, 6] float64) -> float64, same
+ shape."""
+ from nedm.so101_policy import table_bias as TBI
+ k = u_obs.shape[1]
+ u, res = TBI.to_true(self.tb_kin, u_obs.reshape(-1, 6).to(torch.float64),
+ self.tb_plane[si].repeat_interleave(k, 0))
+ self.tb_note(res, self.tb_on[si].repeat_interleave(k, 0), frame=False)
+ u = u.reshape(u_obs.shape)
+ bad = (res > TBI.TOL).reshape(u_obs.shape[:2])[..., None]
+ return torch.where(bad, u_obs.to(torch.float64) - b64[:, None, :], u)
+
+ def tb_note(self, res, row_on, frame=True, skip=None):
+ """Log statistics of the joint map (``log_extra``, since the last log row; rows of the worlds with a plane
+ only): tb_res_um = the largest residual of the rows below ``table_bias.TOL`` (frame map; tb_res_applied_um:
+ the student slots' applied targets), tb_bad_frame / tb_bad_applied = the share of rows above TOL (acting
+ fallback), tb_skip = the share of samples of planed worlds not added (map not exact)."""
+ from nedm.so101_policy import table_bias as TBI
+ k = 0 if frame else 1
+ m = row_on.to(res.device)
+ bad = (res > TBI.TOL) & m
+ good = torch.where(m & ~bad, res, torch.zeros_like(res))
+ self.tb_res[k] = torch.maximum(self.tb_res[k], good.max() if good.numel() else self.tb_res[k])
+ self.tb_cnt[2 * k] += bad.sum()
+ self.tb_cnt[2 * k + 1] += m.sum()
+ if skip is not None:
+ self.tb_cnt[4] += skip[0].sum()
+ self.tb_cnt[5] += skip[1].sum()
+
+ def _qd_reset(self, idx):
+ """Episode start of worlds ``idx``: robot-like qdot draw (``OnlineConfig.qd_robot_p``), tick history = start."""
+ if self.qd_hist is None:
+ return
+ self.qd_rob[idx] = torch.rand(len(idx), device=self.dev, generator=self.qd_gen) < self.o.qd_robot_p
+ self.qd_hist[idx] = qd_ticks(self.env.ws.q[idx]).to(self.qd_hist)[:, None].expand(-1, self.qd_hist.shape[1],
+ -1)
+
+ def qd_input(self, qd):
+ """[N, 6] float32 qdot of the student's input: the robot-like slope in the ``qd_rob`` worlds, else ``qd``."""
+ if self.qd_hist is None:
+ return qd
+ return torch.where(self.qd_rob[:, None], robot_qd(self.qd_hist, self.qd_w).to(qd), qd)
+
+ def lastcmd_input(self, q, u=None):
+ """[N, 12] float64 raw last-command input of every world (``lastcmd_raw``): the env's ``u_exe`` (the targets of
+ the decision before, after the action layer; ``u``: those in another frame, the table frame) vs q [N, 6]; 0 in
+ the worlds at an episode start (``lc_fresh``; ``env.u_exe`` is not cleared at an automatic reset)."""
+ u = self.env.u_exe if u is None else u
+ if u is None:
+ return lastcmd_zeros(q.shape[0], self.dev)
+ return lastcmd_raw(u[:, -1], u[:, -2], q, self.lc_fresh)
+
+ def _lag_hook(self, e, j):
+ if self.il is not None: # img_lag: the goal of every 20 ms state as well
+ self.lag_hist.push(*_sane(e.ws.q, e.ws.cube_pos, e.ws.cube_quat, self.dev), goal=self._goal_pose(e.task))
+ return
+ self.lag_hist.push(*_sane(e.ws.q, e.ws.cube_pos, e.ws.cube_quat, self.dev))
+
+ def _step_hook(self, e, j):
+ """After every 20 ms step: the image-lag history and / or the tick history of the robot-like qdot."""
+ if self.lag_hist is not None:
+ self._lag_hook(e, j)
+ if self.qd_hist is not None:
+ self.qd_hist = torch.cat((qd_ticks(e.ws.q).to(self.qd_hist)[:, None], self.qd_hist[:, :-1]), 1)
+
+ def ckpt_record(self) -> dict:
+ """Checkpoint keys of the v8 training options (``save_student(**extra)``): ``v8_online`` = the image lag
+ (``img_lag``) and the table randomisation (``table_bias``, ``table_render``, ``plate_mm``) the student was
+ trained with; {} while all of them are off (the old checkpoint layout bit for bit). The evaluation does not
+ read it (it renders with ``ViralConfig.lag``); the robot reads ``table_bias`` and ``student_floor`` for its
+ floor mode (``hw_lib.student_floor_mode``: table_bias on = the floor above the calibrated mat plane, unless
+ ``student_floor`` "observed" (v12; only written when not the default): the flat arm-frame floor). v12 visual
+ fix: ``v12_vis`` = the gripper look of the training views and the student's scene sha256 (only when on)."""
+ rec = {}
+ if getattr(self, "il", None) is not None:
+ rec["img_lag"] = asdict(self.il)
+ if getattr(self, "tb", None) is not None:
+ rec.update(table_bias=self.tb.to_dict(), table_render=bool(self.tb_render))
+ if getattr(self.o, "student_floor", "true") != "true": # v12: the flat observed-frame floor
+ rec["student_floor"] = self.o.student_floor
+ if getattr(self.o, "plate_mm", ()):
+ rec["plate_mm"] = [float(v) for v in self.o.plate_mm]
+ out = {"v8_online": rec} if rec else {}
+ if getattr(self.o, "gripper_look", None): # v12: the training look (its own key; the robot ignores it)
+ out["v12_vis"] = dict(gripper_look=dict(self.o.gripper_look),
+ scene_sha256=getattr(self.st.cfg, "scene_sha256", ""))
+ return out
+
+ def log_extra(self):
+ """Columns of the online log for the robot options that are on (none: {} = the old columns)."""
+ out = {}
+ if self.env.dyn is not None:
+ out.update(self.env.dyn.summary())
+ if self.env.pause is not None:
+ out.update(self.env.pause.summary())
+ if self.qd_hist is not None:
+ out["qd_robot"] = round(float(self.qd_rob.float().mean()), 3)
+ if self.tb is not None: # the worlds' current table planes: share with one, mean drop at x_ref; the map's
+ on = self.tb_on # statistics since the last row (``tb_note``)
+ drop = -(self.tb_plane[:, 0] + self.tb_plane[:, 1] * float(self.tb.x_ref_m))
+ out["tb_on"] = round(float(on.float().mean()), 3)
+ out["tb_drop_mm"] = round(float(drop[on].mean()) * 1e3, 2) if bool(on.any()) else float("nan")
+ r, c = self.tb_res.tolist(), [int(v) for v in self.tb_cnt.tolist()]
+ out["tb_res_um"], out["tb_res_applied_um"] = round(r[0] * 1e6, 4), round(r[1] * 1e6, 4)
+ out["tb_bad_frame"] = round(c[0] / max(c[1], 1), 6)
+ out["tb_bad_applied"] = round(c[2] / max(c[3], 1), 6)
+ out["tb_skip"] = round(c[4] / max(c[5], 1), 6)
+ self.tb_res, self.tb_cnt = torch.zeros_like(self.tb_res), torch.zeros_like(self.tb_cnt)
+ if self.env.goal_jump is not None:
+ out.update(self.env.goal_jump.summary())
+ if self.img_hist: # in-episode image pairs since the last log row: the share with the same light etc.
+ n = self.stats.get("img_pairs", 0)
+ out["img_pair_same"] = round(self.stats.get("img_pairs_same", 0) / n, 4) if n else float("nan")
+ if self.il is not None: # the image lags of this decision (ms) and the samples left out since the last row
+ ms = self.lag_x.double() * self.il.step_ms
+ out.update(img_lag_ms=round(float(ms.mean()), 2), img_lag_ms_max=round(float(ms.max()), 2),
+ img_lag_stale=int(self.stale))
+ self.stale = 0
+ return out
+
+ def _draw(self, idx):
+ d = self.views.draw(len(idx))
+ nom = self.nominal[idx]
+ if self.views.real is not None:
+ d = self.views.merge_nominal(d, nom)
+ if self.dr is None:
+ self.dr = d
+ else:
+ for k in self.dr:
+ self.dr[k][idx] = d[k]
+ return
+ d["colors"] = torch.where(nom[:, None, None], self.views.base.expand_as(d["colors"]), d["colors"])
+ d["cam_dpos"] = torch.where(nom[:, None, None], torch.zeros_like(d["cam_dpos"]), d["cam_dpos"])
+ d["cam_drot"] = torch.where(nom[:, None, None], torch.zeros_like(d["cam_drot"]), d["cam_drot"])
+ if self.dr is None:
+ self.dr = d
+ else:
+ for k in self.dr:
+ self.dr[k][idx] = d[k]
+
+ @torch.no_grad()
+ def act(self):
+ """One decision of every world -> timing dict."""
+ env, st, o = self.env, self.st, self.o
+ T = {}
+ t0 = time.time()
+ if env.obs is None:
+ env.reset()
+ self._draw(torch.arange(env.B, device=self.dev))
+ self._lag_reset(torch.arange(env.B, device=self.dev))
+ self._bias_reset(torch.arange(env.B, device=self.dev))
+ self._qd_reset(torch.arange(env.B, device=self.dev))
+ ws, obs = env.ws, env.obs
+ q = ws.q.to(torch.float64)
+ if o.relabel_cmd_speed and env.dyn is not None and env.u_exe is not None and bool(env.dyn.on.any()):
+ v = ((env.u_exe[:, -1] - env.u_exe[:, -2]) / JE.CONTROL_DT).to(obs.dtype) # commanded speed [B, 6]
+ obs = obs.clone()
+ m = relabel_mask(o, env)
+ obs[:, 6:12] = torch.where(m[:, None], v, obs[:, 6:12]) # obs layout: q, qd, ...
+ a = self.jt.act(obs).to(torch.float64)
+ lab = env.codec.targets(a, q) # [N, 5, 6] the label
+ if self.roll_cap is not None: # the roll cap: capped labels
+ lab = env.cap_roll(lab)
+ noise = (self.noisy.double()[:, None] * o.noise) * self.jt.std.to(a)[None] * \
+ torch.randn(a.shape, device=self.dev, generator=self.gen, dtype=a.dtype)
+ tg = env.codec.targets(a + noise, q)
+ gp = torch.cat((env.task.goal_xy, env.task.goal_yaw[:, None]), -1).float()
+ ok = torch.isfinite(q).all(-1) & torch.isfinite(ws.cube_pos).all(-1) & torch.isfinite(ws.cube_quat).all(-1)
+ qf = torch.where(ok[:, None], q, torch.zeros_like(q)).float()
+ cp = torch.where(ok[:, None], ws.cube_pos, torch.tensor([0.2, 0.0, 0.015], **dict(
+ dtype=ws.cube_pos.dtype, device=self.dev))).float()
+ cq = torch.where(ok[:, None], ws.cube_quat, torch.tensor([1.0, 0.0, 0.0, 0.0], dtype=ws.cube_quat.dtype,
+ device=self.dev)).float()
+ T["jt"] = time.time() - t0
+ t1 = time.time()
+ light = bool(torch.rand(1, device=self.dev, generator=self.gen) >= o.default_light_p)
+ kw = {}
+ if self.redraw_gen is not None: # light_redraw_p < 1: the last decision's per-call state stays unless redrawn
+ if self.light_prev is not None and bool(torch.rand(1, generator=self.redraw_gen) >= o.light_redraw_p):
+ light, kw = self.light_prev, dict(keep=True)
+ self.light_prev = light
+ icp, igp, cur_goal = cp, gp, None
+ lagged = None
+ if self.il is not None: # img_lag: per decision lags in ms, interpolated states
+ self._lag_redraw()
+ lagged = self._lag_states(gp)
+ TF = None
+ if self.tb is not None: # the table plane's observed frame: reading, qdot, labels, last executed targets
+ ttb = time.time() # (before the render: table_render draws the arm at the reading; own timing)
+ qd = self.qd_input(ws.qd.float().nan_to_num())
+ iq_ = None # the image state(s) to map (table_render with image lag)
+ if self.tb_render and lagged is not None: # img_lag: one state per lag column (camera-major rows)
+ iq_ = torch.cat([s_[0] for s_ in lagged])
+ elif self.tb_render and self.lag_hist is not None:
+ iq_ = self.lag_hist.get(self.lagk)[0]
+ TF = self.table_frame(torch.where(ok[:, None], q, torch.zeros_like(q)), qf, qd, lab,
+ env.u_exe if (self.n_cmd or self.LC) and env.u_exe is not None else None, iq_,
+ ~self.fresh) # (an auto-reset world's u_exe is the last episode's: unused)
+ torch.cuda.synchronize() if self.dev.type == "cuda" else None
+ T["table"] = time.time() - ttb
+ rkw = {} # v8 render inputs (only when on: other views keep their old call)
+ if self.tb_render: # consistent images: the world on each world's plane, the arm at the reading
+ rkw["plane"] = self.tb_plane
+ if getattr(self.views, "plate_on", False): # the plate lift spares a cube the jaws hold
+ F = env.task.F
+ held = F["held"].to(self.dev) if F is not None else torch.zeros_like(self.fresh)
+ rkw["held"] = held & ~self.fresh # (F of an auto-reset world is the last episode's)
+ if lagged is not None: # img_lag (+ table_render: the arm at Phi of each state)
+ iqs = TF["iq"].split(len(qf)) if self.tb_render else None
+ rgb, icp, igp, cur_goal = self._render_lagged(gp, light, kw, lagged, iqs, rkw)
+ elif self.lag_hist is not None: # the images lag; q, qd, the labels stay current
+ iq, icp, icq = self.lag_hist.get(self.lagk)
+ rgb = self.views.render(TF["iq"] if self.tb_render else iq, icp, icq, gp, dr=self.dr, light=light, **kw,
+ **rkw)
+ else:
+ rgb = self.views.render(TF["q"] if self.tb_render else qf, cp, cq, gp, dr=self.dr, light=light, **kw,
+ **rkw)
+ cid = getattr(self.views, "call_id", None)
+ same_call = cid is None or self.call_id is None or cid == self.call_id # the last decision's light etc.
+ self.call_id = cid
+ torch.cuda.synchronize() if self.dev.type == "cuda" else None
+ T["render"] = time.time() - t1 - T.get("table", 0.0)
+ t2 = time.time()
+ stud = ~self.teacher if self.it >= o.warm_teacher_only else torch.zeros_like(self.teacher)
+ if TF is None:
+ qd = self.qd_input(ws.qd.float().nan_to_num()) # robot-like qdot in the qd_rob worlds
+ qin = qf + self.qb if self.qb_h is not None else qf # q input offset (q_bias)
+ if TF is not None: # (table frame)
+ qin, qd = qin + TF["b"], TF["qd"]
+ now = torch.cat((qin, qd), -1) # [N, 12]
+ fr = self.fresh
+ if self.H:
+ self.rhist[fr] = now[fr][:, None, :].expand(-1, self.H, -1)
+ robot_all = torch.cat((now, self.rhist.reshape(len(now), -1)), -1)
+ else:
+ robot_all = now
+ if self.n_cmd: # the last decision's executed targets (student or JT) - the measured q now; 0 at a start
+ if env.u_exe is None:
+ cmd = torch.zeros(len(now), self.n_cmd, device=self.dev)
+ else:
+ ue, qr = (env.u_exe, qf) if TF is None else (TF["u_exe"], TF["q"]) # (table frame)
+ cmd = (ue.to(self.dev, torch.float32) - qr[:, None, :]).nan_to_num().reshape(len(now), -1)
+ cmd = torch.where(fr[:, None], torch.zeros_like(cmd), cmd)
+ robot_all = torch.cat((robot_all, cmd), -1)
+ if self.LC: # the last executed command (every slot; 0 at the start, non-finite worlds;
+ # after cmd)
+ lc = torch.where(ok[:, None], self.lastcmd_input(q) if TF is None else
+ self.lastcmd_input(TF["q64"], TF["u_exe"]),
+ torch.zeros(1, 12, dtype=torch.float64, device=self.dev))
+ robot_all = torch.cat((robot_all, lc.to(robot_all)), -1)
+ self.lc_fresh = torch.zeros_like(self.lc_fresh)
+ prgb = None
+ if self.img_hist: # the last decision's images of the same episode (an episode start, or a new per-call render
+ own = fr if same_call else torch.ones_like(fr) # state: the current ones)
+ prgb = rgb if self.prev_rgb is None else torch.where(own[:, None, None, None, None], rgb, self.prev_rgb)
+ if self.prev_rgb is not None:
+ self.stats["img_pairs"] += int((~fr).sum())
+ self.stats["img_pairs_same"] += int((~fr).sum()) if same_call else 0
+ self.last = dict(robot=robot_all, fresh=fr.clone(), prev_rgb=prgb, rgb=rgb, goal_pose=gp, aux_cp=icp)
+ if TF is not None:
+ self.last["tb"] = TF
+ if self.il is not None:
+ self.last.update(img_lag=self.lag_x.clone(), img_goal=igp, cur_goal=cur_goal)
+ if bool(stud.any()):
+ si = stud.nonzero().flatten()
+ st.eval()
+ img = to_input(rgb[si], fx=self.views.fx)
+ pimg = to_input(prgb[si], fx=self.views.fx) if prgb is not None else None
+ robot = robot_all[si]
+ out = []
+ for s in range(0, len(si), 256):
+ with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=st.cfg.amp):
+ p_ = st.predict(img[s:s + 256], robot[s:s + 256]) if pimg is None else \
+ st.predict(img[s:s + 256], robot[s:s + 256], pimg[s:s + 256])
+ out.append(denormalise(st, p_))
+ st.train()
+ u = (qf if TF is None else TF["q"])[si][:, None, :] + torch.cat(out) # relative to its reading
+ K, n = u.shape[1], st.cfg.n_exec
+ jj = torch.arange(n, device=self.dev)
+ kk = (jj + st.cfg.jaw_lead).clamp_max(K - 1)
+ tg[si] = torch.cat((u[:, jj, :5], u[:, kk, 5:]), -1).double()
+ if TF is not None: # observed-frame targets -> applied (true) targets
+ tg[si] = self.table_applied(tg[si], si, TF["b64"][si])
+ T["student"] = time.time() - t2
+ # samples: this decision's label completes the previous sample of every world that did not reset
+ live = ok
+ pv = self.prev_slot
+ has = (pv >= 0) & live
+ if TF is not None: # table frame: only exact samples / labels (``table_frame``: skip, lab_bad)
+ has = has & ~TF["lab_bad"]
+ live = ok & ~TF["skip"]
+ if env.goal_jump is not None: # the goal moved since the previous sample: no second-half label for it
+ has = has & ~env.goal_jump.just
+ lab_b, q_b = (lab, qf) if TF is None else (TF["lab"], TF["q"]) # (table frame: Phi(lab), Phi(q))
+ if bool(has.any()):
+ self.buf.lab2[pv[has]] = lab_b[has].float()
+ self.buf.valid2[pv[has]] = True
+ if cur_goal is not None and not bool(cur_goal.all()): # img_lag: the images still show the goal before a
+ live = live & cur_goal # jump, the label is for the new one: no sample
+ self.stale += int((ok & ~cur_goal).sum())
+ idx = live.nonzero().flatten()
+ if self.tb_render: # the drawn cube: sheared by the plane height under it (``table_render``)
+ from nedm.so101_policy import table_bias as TBI
+ hz = torch.where(self.tb_on, TBI.height(self.tb_plane, icp[:, :2].double()), 0.0).to(icp.dtype)
+ icp = icp + torch.cat((torch.zeros_like(icp[:, :2]), hz[:, None]), -1)
+ aux = aux_targets(igp[idx], icp[idx])
+ plink = None
+ if self.img_hist: # the link to the previous sample (cut when the per-call render state changed)
+ plink = pv[idx] if same_call else torch.full_like(pv[idx], -1)
+ slots = self.buf.add(rgb[idx], q_b[idx], robot_all[idx], lab_b[idx], aux, ~self.nominal[idx], prev=plink)
+ if self.H:
+ self.rhist = torch.cat((now[:, None, :], self.rhist[:, :-1]), 1)
+ self.fresh = torch.zeros_like(self.fresh)
+ if self.img_hist:
+ self.prev_rgb = rgb
+ self.prev_slot = torch.full_like(self.prev_slot, -1)
+ self.prev_slot[idx] = slots
+ self.samples += len(idx)
+ t3 = time.time()
+ hook = self._step_hook if self.qd_hist is not None else self._lag_hook if self.lag_hist is not None else None
+ _, _, done, ex = env.step(targets=tg, step_hook=hook)
+ T["env"] = time.time() - t3
+ if bool(done.any()):
+ di = done.nonzero().flatten()
+ self.prev_slot[di] = -1 # the next decision is a new episode
+ self.fresh[di] = True
+ self.lc_fresh[di] = True
+ ep = ex["episode"]
+ le = ep["lenient"][di]
+ ts = self.teacher[di]
+ self.stats["ep_teacher"] += int(ts.sum())
+ self.stats["len_teacher"] += int((le & ts).sum())
+ self.stats["ep_student"] += int((~ts).sum())
+ self.stats["len_student"] += int((le & ~ts).sum())
+ if "roll_cmd_max" in ep:
+ ro = ep["roll_cmd_max"][di] > self.roll_cap + 1e-9
+ self.stats["roll_over_teacher"] += int((ro & ts).sum())
+ self.stats["roll_over_student"] += int((ro & ~ts).sum())
+ if "goal_jumps" in ep:
+ jm = ep["goal_jumps"][di] > 0
+ self.stats["ep_jump_teacher"] += int((jm & ts).sum())
+ self.stats["len_jump_teacher"] += int((jm & le & ts).sum())
+ self.stats["ep_jump_student"] += int((jm & ~ts).sum())
+ self.stats["len_jump_student"] += int((jm & le & ~ts).sum())
+ self._draw(di)
+ self._lag_reset(di)
+ self._bias_reset(di)
+ self._qd_reset(di)
+ return T
+
+ def qd_noise_scale(self, n):
+ """[n] per-sample factor on the loss-side qdot noise (``OnlineConfig.qd_noise_zero_p``): U(0, 1), exactly 0
+ for that share; None = off (the old loss)."""
+ p = self.o.qd_noise_zero_p
+ if p is None:
+ return None
+ s = torch.rand(n, device=self.dev, generator=self.gen)
+ return torch.where(torch.rand(n, device=self.dev, generator=self.gen) < float(p), torch.zeros_like(s), s)
+
+ def train_steps(self):
+ st, o, b = self.st, self.o, self.st.cfg.batch
+ info_sum, n = {}, 0
+ for _ in range(int(o.steps_per_iter)):
+ i = self.buf.sample(b, self.gen)
+ rgb = self.buf.rgb[i]
+ aug = self.buf.aug[i]
+ fx = self.views.fx
+ if self.img_hist: # the previous images get the SAME per-image augmentation draws as the current
+ gs = self.gen.get_state()
+ img = to_input(rgb, self.drc, self.gen, fx=fx)
+ img = torch.where(aug[:, None, None, None, None], img, to_input(rgb, fx=fx, fx_random=False))
+ pimg = None
+ if self.img_hist:
+ ge = self.gen.get_state()
+ prgb, pok = self.buf.prev_rgb(i)
+ info_sum["prev_ok"] = info_sum.get("prev_ok", 0.0) + float(pok.float().mean())
+ self.gen.set_state(gs)
+ pimg = to_input(prgb, self.drc, self.gen, fx=fx)
+ pimg = torch.where(aug[:, None, None, None, None], pimg, to_input(prgb, fx=fx, fx_random=False))
+ self.gen.set_state(ge)
+ q = self.buf.q[i]
+ tgt = torch.cat((self.buf.lab1[i], self.buf.lab2[i]), 1)[:, :st.cfg.chunk] - q[:, None, :]
+ valid = torch.cat((torch.ones(len(i), JE.STEPS, dtype=torch.bool, device=self.dev),
+ self.buf.valid2[i][:, None].expand(-1, JE.STEPS)), 1)[:, :st.cfg.chunk]
+ robot = self.buf.robot[i]
+ if o.qd_in_zero_p > 0 or o.qd_in_lo != 1.0 or o.qd_in_hi != 1.0: # qdot input scale (training only)
+ k = o.qd_in_lo + (o.qd_in_hi - o.qd_in_lo) * torch.rand(len(i), device=self.dev, generator=self.gen)
+ k = torch.where(torch.rand(len(i), device=self.dev, generator=self.gen) < o.qd_in_zero_p,
+ torch.zeros_like(k), k).to(robot.dtype)
+ robot = robot.clone()
+ robot[:, 6:12] = robot[:, 6:12] * k[:, None]
+ aux_n = (self.buf.aux[i] - st.aux_mean) / st.aux_std
+ qs = self.qd_noise_scale(len(i))
+ with torch.autocast(self.dev.type, dtype=torch.bfloat16, enabled=st.cfg.amp):
+ loss, info = st.loss(img, robot, normalise(st, tgt), valid, aux_n, qd_scale=qs, prev=pimg)
+ self.opt.zero_grad(set_to_none=True)
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(st.parameters(), st.cfg.grad_clip)
+ self.opt.step()
+ for k, v in dict(loss=float(loss.detach()), **info).items():
+ info_sum[k] = info_sum.get(k, 0.0) + v
+ n += 1
+ return {k: v / max(n, 1) for k, v in info_sum.items()}
diff --git a/so101_pick_place/code/src/nedm/so101_policy/world.py b/so101_pick_place/code/src/nedm/so101_policy/world.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e3993f0050242d127a9a481acb8cba8395090cb
--- /dev/null
+++ b/so101_pick_place/code/src/nedm/so101_policy/world.py
@@ -0,0 +1,48 @@
+"""The state contract shared by the NRD world and the MuJoCo worlds of the SO101 + cube policy study.
+
+Both worlds take 6 absolute joint targets per world (5 arm joints + jaw, rad, held for one 20 ms control step) and
+return a ``WorldState``. Every field has the definition of the grasp NRD data (``nedm.contact_nrd.collect.so101_grasp``):
+rates are 20 ms step averages, the cube velocity and spin are in the world frame. The cube orientation is the TRUE
+one, not the NRD's canonical relabelling of the cube's symmetry.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, fields
+
+import torch
+
+CONTROL_DT = 0.02
+JOINTS = 6
+CONTACT_PAIRS = ("fixed_jaw_cube", "moving_jaw_cube", "cube_table")
+
+
+@dataclass
+class WorldState:
+ q: torch.Tensor # [B, 6] joint angles (rad); index 5 = jaw
+ qd: torch.Tensor # [B, 6] 20 ms step-average joint rates (rad/s)
+ cube_pos: torch.Tensor # [B, 3] cube centre, world (m); table top at z = 0
+ cube_quat: torch.Tensor # [B, 4] true cube orientation, w x y z
+ cube_v: torch.Tensor # [B, 3] cube velocity, world (m/s), data definition
+ cube_w: torch.Tensor # [B, 3] cube spin, world (rad/s), data definition
+ contact: torch.Tensor # [B, 3] bool, order CONTACT_PAIRS
+ arm_table: torch.Tensor # [B] bool, arm touches the table (MuJoCo: real contact; NRD: lowest-point guard)
+ invalid: torch.Tensor # [B] bool, any other end condition (non-finite state, cube off table, ...)
+
+ def index(self, idx) -> "WorldState":
+ return WorldState(**{f.name: getattr(self, f.name)[idx] for f in fields(self)})
+
+ def to(self, device=None, dtype=None) -> "WorldState":
+ out = {}
+ for f in fields(self):
+ t = getattr(self, f.name)
+ out[f.name] = t.to(device=device, dtype=dtype) if (dtype is not None and t.is_floating_point()) else t.to(device)
+ return WorldState(**out)
+
+ @property
+ def batch(self) -> int:
+ return self.q.shape[0]
+
+ @staticmethod
+ def cat(states: list["WorldState"]) -> "WorldState":
+ return WorldState(**{f.name: torch.cat([getattr(s, f.name) for s in states]) for f in fields(WorldState)})