go2_sand_finetune: data, NRD, policy V2n s81, code and evaluation records
Browse filesGo2 sand finetune study (follow-on work, not part of the NeDM paper): data -> NRD -> policy V2n s81. 832 files, 5460740438 bytes. release_manifest.json follows in the next commit.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- go2_sand_finetune/README.mdAdded+160
- go2_sand_finetune/code/REPRODUCE.mdAdded+199
- go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/episode.pyAdded+785
- go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/relief.pyAdded+386
- go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/run.pyAdded+349
- go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/swing_lift.pyAdded+161
- go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/cluster/train_amd.sbatchAdded+63
- go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/configs/fresh_lat_v2.jsonAdded+53
- go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/nrd_v3_train.pyAdded+571
- go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/samplers.pyAdded+326
- go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/stall_support.pyAdded+88
- go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/src/go2nrd/fixed_base/three_transformer.pyAdded+436
- go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/ppo_nrdv3_euler.sbatchAdded+46
- go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/recipes/overlay_nrdv3_ood.jsonAdded+9
- go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/recipes/v2.jsonAdded+71
- go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/eval/export_onnx.pyAdded+247
- go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/fixed_base/ppo_lateral_v3.pyAdded+166
- go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/env.pyAdded+898
- go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/lateral_v3.pyAdded+529
- go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/ppo.pyAdded+129
- go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/runner.pyAdded+286
- go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/helpers_src/go2nrd/eval/parity.pyAdded+134
- go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/nrd_v3/train/export_loader.pyAdded+102
- go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_nrdv3/build_ood_reference.pyAdded+169
- go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_nrdv3/export_nrdv3.pyAdded+142
- go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_v3/build_start_groups.pyAdded+92
- go2_sand_finetune/code/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75.tar.gzAdded+3
- go2_sand_finetune/code/collector_crm_code_v1_d8ef2fc8d989.tar.gzAdded+3
- go2_sand_finetune/code/collector_rigid_mjlab_nrd_3a9155b.tar.gzAdded+3
- go2_sand_finetune/code/eval_capsule_runtime_eval_v1_30417413.tar.gzAdded+3
- go2_sand_finetune/code/eval_chrono_suite_v1_p2nrd_699bc991a430.tar.gzAdded+3
- go2_sand_finetune/code/eval_chrono_suite_v2_q1_d407c6940ef1.tar.gzAdded+3
- go2_sand_finetune/code/go2nrd_worktree_snapshot.tar.gzAdded+3
- go2_sand_finetune/code/nrd_capsule_c0e07a22e57434cd.tar.gzAdded+3
- go2_sand_finetune/code/ppo_snapshot_8e08e2544f0d.tar.gzAdded+3
- go2_sand_finetune/code/source_manifest.jsonAdded
- go2_sand_finetune/code/study_scripts_lateral_stuck_20261108.tar.gzAdded+3
- go2_sand_finetune/data/EXPORT_NAMES.jsonAdded+268
- go2_sand_finetune/data/aux/rigid_test_s0000.npzAdded+3
- go2_sand_finetune/data/crm_prod/crm_gates.jsonAdded
- go2_sand_finetune/data/crm_prod/crm_gates_brief.jsonAdded+230
- go2_sand_finetune/data/crm_prod/export.logAdded+44
- go2_sand_finetune/data/crm_prod/manifest.jsonAdded
- go2_sand_finetune/data/crm_prod/system.jsonAdded+706
- go2_sand_finetune/data/crm_prod/unified_data.npzAdded+3
- go2_sand_finetune/data/crm_prod/validate_report.jsonAdded+471
- go2_sand_finetune/data/lateral_crm_v2_cuda/export.logAdded+44
- go2_sand_finetune/data/lateral_crm_v2_cuda/manifest.jsonAdded
- go2_sand_finetune/data/lateral_crm_v2_cuda/system.jsonAdded+734
- go2_sand_finetune/data/lateral_crm_v2_cuda/unified_data.npzAdded+3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160# Go2 sand finetune: data, NRD and the policy V2n s81
This folder holds the full pipeline of one study: data → NRD → policy. A Unitree Go2 velocity policy stalled when itwalked sideways on sand. PPO fine-tuned it only inside a neural reduced dynamics model (NRD) of the Go2 on ProjectChrono CRM sand and on rigid ground. The released policy is **V2n s81** (deploy ONNX SHA-256`1419d9722698c23a04b8805dd15f6eb25710e1f11860ffbad0cb1a63159674e9`). This is follow-on work to the NeDM paper, notpart of it. The results, the limits and the pinned manifest are in[`go2_sand_finetune/` of the NeDM code repository](https://github.com/uwsbel/NeDM/tree/main/go2_sand_finetune).
## Status
| Item | Status ||---|---|| Held-out Chrono sand suite | Stuck-time ratio 0.214 of the base policy (9 of 9 blocks better). Label **NOT_CONFIRMED**: falls (5 of 72 realistic episodes, base policy 0), wrong-way motion on soft sand (8 of 16 segments toward -y, base policy 0), power 1.66 times the base value || MuJoCo rigid ground, 120 development paths | Tracking loss ratio 0.854 (95 % range 0.836 to 0.874), 0 falls || C++ deploy stack in MuJoCo, flat ground | Both test profiles completed, 0 falls (one run each) || Real robot | User report only (2026-11-10 to 2026-11-11, sand and rigid floor): it performed well, with a higher foot lift and stronger lateral motion, and a small jitter at some stops after lateral motion. No robot log, no video, no record of the ONNX that ran. See `reports/hardware_note.md` || Deploy package | [`legged_rl_deploy` PR #3](https://github.com/harryzhang1018/legged_rl_deploy/pull/3), package `policies/go2/nrd_finetune_lateral_v2n_seed81/velocity/` || License | BSD-3-Clause, the same as the rest of this dataset |
All numbers in this table are simulation results. "Stuck time" is lateral hold time in 1 s windows where the lateral speedis less than 0.4 of the command. A fall or an early stop counts the rest of the hold as stuck.
## Layout
Sizes are approximate. `release_manifest.json` gives the exact size and SHA-256 of each file.
| Path under `go2_sand_finetune/` | Contents | Size ||---|---|---|| `README.md` | This study card | - || `release_manifest.json` | Size and SHA-256 of each file in this folder, the lineage hashes and `hf_revision`: the Hub commit that added these files. The manifest comes in the next commit | - || `data/rigid_prod_v2/` | MuJoCo Warp (mjlab) rigid-plane episodes of the base policy: 10,443 pieces, 9.06 h. `unified_data.npz`, `system.json`, `manifest.json`, validation report | 2.9 GB || `data/crm_prod/` | Chrono CRM episodes of the base policy: 2,000 episodes, 3,489 pieces, 5.94 h. Same files, plus gate reports | 1.1 GB || `data/lateral_crm_v2_hip/` | New lateral Chrono CRM episodes of the base policy, AMD HIP build: 400 episodes, 730 pieces, 1.84 h | 0.27 GB || `data/lateral_crm_v2_cuda/` | The same plan, Euler CUDA build: 80 episodes, 149 pieces, 0.38 h | 54 MB || `data/lateral_crm_v2_test_hip/` | Held-out lateral test: 60 episodes, 105 pieces, 0.27 h. Never used for training or normalization | 38 MB || `data/lateral_crm_v2_slim_diag/` | Diagnostics of each episode of the three lateral exports: feet, center of mass, relief, surface maps, swing-lift signal | 0.29 GB || `data/splits/` | The parent split manifest and the lateral split manifest that the NRD used | 14 MB || `data/plans/` | Collection plans and plan arrays (commands, injections) | 0.22 GB || `data/reports/` | Collection, export and validation reports | 15 MB || `data/EXPORT_NAMES.json` | Map from these folder names to the original export names | - || `data/aux/rigid_test_s0000.npz` | Raw rigid test shard of the base policy. The ONNX export and parity scripts read their verification rows from it | 90 MB || `teacher/` | The base policy: PPO checkpoint `model_10000.pt`, deploy ONNX and configs, training parameters, job record | 6.6 MB || `nrd/fresh_b/` | The NRD: last checkpoint, resume state, stage-end checkpoints, loader export, training logs, validations, lineage, cluster job records | 89 MB || `nrd/gates/` | Pre-registered NRD gates, the waiver and the gate results. The gate scripts are in `code/` | 14 MB || `nrd/reports/` | NRD training, gate, replication and verification reports | 1.3 MB || `policy/v2n_s81/run/` | The PPO run: config, recipe, start record, metrics, train log, checkpoints `model_0`, `model_150`, `model_299`, the run's own ONNX, audit and job records | 19 MB (with `deploy/`) || `policy/v2n_s81/deploy/` | The deploy re-export (ONNX, config, export record, parity) and a copy of the `legged_rl_deploy` package (README, provenance) | (see above) || `policy/inputs/` | PPO inputs: base config, recipe, overlay, start groups, OOD reference | 7.5 MB || `eval/` | Chrono suites (selection, held-out, fresh), selection rules and results, MuJoCo rigid check, C++ deploy check, torque-clip check, mechanism analysis, fall audit | 51 MB || `videos/crm_showcase/` | Chrono side-by-side videos of the base policy and V2n s81 on two selected sand cases, and the displacement plot | 34 MB || `videos/mujoco_eval/` | Replays of the C++ deploy runs on rigid ground (base policy, V2n s81, an ensemble policy) | 60 MB || `code/` | Source archives of each step, `source_manifest.json`, `REPRODUCE.md`, browsable key scripts | 0.15 GB || `reports/` | Study report, durable state, verification reports, receipts, hardware note | 2.8 MB |
Total approximately 5.5 GB, of which `data/` is 5.0 GB.
## Lineage
| Step | File in this folder | SHA-256 (first 8) ||---|---|---|| Base policy checkpoint / ONNX | `teacher/model_10000.pt` / `teacher/deploy/policy.onnx` | `7ee303f9` / `c58a3494` || Rigid data | `data/rigid_prod_v2/unified_data.npz` | `b02c0c50` || CRM data | `data/crm_prod/unified_data.npz` | `35b73ce2` || Lateral data, HIP / CUDA | `data/lateral_crm_v2_hip/unified_data.npz` / `data/lateral_crm_v2_cuda/unified_data.npz` | `2e78115a` / `f1079976` || Held-out lateral test | `data/lateral_crm_v2_test_hip/unified_data.npz` | `e1f18d48` || Split manifests, parent / lateral | `data/splits/splits_fixed_base_20261102.json` / `data/splits/splits_lateral_v2.json` | `f1d264dd` / `9ba6dce9` || NRD last checkpoint / loader export | `nrd/fresh_b/last.pt` / `nrd/fresh_b/export/nrd_v3_FRESH-b_loader.pt` | `b41561c3` / `501c9b8d` || PPO checkpoint | `policy/v2n_s81/run/model_299.pt` | `cdb54fb5` || Deploy ONNX | `policy/v2n_s81/deploy/legged_rl_deploy_package/policy.onnx` | `1419d972` |
- The base policy made all NRD training data. No episode of a fine-tuned policy is in the NRD data.- The NRD trained from random weights in one AMD MI350X job (509956, 2.39 h). PPO ran in one Euler RTX A4500 job (114010, 601 s of training).- The deploy ONNX is a CPU re-export of `model_299.pt`. The run's own `policy.onnx` (`6e82a553`) has other bytes.
## What the files contain
- `unified_data.npz` (uncompressed NumPy): `robot` [N, 1001, 37] (base position, quaternion wxyz, 12 joint angles, base velocity, base angular velocity, 12 joint rates), `action` [N, 1001, 12] (joint position targets), `contacts` [N, 1000, 4] (four feet), `command` [N, 1001, 3], `ground_features` [N, 3], `soil` [N, 4] (cohesion, friction, density, Young's modulus), `lengths`, `splits` and more arrays. Records are 10 ms apart. The NRD step is 20 ms. `system.json` gives the channels, families and contact rule. `manifest.json` gives the raw shards with their SHA-256, the code hashes and the counts.- The NRD loader export is a PyTorch checkpoint (`model_config`, `system`, `masks`, `model_state_dict`). It has three Transformer networks (core, collision, contact; 4 layers, width 128, 4 heads, feed-forward 512) and a ground code of 3 features. Load it with the `go2nrd` loader of the code archives. The raw `last.pt` does not load in that loader.- `model_299.pt` is an RSL-RL checkpoint (`actor_state_dict`, `critic_state_dict`, `optimizer_state_dict`). The deploy ONNX takes `obs` [1, 47] and gives `actions` [1, 12]. The observation normalization is in the graph.
## Download and examine the files
`release_manifest.json` gives the size and the SHA-256 of each file. Its `hf_revision` is the Hub commit that addedthe files. This example reads the manifest, downloads the policy and the NRD at `hf_revision`, then examines eachdownloaded file:
```pythonimport hashlib, jsonfrom pathlib import Pathfrom huggingface_hub import hf_hub_download, snapshot_download
REPO = "harryzhang1018/NeDM"MANIFEST_REV = "main" # to pin the manifest, use hub_manifest.hf_revision of the NeDM go2_sand_finetune pin filemanifest = json.loads(Path(hf_hub_download(REPO, "go2_sand_finetune/release_manifest.json", repo_type="dataset", revision=MANIFEST_REV)).read_text())REV = manifest["hf_revision"] # the commit that added the files in "files"root = Path(snapshot_download(REPO, repo_type="dataset", revision=REV, allow_patterns=["go2_sand_finetune/policy/*", "go2_sand_finetune/nrd/fresh_b/*"]))files = manifest["files"]if isinstance(files, list): files = {f["repo_path"]: f for f in files}for path, f in sorted(files.items()): p = root / path if not p.exists(): continue h = hashlib.sha256() with p.open("rb") as fh: for block in iter(lambda: fh.read(1 << 20), b""): h.update(block) assert p.stat().st_size == f["bytes"] and h.hexdigest() == f["sha256"], path print("ok", path)```
- Add `"go2_sand_finetune/data/*"` to `allow_patterns` for the 5.0 GB of episodes.- You cannot load the files with `datasets.load_dataset`. Read them with NumPy, PyTorch or ONNX Runtime.- `code/REPRODUCE.md` tells how to rebuild each step from the source archives.
## Paths in the files
Except the generated files (code archives, log archives, the compressed training log of the base policy, job records,file inventories and release documents), the files are byte-exact copies of the study files. They keepthe machine-local and cluster paths of the study, for example `/home/harry/...` (workstation), `/work1/dannegrut/harry/...` (AMD cluster) and `/srv/home/hzhang699/...`(Euler cluster). These paths are records of the original runs. Change them to your own paths before you run the code.The split manifests and the run configs name the data folders by their original export names, for example`lateral_stuck_20261108_crm_v2_hip`. `data/EXPORT_NAMES.json` maps these names to the folder names of this release.
## Known limitations
- **Simulation results only.** The real-robot test is a user report. Nothing records the number of trials or the file that ran.- **NOT_CONFIRMED.** V2n s81 did not pass the held-out gates for falls, soft-sand wrong-way motion and power. The study released it only as an experimental candidate.- **NRD gates.** The NRD missed 2 rigid accuracy rules. A written waiver, made during the study, let PPO use it.- **Seed dependence.** Only 1 of 4 NRD seeds of the same recipe met the main NRD gate. NRD seed 62 is the best seed, not a typical seed.- **Falls are not in the NRD.** The NRD predicts almost no falls. All 5 held-out falls were on medium uneven sand.- **Study soils.** The soil levels are study levels, not measured sand. Only the feet and calves of the Chrono robot touch the particles.- **Statistical reproduction.** Chrono CRM is not bit-deterministic on MI210. NRD training is not bitwise across GPU types. PPO set no determinism flags. The Chrono builds are not in this folder.- **Development data reuse.** The selection suite and the 120 rigid paths guided choices during the study.
## License and citation
BSD-3-Clause, the same as the rest of this dataset and the NeDM code. Upstream projects keep their own licenses(`unitree_rl_mjlab`: Apache License 2.0; the Unitree Go2 model files and the `legged_rl_deploy` code in the archives: theirupstream licenses). The study has no publication yet: please cite the NeDM paper and name thedataset revision you used (`hf_revision` in `release_manifest.json`).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199# Reproduce the Go2 sand lateral fine-tune (data -> NRD -> policy V2n s81)
This guide gives the stages that made the policy V2n s81.The real robot ran this policy as ONNX `1419d9722698c23a04b8805dd15f6eb25710e1f11860ffbad0cb1a63159674e9`.Each stage names its entry point, its arguments, its archive and its environment.The archive sha256 values and the per-file sha256 values are in `source_manifest.json`.
Important: a re-run gives a statistically similar result, not the same bytes.Use the archived artifacts (data exports, NRD loader, model_299.pt, ONNX) as the reference.Section 6 tells what is not bitwise reproducible.
## 1. Archives in `code/`
| Archive | Stage | Code digest | How the digest was checked ||---|---|---|---|| `collector_rigid_mjlab_nrd_3a9155b.tar.gz` | rigid_prod collection (MuJoCo Warp) | nrd commit `3a9155b` | The 7 collector file hashes in `rigid_prod_v2/manifest.json` equal the files at this commit. || `collector_crm_code_v1_d8ef2fc8d989.tar.gz` | crm_prod collection and the export step of rigid_prod_v2 / crm_prod | `d8ef2fc8d989` | CODE_DIGEST and MD5SUMS recomputed. `code_sha256()` = `d6bd79f5` = the crm_prod shard metadata. || `collector_crm_code_lateral_stuck_20261108_v2_698933cdce75.tar.gz` | lateral v2 collection, export, QA (HIP and CUDA) | `698933cdce75` | CODE_DIGEST and MD5SUMS recomputed. `code_sha256()` = `682eb8c7` = the lateral shard metadata. || `nrd_capsule_c0e07a22e57434cd.tar.gz` | NRD FRESH-b training | `c0e07a22e57434cd` | `sha256sum -c FILES.sha256` passes. Digest = sha256(FILES.sha256)[:16]. || `ppo_snapshot_8e08e2544f0d.tar.gz` | PPO V2n s81, NRD loader runtime, deploy ONNX exporter | `8e08e2544f0d` | `sha256sum -c SOURCE_SHA256.txt` passes. Digest = sha256(SOURCE_SHA256.txt)[:12]. || `study_scripts_lateral_stuck_20261108.tar.gz` | plans, splits, loader export, gates, OOD reference, start groups, ONNX export, parity, evaluation, selection, packaging | none | File copy. `helpers_src/` holds `go2nrd/eval/export_onnx.py` (`5e418e4c`) and `go2nrd/eval/parity.py`. || `eval_capsule_runtime_eval_v1_30417413.tar.gz` | rigid dev120 judge (`go2nrd.fixed_base.rigid_judge`) | `30417413...` | SOURCE_SHA256.json verifies. Digest recomputed. || `eval_chrono_suite_v1_p2nrd_699bc991a430.tar.gz` | Chrono suite_v1 code staged for the selection runs (tag p2nrd) | `699bc991a430` | Staging digest recomputed (ONNX hashes from the remote listing). || `eval_chrono_suite_v2_q1_d407c6940ef1.tar.gz` | Chrono held-out suite_v2 code staged for the confirmation runs (tag q1) | `d407c6940ef1` | Staging digest recomputed. || `go2nrd_worktree_snapshot.tar.gz` | reference only: the go2nrd working tree on 2026-11-17 | HEAD `ea23bba` + uncommitted edits | Not a run snapshot. See `WORKTREE_STATE.txt` inside. |
The archives contain no git history.Each archive has one top folder with the archive name.`browse/<archive>/<path>` holds plain copies of the main entry points, taken from the archives.
## 2. Before you start
1. Unpack the archives into one work folder.2. The scripts contain absolute paths of the original machines. Replace them with your paths: - workstation `luffy`: `/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102` (go2nrd worktree), `/home/harry/go2_sand/nrd_data/export` (data exports), `/home/harry/go2_sand/legged_rl_deploy` (deploy repo, teacher package, `sim_eval`), `/home/harry/go2_sand/unitree_rl_mjlab` (teacher training). - AMD HPC Fund cluster: `/work1/dannegrut/harry/go2nrd` and `/work1/dannegrut/harry/lateral_stuck_20261108`. - Euler cluster: `/srv/home/hzhang699/go2nrd` and `/scratch/hzhang699/...`.3. The release renames the data folders. The code expects the original names. Make a data root with links:
| Release folder | Original folder name (use this name in the data root) | |---|---| | `data/rigid_prod_v2` | `rigid_prod_v2` | | `data/crm_prod` | `crm_prod` | | `data/lateral_crm_v2_hip` | `lateral_stuck_20261108_crm_v2_hip` | | `data/lateral_crm_v2_cuda` | `lateral_stuck_20261108_crm_v2_cuda` | | `data/lateral_crm_v2_test_hip` | `lateral_stuck_20261108_crm_v2_test_hip` (held out; the NRD driver refuses it) | | `data/lateral_crm_v2_slim_diag` | `lateral_stuck_20261108_crm_v2_slim_diag` |
4. There is no `pyproject.toml`. Each stage runs with `PYTHONPATH=<snapshot>/src`.5. The scripts check sha256 values of their inputs. A wrong file stops the script.
## 3. Stage table
| # | Stage | Entry point | Archive | Where it ran | Date (CST) ||---|---|---|---|---|---|| 0 | Base teacher | unitree_rl_mjlab `Unitree-Go2-Flat` PPO, seed 42, 10,001 iterations | `teacher/` part | Euler job 95472 (euler17) | 2026-10-22 || 1a | rigid_prod collection | `python -m go2nrd.collect.mjlab.run --campaign rigid_prod --out RAW/rigid_prod --export EXPORT/rigid_prod --max-records-export 1001` | `collector_rigid_mjlab_nrd_3a9155b` | luffy, RTX 5090, 4,096 envs | 2026-10-29 || 1b | rigid_prod_v2 export | `python -m go2nrd.collect.common.export --raw RAW/rigid_prod --out EXPORT/rigid_prod_v2 --plan rigid_prod --max-records 1001` | export code = `collector_crm_code_v1_d8ef2fc8d989` (`src/go2nrd/collect/common`, = nrd commit `1346b2c`) | luffy | 2026-10-30 || 1c | crm_prod collection | pool worker `go2nrd.collect.chrono.run` (units from `cluster/amd/launch_crm/make_pool.py`; that script is not in this capsule, and the pool archives in `data/reports/prior/` hold the units that ran) | `collector_crm_code_v1_d8ef2fc8d989` | AMD mi2101x MI210, array job 487049 | 2026-10-30 || 1d | crm_prod export | `python -m go2nrd.collect.common.export --raw <shard dirs> --out EXPORT/crm_prod --plan crm_prod --threshold-n 20 --max-records 1001` | same | luffy | 2026-10-30 || 2a | lateral plan v2 | `PYTHONPATH=<wt>/src python -B collect/scripts/make_lateral_plan_v2.py --out-dir configs/collect/plans` | `study_scripts_lateral_stuck_20261108` | luffy | 2026-11-08 22:45 || 2b | lateral code freeze | `collect/scripts/cluster_freeze_code_v2.sh amd\|euler` | same | luffy -> clusters | 2026-11-08 22:57 || 2c | lateral collection | pools from `collect/scripts/cluster_make_pools_v2.sh`; worker `go2nrd.collect.chrono.run --backend-opt gpu_admission=false` | `collector_crm_code_lateral_stuck_20261108_v2_698933cdce75` | AMD mi2104x 509760 (HIP); Euler euler07 113924 (CUDA) | 2026-11-08 || 2d | lateral export, checker, slim diag, QA | `collect/orchestration/post_amd.sbatch`, `post_euler.sbatch` (`go2nrd.collect.common.export ... --threshold-n 20 --max-records 1001`, `validate`, `qa/extract_slim_diag.py`, `qa/qa_episodes.py`) | study scripts + lateral collector | AMD 509836, Euler 113929 | 2026-11-08 || 3 | split manifest | `PYTHONPATH=<wt>/src python -B collect/scripts/make_splits_lateral_v2.py --export-root EXPORT --out collect/splits_lateral_v2.json` | study scripts | luffy | 2026-11-08 23:48 || 4a | gates registered | `nrd_v3/gates/register_gates_v1.py`, `register_gates_v2.py`, `freeze_windows.py`, `build_reference.py` | study scripts | luffy | 2026-11-09 00:15 || 4b | NRD capsule | `nrd_v3/train/cluster/make_capsule.sh OUT_PARENT` | study scripts; result = `nrd_capsule_c0e07a22e57434cd` | luffy | 2026-11-09 00:26 || 5 | NRD FRESH-b training | `sbatch train_amd.sbatch CODE fresh fresh_lat_v2.json 62 fresh_b_s62 13200 0` | `nrd_capsule_c0e07a22e57434cd` | AMD mi3501x MI350X, job 509956 (k007-005-v6) | 2026-11-09 00:52-03:15 || 6 | loader export | `export_loader.py --src last.pt --out nrd_v3_FRESH-b_loader.pt --frozen-src <yaw_correction_v1 src> --manifest splits_lateral_v2.json --data-root EXPORT` | study scripts (`nrd_v3/train/export_loader.py`) + runtime code from `ppo_snapshot_8e08e2544f0d` | luffy CPU | 2026-11-09 04:16 || 7 | gate scoring and waiver | `PYTHONPATH=<wt>/src python run_gates.py LOADER.pt lineage.json OUT --label nrd_v3_FRESH-b`; `nrd_v3/gates/waiver_v1.json` | study scripts | luffy RTX 5090 | 2026-11-09 04:24-05:15 || 8a | OOD reference | `PYTHONPATH=<wt>/src python ppo_nrdv3/build_ood_reference.py --out assets/ood_ref_crm_freshb_v1.npz` | study scripts | luffy | 2026-11-09 05:17 || 8b | start groups | `python3 ppo_v3/build_start_groups.py` (input `diag/crm_coverage/lateral_windows.json`); result `start_groups_crm_stuck_v1.npz` (`e5b427d9...`) | study scripts | luffy | 2026-11-08 22:35 || 8c | PPO code snapshot | `ppo_nrdv3/make_snapshot.sh` | study scripts; result = `ppo_snapshot_8e08e2544f0d` | luffy | 2026-11-09 05:20:36 || 9 | PPO V2n s81 | `sbatch -w euler08 ppo_nrdv3_euler.sbatch CODE v2.json 81 lateral_stuck_20261108_ppo_nrdv3_V2_s81` | `ppo_snapshot_8e08e2544f0d` | Euler euler08, RTX A4500, job 114010 | 2026-11-09 05:21-05:31 || 10 | deploy ONNX re-export + parity | `python ppo_nrdv3/export_nrdv3.py lateral_stuck_20261108_ppo_nrdv3_V2_s81=<run dir>` (calls `go2nrd.eval.export_onnx` and `go2nrd.eval.parity --rows 4000`) | study scripts + `ppo_snapshot_8e08e2544f0d` (exporter `5e418e4c`) | luffy CPU | 2026-11-09 05:34 || 11a | Chrono suite_v1 + selection | `eval_suite/run_suite.py all --cluster amd --candidates ... --tag p2nrd`; `ppo_nrdv3/chrono_p2.py`; `selection/apply_selection_v1.py` | study scripts + `eval_chrono_suite_v1_p2nrd_699bc991a430` | AMD mi2101x MI210, jobs 510372-510389, 510462 | 2026-11-09 || 11b | rigid dev120 + C++ sim_deploy | `rigid_check/rigid_check.py all --candidates ... --tag ...` | study scripts + `eval_capsule_runtime_eval_v1_30417413` | luffy RTX 5090 | 2026-11-09 || 11c | held-out suite_v2 | `eval_suite_v2/run_suite_v2.py stage/submit/pull --tag q1`; `analyze_v2.py`; `decide_v2.py` | study scripts + `eval_chrono_suite_v2_q1_d407c6940ef1` | AMD mi2101x, jobs 510651-510678 | 2026-11-09 || 12 | deploy package (PR #3 of legged_rl_deploy) | `selection/make_pr_packages.py --repo <legged_rl_deploy worktree>` | study scripts | luffy | 2026-11-09 23:44 |
## 4. Stage details
### Stage 1: old data (rigid_prod_v2, crm_prod)
- The base teacher `model_10000.pt` (sha256 `7ee303f9...`) made all data. Its ONNX is `c58a3494...`.- rigid_prod: MuJoCo Warp plane, deterministic mean action, 8,700 episodes, collector pushes.- The rigid collector ran from a dirty tree. Its 7 file hashes equal commit `3a9155b`. The archive is `git archive 3a9155b -- src configs`.- The rigid plan is `configs/collect/plans/rigid_prod.json` (sha256 `e3ffdfc3...`) in that archive. The plan arrays file `rigid_prod_arrays.npz` (`4c3416af...`, 100 MB) is not in the code archives. `go2nrd.collect.common.plan` regenerates the arrays from the plan seeds and checks their sha256.- crm_prod: Chrono CRM (HIP build), teacher ONNX through the deploy pipeline, OU target noise, pushes. Plan `crm_prod.json` (`d2f30cc7...`) and its arrays are in `collector_crm_code_v1_d8ef2fc8d989`.- The export step of both data sets equals commit `1346b2c` (`src/go2nrd/collect/common`, in `collector_crm_code_v1_d8ef2fc8d989`).
### Stage 2: lateral v2 data
- Plan `lateral_stuck_20261108_crm_v2.json` sha256 `77ef91d9...`, master seed 2026110803, 480 planned episodes. Held-out plan `_test` sha256 `ae1f525c...`, seed 2026110804.- The plans and their arrays are in `collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/configs/collect/plans/`.- The capsule also holds `sim_eval/legged_sim_eval` (the deploy-policy evaluator) and `qa/`. The local `sim_eval` used later by the parity step is equal to this copy.- 400 episodes ran on AMD (HIP), 80 on Euler (CUDA). All use teacher ONNX `c58a3494`, OU noise and swing-lift injection (`swing_lift.py`, `relief.py`).- The deploy config of all Chrono collections is `config_noclip.yaml` (`5ea19848`). It is with the teacher files, not in the code archives.
### Stage 3: split manifest
- `splits_lateral_v2.json` (`9ba6dce9...`) extends `splits.json` (`f1d264dd...`). Both are in `nrd_capsule_c0e07a22e57434cd/manifests/`.- Arm `mixed_plus_lat_v2`, budget `matched`. The test export is only in `heldout_test`.
### Stage 5: NRD FRESH-b training
- Command inside `train_amd.sbatch`: `python3.12 -B CODE/nrd_v3/nrd_v3_train.py --mode fresh --run-config CODE/nrd_v3/configs/fresh_lat_v2.json --source-root CODE/src --pins CODE/nrd_v3/reference/pins.json --recipe CODE/nrd_v3/reference/full_config.json --data-root DATA_ROOT --output OUT --seed 62 --device cuda --max-wall-seconds 13200 --stop-at-update 0 --short-module CODE/nrd_v3/reference/short_support.py --manifest CODE/manifests/splits_lateral_v2.json`- `CODE` = the unpacked `nrd_capsule_c0e07a22e57434cd`. `DATA_ROOT` = the data root of section 2 (only the 4 training folders are read).- Env: `OMP_NUM_THREADS=1`, `OPENBLAS_NUM_THREADS=1`, `PYTHONDONTWRITEBYTECODE=1`.- Key file hashes: driver `nrd_v3_train.py` `73b6f253...`, `samplers.py` `b75f8f99...`, `stall_support.py` `adff6f30...`, recipe `df61c402...`.- Schedule: stage A updates 1-12000 (core, collision, joint one-step, rollout H10->H50), stage B 12001-13000, stage C 13001-13500.- One job, no resume. The output is `last.pt` (`b41561c3...`), `resume.pt`, `checkpoints/update_00{12000,13000,13500}.pt`, `lineage.json`, `train.jsonl`. These files are in `nrd/fresh_b/`.- The sbatch refuses to run when `OUT/complete.json` exists. Use a new output folder.
### Stage 6: loader export
- Command (same as `nrd_v3/replicate/collect_n2.sh`): `env -u PYTHONPATH OMP_NUM_THREADS=1 python -B nrd_v3/train/export_loader.py --src FRESH-b/last.pt --out FRESH-b/export/nrd_v3_FRESH-b_loader.pt --frozen-src <yaw_correction_v1 src> --manifest <nrd_capsule_c0e07a22e57434cd>/manifests/splits_lateral_v2.json --data-root EXPORT` (the manifest is also `data/splits/splits_lateral_v2.json`, `9ba6dce9...`)- `--frozen-src` = `nrd_capsule_c0e07a22e57434cd/src` (the frozen yaw_correction_v1 source).- The check imports `load_model` and `Go2NrdSim` from the working tree `src`. Use `ppo_snapshot_8e08e2544f0d/src` for this; its `contact_nrd/model.py` and `sim/nrd_sim.py` are the files that PPO used.- `export_loader.py` hard-codes `W=/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102` (line 26) for the check. Change `W` to the folder that holds that `src`.- The export stores the `--src` path string (`runtime.export.source_endpoint`). A byte-equal `501c9b8d` needs the original string; other paths give other bytes with the same weights.- The weights do not change. The result is `501c9b8d...`. A re-run reproduced it bitwise with `OMP_NUM_THREADS=1`.
### Stage 7: gates
- `gates_v1.json` (`38c85547...`) and `gates_v2.json` (`7ee59cb6...`) were registered before training.- FRESH-b fails G1 on 2 rigid rules. `waiver_v1.json` (by the coordinator) allows its use for PPO.
### Stage 8: PPO inputs
- OOD reference `ood_ref_crm_freshb_v1.npz` (`291e7eaa...`). Start groups `start_groups_crm_stuck_v1.npz` (in `ppo_snapshot_8e08e2544f0d/recipes/`). The policy inputs are also in `policy/inputs/`.
### Stage 9: PPO V2n s81
- Command inside `ppo_nrdv3_euler.sbatch`: `python -B -m go2nrd.fixed_base.ppo_lateral_v3 --base CODE/recipes/base_ppo71_config.json --recipe CODE/recipes/v2.json --paths CODE/recipes/paths_euler_nrdv3.json --overlay CODE/recipes/overlay_nrdv3_ood.json --nrd-sha256 501c9b8da022caf9594ad9cd7c50a7eda1e00424e5d4c9c7c8add65ee788848c --seed 81 --output OUT --device cuda --max-seconds 3000 --track P2_ppo_nrdv3`- `CODE` = the unpacked `ppo_snapshot_8e08e2544f0d`. `PYTHONPATH=<pydeps>:CODE/src`. `OMP_NUM_THREADS=8`.- Edit `paths_euler_nrdv3.json` (or use `paths_local_nrdv3.json`) to point at: crm_prod, rigid_prod_v2, the FRESH-b loader, the teacher `model_10000.pt`, the start groups and the OOD reference.- The driver merges base config `5ceaa0bc` + recipe `162b4883` + overlay `17d563ae` into `config.json`.- 300 iterations, 1,024 envs, 24 steps per env. Iterations 0-24 train only the critic. The actor starts from the teacher. The action std is capped to 0.2.- Output: `model_299.pt` (`cdb54fb5...`), `config.json`, `frozen_audit.json`, `complete.json`, an in-run `policy.onnx` (`6e82a553...`, not the deployed file).- The driver resumes from `last.pt` in OUT. Use a new output folder for a clean run.
### Stage 10: deploy ONNX re-export and parity
- `export_nrdv3.py` asserts the exporter sha256 `5e418e4c...` and the teacher ONNX `c58a3494...`.- It runs `python -m go2nrd.eval.export_onnx --checkpoint RUN/model_299.pt --out EXPORTS/<name>_i299 --reference <teacher velocity/policy.onnx> --template <teacher velocity/config.yaml>`.- Exporter: opset 18, static input [1, 47], metadata copied from the teacher ONNX, normalizer inside the graph.- Then `python -m go2nrd.eval.parity --folder EXPORTS/<name>_i299 --rows 4000` and a 4,000-row CRM parity.- Env: `CUDA_VISIBLE_DEVICES=""`, `OMP_NUM_THREADS=1`, `PYTHONPATH=<src>:<legged_rl_deploy>/sim_eval`. The exporter imports nothing from `unitree_rl_mjlab`. Only parity needs `sim_eval`; a byte-equal copy is in `collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/sim_eval`.- The exporter and parity read verification rows from the hard-coded raw shard `/home/harry/go2_sand/nrd_data/raw/rigid_test/rigid_test_s0000.npz` (`42917461...`). It is in this release as `data/aux/rigid_test_s0000.npz`. Pass `--shard` to parity, or put the file at that path. The ONNX bytes do not depend on it.- Result: `policy.onnx` `1419d972...`. Max ONNX vs torch difference 9.5e-6.- On 2026-11-17 a new export with only the archived `ppo_snapshot_8e08e2544f0d/src` (go2eval env, CPU) gave the same bytes `1419d972...` and the same `parity.json` values.
### Stage 11: evaluation
- Chrono suites run on AMD MI210 with the HIP Chrono build. The staged code for V2n s81 is in the two `eval_chrono_*` archives. The candidate ONNX files are not in those archives; `STAGE.json` and `source_manifest.json` list their sha256.- Selection rule v1 (`selection/selection_rule_v1.json`, `9d30877c...`) picked V2n s81 (rank 1, score 0.221).- The held-out suite_v2 label is NOT_CONFIRMED (G2, G3, S1). The rigid dev120 gate and the C++ sim_deploy check passed.- The C++ `legged_rl_deploy_node` binary is not archived. Build it from the public legged_rl_deploy repo.
## 5. Environments and hardware
| Stage | Hardware | Software (recorded) ||---|---|---|| Teacher | Euler euler17 | unitree_rl_mjlab commit `1425b15f` (see `teacher/`) || rigid_prod collection | luffy, NVIDIA RTX 5090 | python 3.11.17, mjlab env (MuJoCo Warp) || Data export (rigid_prod_v2, crm_prod) | luffy CPU | python 3.12.13, numpy 2.4.6, mujoco 3.3.6, torch 2.12.0, onnxruntime 1.30.0 (`go2eval` conda env) || crm_prod collection | AMD MI210 (mi2101x) | Chrono CRM HIP build, venv `go2nrd`, module pytorch/2.10.0 || Lateral collection + export | AMD MI210 (mi2104x), Euler euler07 RTX A4500 | python 3.12.12, numpy 2.4.3, onnxruntime 1.31.1; Chrono HIP and CUDA builds || NRD training | AMD Instinct MI350X (mi3501x) | python 3.12.12, torch 2.10.0+rocm7.1, HIP 7.1.25424, numpy 2.4.3 || Loader export, gates | luffy RTX 5090 / CPU | `go2eval` env, torch 2.12.0+cu130 || PPO | Euler euler08, NVIDIA RTX A4500 | torch 2.12.0+cu130, rsl-rl-lib 5.0.1, tensordict 0.14.3 (`go2eval` env + `ppo_v3_pydeps`). To rebuild the extra packages: `pip install --target <pydeps> rsl-rl-lib==5.0.1 tensordict==0.14.3 --no-deps` || Deploy ONNX export | luffy CPU | torch 2.12.0+cu130, onnx 1.22.0, numpy 2.4.6, onnxruntime 1.30.0 || Chrono evaluation | AMD MI210 (mi2101x) | HIP Chrono build (one binary for all roles of a tag) || Rigid dev120 | luffy RTX 5090 | unitree_rl_mjlab conda env |
No lock file exists. The cluster environments are not captured beyond these version strings.The Chrono builds (pychrono with CRM, HIP and CUDA) are not archived.
## 6. What is not bitwise reproducible
- Chrono collection on GPU: the CRM collector is not bit-deterministic on MI210. HIP and CUDA builds give different numbers.- NRD training: losses drift between GPU types. FRESH-b depends on its seed: seeds 61, 63 and 64 of the same recipe miss the main gate. FRESH-b was 1 of 4 candidates.- PPO: only `torch.manual_seed` is set. No deterministic flags. A bitwise re-run was not tested.- In-run ONNX: the run writes its own `policy.onnx` (`6e82a553`). It is never equal to the deployed file `1419d972`. Stage 10 makes the deployed file.- Chrono evaluation: scores change between job sets. V2n s81 scored 0.197 to 0.221 in 5 job sets. A re-run can pick a different rank-1 candidate.- Loader export: bitwise with `OMP_NUM_THREADS=1` (shown).- Deploy ONNX export: bitwise from the archived code (shown on 2026-11-17).- The archives themselves are deterministic: sorted members, fixed mtime, owner 0, gzip mtime 0.
## 7. Known gaps
- The go2nrd repository has no remote. Most study code is uncommitted. The archives are the only published copy.- Intermediate NRD checkpoints (update_*.pt), PPO checkpoints model_25..model_275 and the Slurm stdout files exist only on the clusters.- No real-robot log exists. The hardware result is only the user's report (2026-11-10/11): higher foot lift, stronger lateral motion on sand and rigid floor, a small stop jitter after -y lateral motion.- The selection label of V2n s81 is NOT_CONFIRMED. It was packaged as experimental.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785"""One Chrono collection episode (task or probe) of the mjlab policy, deploy-faithful, recorded at 10 ms.
New file (go2nrd Chrono collector builder, 2026-10-29). The loop follows legged_sim_eval ``episode.run_episode``(``/home/harry/go2_sand/legged_rl_deploy/sim_eval/legged_sim_eval/episode.py``, uncommitted user checkout of2026-10-22, read-only): build, ``LowLevel.enter_fixstand``, 1 s FixStand (go2.yaml gains, quintic), START in the laststand tick (``DeployPolicy.reset``), then the policy at every 4th 5 ms tick through ``DirectCommand``, ``torqueClip``,the float32 LowCmd and the PD law at every 0.5 ms MBD step (``pd_mode=substep``, also inside the FSI step). Changesfor collection (plan: specs/NRD_PLAN.md; contract: nrd/configs/collect/CONTRACT.md):
* fix_chrono worker, 2026-10-30 (NRD_PLAN.md section 10): ``torqueClip`` OFF by default (``EpisodeSpec.torque_clip``; the PD law's per-MBD-step actuator clamp at 23.5 / 45 N m stays, like mjlab's ``forcerange``, so the PD tracks the recorded action); the robot's MuJoCo soft joint limit (``go2nrd.chrono_robot.limits``, backend option ``joint_limits``); CRM label = norm of the vector sum of the foot-sphere and calf-cylinder FSI forces; per-interval CRM free flag ``crm_free`` (contract section 11); a CRM non-foot geom below the soil top ends the episode (``nonfoot_contact``, review D11); diag keeps every read's force vectors and the per-record joint-limit torque;
* records every 2 ticks from the hand-over tick (record 0 = the first policy tick; the stand is not recorded): the 37-channel base_link REF-frame state (``CollectorGo2Sim.state37``) read at the tick start, before ``apply``;* ``action[t]`` = the joint target the PD law gets over [t, t + 10 ms) (``sent.q`` in policy order: float32 of ``default + 0.25 raw + injection``), checked equal on the record's two ticks;* the plan's command per control step, the plan's OU injection (``InjectingLowLevel``), pushes (base COM, world);* per physics step (CRM: every 1.0 ms FSI exchange; rigid: every 0.5 ms MBD step) the pair forces; labels from the max over the reads that act inside the interval (measured read timing, :data:`FORCE_READ_WINDOW`);* terminations: nonfinite, fell (z < 0.15 m), tilt (> 70 deg), off_bed (CRM: base REF x, y within 0.25 m of the bed edge), nonfoot_contact (rigid: a non-foot mjlab collision geom below the surface or base contact in the interval; CRM: a base / hip / thigh mjlab collision geom below the NOMINAL soil top in any 1.0 ms exchange of the interval -- those bodies are not FSI bodies, the soil would not push them; the nominal top is conservative where the soil has sunk and is never more than the few cm of heave below the deformed top); a nonfoot event finishes its already driven 10ms interval and retains the finite endpoint before another policy/low-level tick; nonfinite endpoints are discarded as numerical failure rather than fabricated;* probes: no stand; spawn at the planned attitude / clearance with default + offsets, policy gains from tick 0, the policy reset at spawn with its phase counter set to ``phase_k0``;* CRM soil per episode (:mod:`go2nrd.collect.chrono.soil`, soil_sweep worker 2026-10-29): cohesion, internal friction mu_s = mu_2, density, Young's modulus from the plan entry's ``soil`` / the run's soil map / the campaign base, as evaluator backend options; defaults = the evaluator's soil. Recorded in ``RawEpisode.meta["soil"]`` and the raw shard meta; ``physics_config`` keeps the campaign base (identical over the campaign).
* opt-in uneven initial CRM surface (lateral_stuck_20261108, :mod:`go2nrd.collect.chrono.relief`): a plan entry's ``terrain_relief`` block makes the scene build the bed from a relief lattice (flat blocks: the unchanged box bed), adds ``physics_config["terrain_relief"]``, ``RawEpisode.meta["terrain_relief"]`` and the diag arrays ``relief_dk`` / ``surface_*``; entries without the key run exactly as before.* opt-in swing-lift perturbation (lateral_stuck_20261108 track A, :mod:`go2nrd.collect.chrono.swing_lift`): a plan entry's ``swing_lift`` block adds, per control step, a leg-folding offset to the joint target of each leg in its swing phase (teacher gait clock, causal) next to the OU injection; the recorded ``action`` contains it. Adds ``physics_config["swing_lift"]``, ``RawEpisode.meta["swing_lift"]``, the raw per-record array ``swing_lift`` and the diag arrays ``swing_lift_*`` / ``injection_applied``; entries without the key run exactly as before.
Partial records are flushed every ``flush_every`` records (atomic npz), so an FSI process abort keeps what was done.
Child entry point (one process per attempt; ``go2nrd.collect.chrono.run`` writes the spec)::
python -B -m go2nrd.collect.chrono.episode SPEC.json"""
from __future__ import annotations
import dataclassesimport hashlibimport jsonimport mathimport osimport shutilimport sysimport timeimport tracebackfrom dataclasses import dataclass, fieldfrom functools import lru_cachefrom pathlib import Pathfrom typing import Any
import numpy as np
from go2nrd.collect.chrono import soil as Sfrom go2nrd.collect.common import contract as Cfrom go2nrd.collect.common.plan import probe_initial_state, probe_initial_velocity
COLLECTOR_NAME = "go2nrd.collect.chrono"COLLECTOR_VERSION = "2"FORCE_READ_WINDOW = {"crm": (2, 1), "rigid": (0, 0)}"""Which force reads act inside a span of steps: the steps a+1 .. b are driven by the reads a+1-lo .. b-hi(read j = the value read right after step j; read 0 = before the first step). Measured with the robot's linearmomentum balance (go2nrd.collect.chrono.analysis.momentum_timing; reports/build_chrono.md):
* rigid (lo, hi) = (0, 0): ``GetContactForce`` read after an MBD step is the force of that step (residual 3e-6 N);* CRM (lo, hi) = (2, 1): the momentum change over FSI exchange s is exactly (read[s-2] + read[s-1]) / 2 * dt (residual < 1e-6 N): the first 0.5 ms MBD substep of exchange s uses the ``GetFsiBodyForce`` value read after exchange s-2, the second uses the one read after s-1. A read acts 0.5-1.5 ms after it is read; an interval's steps a+1 .. b use the reads a-1 .. b-1 (11 reads, the outer two for half an exchange each)."""CONTACT_THRESHOLD_N = {"rigid": 1.0, "crm": 20.0}"""Label threshold written into the raw shards: rigid 1 N (G1 rule); CRM 20 N: the NRD_PLAN.md section 10 rule on theHIP-build pilot (fix_chrono 2026-10-30, reports/fix_chrono.md: 8 soils, cohesion 0 / 250 / 1000 / 4000 Pa x mu 0.6 /0.9, two 10 s walks + a 4 s stand + a drop each; candidates 2 / 5 / 10 / 15 / 20 N on the norm label; 20 N has the bestmean agreement with the kinematic stance estimate, 0.888, with flicker <= 0.04 per s per foot on every soil; 10 and15 N exceed 0.1 per s on soft soil). export --threshold-n relabels exactly from contact_force."""CRM_PAIR_RULE = ("norm of the vector sum of the foot-sphere and calf-cylinder FSI forces (world, GetFsiBodyForce) of " "the leg, per force read; non-negative by construction (NRD_PLAN.md section 10, review D3)")CRM_FREE_FORCE_N = C.CRM_FREE_FORCE_NFREE_FLAG = getattr(C, "CRM_FREE_FLAG", "crm_free")"""Per-interval CRM free flag name (contract section 11)."""STAND_S = 1.0FLUSH_EVERY = 100TEST_ABORT_ENV = "GO2NRD_CHRONO_TEST_ABORT""""Test hook: ``"<record>:<attempt>,<attempt>"`` makes the child call ``os.abort()`` (SIGABRT, like a CUDA / FSIabort) when it reaches that record in one of those attempts. Unset in real runs."""
def _test_abort(record: int, attempt: int) -> None: hook = os.environ.get(TEST_ABORT_ENV) if not hook: return at, _, attempts = hook.partition(":") if record == int(at) and (not attempts or attempt in {int(a) for a in attempts.split(",")}): sys.stdout.flush() os.abort()
@dataclassclass EpisodeSpec: """Everything one attempt needs (JSON: the parent writes it, the child reads it)."""
campaign: str entry: dict commands: list injection: list terrain: str out: str partial: str diag: str error: str attempt: int = 1 max_records: int | None = None override_command: list | None = None override_sigma_zero: bool = False trace_fsi: bool = False threshold_n: float | None = None read_window: list | None = None config: str | None = None command_clip: str = "none" torque_clip: bool = False """Deploy ``torqueClip`` (the judge's; NRD_PLAN.md section 10: off in the collector, so the PD law tracks the recorded action with only the per-MBD-step actuator clamp).""" flush_every: int = FLUSH_EVERY backend_options: dict = field(default_factory=dict) shard_meta: dict = field(default_factory=dict) soil_campaign: dict = field(default_factory=dict) """CRM campaign base soil (``run --soil``); see :mod:`go2nrd.collect.chrono.soil`.""" soil_episode: dict | None = None """This episode's soil from the run's ``--soil-map`` (the plan entry's ``soil`` is read from ``entry``).""" policy: str | None = None """A deploy folder of go2nrd.eval.export_onnx (``run --policy``; round_tools 2026-10-30): its ONNX instead of the mjlab policy's, same deploy settings (:func:`go2nrd.collect.chrono.deploy.with_policy_folder`). None = default."""
def save(self, path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name(path.name + ".tmp") tmp.write_text(json.dumps(self.__dict__)) os.replace(tmp, path)
@classmethod def load(cls, path: Path | str) -> "EpisodeSpec": return cls(**json.loads(Path(path).read_text()))
# ====================================================================== helpersdef category_of(terrain: str) -> str: return "crm" if terrain == "crm" else "rigid"
def rigid_floor_size(entry: dict, commands: np.ndarray) -> float: """Edge of the rigid ground box: covers the spawn plus an upper bound of the planned travel, with 5 m margin (an entry key ``floor_size_m`` overrides it: tests against the evaluator's own floor).""" if entry.get("floor_size_m"): return float(entry["floor_size_m"]) r0 = math.hypot(entry["spawn"]["x"], entry["spawn"]["y"]) travel = float(np.hypot(commands[:, 0], commands[:, 1]).sum() * C.CONTROL_STEP_S) if len(commands) else 0.0 return max(10.0, 2.0 * (r0 + travel + 5.0))
def backend_options(terrain: str, extra: dict | None = None) -> dict: """The evaluator's scene options; rigid: sample every 0.5 ms MBD step (physics-neutral in substep mode). CRM without ``nvidia-smi`` (AMD / ROCm): GPU admission off unless asked for (its lock and memory poll need ``nvidia-smi``; physics-neutral, reports/build_cluster.md section 4).""" opts = dict(extra or {}) if terrain == "rigid": opts.setdefault("exchange_step_s", float(opts.get("rigid_mbd_step_s", 5e-4))) elif shutil.which("nvidia-smi") is None: opts.setdefault("gpu_admission", False) return opts
def episode_soil(spec: EpisodeSpec, opts: dict) -> tuple[dict, dict | None]: """(backend options with the episode's soil, the soil record or None). CRM: the soil keys of ``opts`` become the campaign base, the episode's values (:func:`go2nrd.collect.chrono.soil.resolve`) are passed as backend options. Rigid: options unchanged; a soil request is noted as ignored.""" if spec.terrain != "crm": asked = spec.entry.get("soil") or spec.soil_episode or spec.soil_campaign return opts, (dict(ignored="rigid terrain has no soil", requested=dict( plan=spec.entry.get("soil"), map=spec.soil_episode, campaign=spec.soil_campaign or None)) if asked else None) rest, backend_soil = S.split_backend_options(opts) record = S.resolve(spec.entry, spec.soil_campaign, spec.soil_episode, backend_soil) record["defaults"] = S.evaluator_defaults() return {**rest, **record["values"]}, record
@lru_cache(maxsize=1)def pychrono_core_md5() -> str | None: """md5 (16 hex) of the loaded pychrono ``_core.so`` (AMD HIP builds report ``pychrono: unknown``).""" try: import pychrono
path = Path(pychrono.__file__).parent / "_core.so" h = hashlib.md5() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1 << 22), b""): h.update(chunk) return h.hexdigest()[:16] except Exception: # noqa: BLE001 - informational return None
def canonical_build(backend: Any, soil_base: dict | None = None) -> tuple[str, dict]: """(build id, ``params.physics()``) of ``backend`` with the URDF named by file name + sha256 instead of its path (the cluster jobs run from per-job code snapshots, so the path differs between jobs; the evaluator does the same for its canonical go2_irrvis URDF) and, if ``soil_base`` is given, the soil replaced by the campaign base.""" p = backend.params q = dataclasses.replace(p, urdf=f"{Path(backend.sim.urdf.path).name} sha256 {backend.sim.urdf.sha256}") if soil_base is not None: q = dataclasses.replace(q, crm=dataclasses.replace(q.crm, soil=dataclasses.replace(q.crm.soil, **soil_base))) backend.params = q try: return backend.build_id(), backend.params.physics() finally: backend.params = p
def physics_config(backend: Any, cfg: Any, terrain: str, command_clip: str, window: tuple, soil: dict | None = None, torque_clip: bool = False) -> dict: """Simulator settings for system.json (identical for every episode of a campaign on one build; no paths). CRM with a soil record: ``params.crm.soil`` and ``build_id`` are the campaign base, ``soil`` says where the per-episode values are (:func:`go2nrd.collect.chrono.soil.physics_block`).""" from legged_sim_eval.backends.chrono_backend import pychrono_build
sim = backend.sim build_id, phys = canonical_build(backend, soil["base"] if (soil is not None and "base" in soil) else None) extra = dict(soil=S.physics_block(soil["base"], soil["defaults"])) if (soil is not None and "base" in soil) else {} return dict( simulator="Chrono (pychrono)", pychrono=pychrono_build(), pychrono_core_md5=pychrono_core_md5(), backend=backend.name, build_id=build_id, **extra, terrain=terrain, params=phys, robot=backend.robot_extras(), robot_mass_kg=None, mbd_step_s=sim.mbd_dt, sample_step_s=sim.exchange_dt, fsi_exchange_step_s=sim.exchange_dt if terrain == "crm" else None, rigid_sample_note=("rigid: exchange_step_s = the 0.5 ms MBD step only to read every MBD step's contact " "force; same DoStepDynamics calls as the evaluator's 2.5 ms samples") if terrain == "rigid" else None, surface_z_in_sim=sim.surface_z() if sim.system is not None else (0.2 if terrain == "crm" else 0.05), deploy=dict(config_sha256=cfg.sha256, model_sha256=cfg.model_sha256, ll_dt=cfg.ll_dt, policy_dt=float(np.float32(cfg.policy.get("policy_dt", 0.02))), tau_max=cfg.tau_max.tolist(), torque_clip=bool(torque_clip), command_clip=command_clip, fixstand_kp=cfg.llc.kp.tolist(), fixstand_kd=cfg.llc.kd.tolist()), startup="task: FixStand 1 s (go2.yaml gains, quintic from the spawn pose), START in the last stand tick, " "records from the first policy tick; probes: spawn in the air at the planned pose, policy gains " "and policy reset at spawn (phase counter = plan phase_k0)", injection="plan OU target noise added to the HighController target before torqueClip (motor order)", push=("world-frame force at the base COM through a base force accumulator, set at the planned record " "boundaries; acts 0.5 ms (one MBD step) later for exactly 0.1 s (Chrono accumulator update lag)"), force_read_window=dict(lo=int(window[0]), hi=int(window[1]), rule="steps a+1..b <- reads a+1-lo..b-hi"), nonfoot=("rigid: kinematic, any mjlab non-foot collision geom (base, hips, thighs, calves) below the box " "top, or base contact force; CRM: base, hip or thigh geom below the nominal soil top in any 1.0 ms " "exchange; both end the episode (terminal reason nonfoot_contact)"), actuator=("PD law at every MBD step, clamped at the effort limit (23.5 / 45 N m) per step" + ("; deploy torqueClip on the 5 ms ticks" if torque_clip else "; no deploy torqueClip")), joint_limits=("MuJoCo default soft joint limit of the mjlab model as a one-sided torque in the PD law " "(go2nrd.chrono_robot.limits; robot.joint_limits)" if "joint_limits" in backend.robot_extras() else "none"), )
def build_meta(spec: EpisodeSpec) -> dict: e = spec.entry keep = ("index", "shard", "shard_slot", "command_family", "long_run", "duration_s", "records", "control_steps", "spawn", "bed", "noise", "pushes", "clearance_m", "tilt_rad", "tilt_axis_rad", "joint_offsets_rad", "command", "phase_k0", "command_scale") return {"plan": {k: e[k] for k in keep if k in e}, "campaign": spec.campaign}
# ====================================================================== the episodeclass Recorder: """Per-record arrays (L planned records) + per-step force reads."""
def __init__(self, L: int, crm: bool) -> None: self.L = L self.state = np.full((L, C.STATE_DIM), np.nan) self.action = np.full((L, C.ACTION_DIM), np.nan) aux = C.empty_aux(L) self.obs, self.raw, self.command = aux["obs"], aux["raw_action"], aux["command"] self.phase_k, self.push_force, self.nonfoot = aux["phase_k"], aux["push_force"], aux["nonfoot_contact"] self.com = np.full((L, 6), np.nan) # base COM position (z minus surface) and velocity, world self.feet = np.full((L, 4, 3), np.nan) # foot sphere centres (world, z minus surface) self.tau_ff = np.full((L, 2, 12), np.nan) # torqueClip feed-forward of the record's 2 ticks (policy order) self.t_sim = np.full(L, np.nan) self.reads: list[np.ndarray] = [] # per step (P, 3); reads[0] = before the first step self.step_record: list[int] = [-2] # record of each read's step (-1 = stand, -2 = before any) self.extra: dict[str, list] = {"torque": [], "momentum": [], "t": []} self.crm = crm self.nonfoot_low = np.full(L, np.inf) # smallest non-foot clearance seen in the interval (m) self.first_step_of_record = np.full(L, -1, np.int64) self.limit_torque = np.zeros((L, 12)) # max |joint-limit torque| in the interval (policy order, N m) self.limit_pen = np.zeros((L, 12)) # max limit penetration in the interval (rad) self.limit_steps = np.zeros((L, 12), np.int32) # MBD steps with an active limit in the interval self.stand_limit = None
def interval_forces(rec: Recorder, L: int, window: tuple, crm: bool) -> dict: """Per-interval forces from the step reads (reads acting in the interval, :data:`FORCE_READ_WINDOW`):
* ``contact_force`` [L-1, 4]: CRM: the max over the reads of the NORM of the vector sum foot sphere + calf cylinder of the leg (:data:`CRM_PAIR_RULE`; sees pull and shear, review D3); rigid: max(0, max over the reads of the foot's world z contact force); * CRM ``foot_force`` / ``calf_force`` [L-1, 4]: max over the reads of the force NORM of the foot sphere / calf cylinder (per-body diagnostics; the full vectors of every read are in the diag file); * CRM ``crm_free`` [L-1] uint8 (contract section 11): 1 iff all 8 body force norms are below ``CRM_FREE_FORCE_N`` (1 N) in every read acting in the interval.""" reads = np.asarray(rec.reads) # [S + 1, P, 3]: reads[s] = after step s fz = reads[..., 2] fn = np.linalg.norm(reads, axis=-1) pn = np.linalg.norm(reads[:, :4] + reads[:, 4:8], axis=-1) if crm else None first = rec.first_step_of_record[:L] # steps done when record r was read if (first[: L] < 0).any() or np.any(np.diff(first) <= 0): raise RuntimeError("record step bookkeeping is broken") out_pair = np.zeros((L - 1, 4)) out_foot = np.zeros((L - 1, 4)) out_calf = np.zeros((L - 1, 4)) out_free = np.zeros(L - 1, np.uint8) for r in range(L - 1): # the steps of interval r are first[r] + 1 .. first[r + 1]; they are driven by the reads below idx = np.clip(np.arange(first[r] + 1 - window[0], first[r + 1] + 1 - window[1]), 0, len(fz) - 1) if crm: out_pair[r] = pn[idx].max(0) out_foot[r] = fn[idx, :4].max(0) out_calf[r] = fn[idx, 4:8].max(0) out_free[r] = np.uint8(fn[idx, :8].max() < CRM_FREE_FORCE_N) else: out_pair[r] = np.maximum(fz[idx, :4].max(0), 0.0) out: dict[str, np.ndarray] = {"contact_force": out_pair} if crm: out.update(foot_force=out_foot, calf_force=out_calf) out[FREE_FLAG] = out_free return out
def assemble(spec: EpisodeSpec, rec: Recorder, L: int, terminal: str, info: dict, window: tuple, threshold: float) -> C.RawEpisode: """RawEpisode of the first L records.""" e = spec.entry crm = category_of(spec.terrain) == "crm" forces = interval_forces(rec, L, window, crm) cf = forces.pop("contact_force") action = rec.action[:L].copy() if not np.isfinite(action[L - 1]).all(): action[L - 1] = action[L - 2] extra = {} if getattr(rec, "per_record_extra", None): # swing_lift episodes only (swing_lift.py) for k, v in rec.per_record_extra.items(): x = v[:L].copy() if not np.isfinite(rec.action[L - 1]).all(): # the last record repeats the last interval's values x[L - 1] = x[L - 2] extra[k] = x events = [] for p in e.get("pushes", []): a, b = int(p["start_record"]), min(int(p["stop_record"]), L) if a < b: events.append([a, b]) push_force = rec.push_force[:L].copy() push_force[L - 1] = 0.0 meta = build_meta(spec) meta.update(info) if crm and e.get("bed"): meta["bed_bounds"] = e["bed"]["bounds_m"] return C.RawEpisode( episode_id=int(e["episode_id"]), group_id=int(e["group_id"]), seed=int(e["seed"]), family=e["family"], category=category_of(spec.terrain), terminal_reason=terminal, state=rec.state[:L], action=action, contacts=(cf > threshold).astype(np.uint8), contact_force=cf, obs=rec.obs[:L], raw_action=rec.raw[:L], command=rec.command[:L], phase_k=rec.phase_k[:L], push_force=push_force, nonfoot_contact=rec.nonfoot[:L], push_events=events, per_interval=forces, meta=meta, **({"per_record": extra} if extra else {})).check()
def save_episode(path: Path | str, ep: C.RawEpisode, shard_meta: dict) -> None: C.save_raw_shard(path, [ep], shard_meta)
def save_diag(path: Path | str, rec: Recorder, L: int, trace: bool) -> None: path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) reads = np.asarray(rec.reads, np.float32) arrays = dict(com=rec.com[:L], feet=rec.feet[:L], tau_ff=rec.tau_ff[:L], t_sim=rec.t_sim[:L], step_record=np.asarray(rec.step_record, np.int32), nonfoot_low=rec.nonfoot_low[:L], first_step_of_record=rec.first_step_of_record[:L], limit_torque=rec.limit_torque[:L], limit_pen=rec.limit_pen[:L], limit_steps=rec.limit_steps[:L]) arrays["force_z"] = reads[..., 2] arrays["force_norm"] = np.linalg.norm(reads, axis=-1) arrays["force"] = reads # every read's per-body vectors (CRM: 4 feet then 4 calves) for k, v in (getattr(rec, "relief_arrays", None) or {}).items(): # terrain_relief episodes only (relief.py) arrays[k] = v for k, v in (getattr(rec, "lift_arrays", None) or {}).items(): # swing_lift episodes only (swing_lift.py) arrays[k] = v[:L] if trace: for k, v in rec.extra.items(): if v: arrays[k] = np.asarray(v, np.float64) tmp = path.with_name(path.name + ".tmp.npz") np.savez_compressed(tmp, **arrays) os.replace(tmp, path)
def _lift_copy_last(rec: Recorder, r: int) -> None: """swing_lift: the terminal record r (no interval of its own) repeats record r-1's offsets, like its action.""" for k, v in rec.lift_arrays.items(): v[r] = v[r - 1] for v in rec.per_record_extra.values(): v[r] = v[r - 1]
def run_episode(spec: EpisodeSpec) -> dict: """Run one attempt; writes spec.out (raw shard of one episode) and spec.diag; returns the summary.""" from legged_sim_eval.lowlevel import DirectCommand
from go2nrd.collect.chrono.deploy import load_policy, make_low_level_class, policy_record from go2nrd.collect.chrono.scene import JMAP, collector_backend_class, to_motor
t_start = time.perf_counter() e = spec.entry terrain = spec.terrain category = category_of(terrain) crm = terrain == "crm" probe = e["family"] in C.PROBE_FAMILIES initial_velocity = probe_initial_velocity(e) # reject malformed opt-in before policy/backend/world build window = tuple(FORCE_READ_WINDOW[category] if spec.read_window is None else spec.read_window) threshold = float(spec.threshold_n if spec.threshold_n is not None else CONTACT_THRESHOLD_N[category]) commands = np.asarray(spec.commands, np.float32).reshape(-1, 3) injection = np.asarray(spec.injection, np.float32).reshape(-1, 12) if spec.override_command is not None: commands = np.tile(np.asarray(spec.override_command, np.float32), (len(commands), 1)) if spec.override_sigma_zero: injection = np.zeros_like(injection) L = int(e["records"]) if spec.max_records is not None and spec.max_records < L: L = 2 * ((int(spec.max_records) - 1) // 2) + 1 if L < 3 or (L - 1) // 2 > len(commands): raise ValueError(f"episode {e['episode_id']}: {L} records for {len(commands)} control steps")
cfg, policy = load_policy(spec.config, spec.command_clip, spec.policy) ll_dt = float(cfg.ll_dt) if abs(2 * ll_dt - C.RECORD_STEP_S) > 1e-12: raise RuntimeError(f"two low-level ticks ({2 * ll_dt}) must equal the 10ms record interval") Backend = collector_backend_class() opts, soil = episode_soil(spec, backend_options(terrain, spec.backend_options)) backend = Backend(terrain, pd_mode="substep", **opts) backend.set_tick_period(ll_dt) sim = backend.sim n_tick = int(round(ll_dt / sim.exchange_dt)) if abs(n_tick * sim.exchange_dt - ll_dt) > 1e-12: raise RuntimeError(f"tick {ll_dt} is not a multiple of the step {sim.exchange_dt}")
# ---------------------------------------------------------------- build if probe: init = probe_initial_state(e) q_motor = to_motor(np.asarray(init["joint_pos"])) sim.spawn_quat = np.asarray(init["quat_wxyz"], np.float64) sim.spawn_clearance = float(init["clearance_m"]) if initial_velocity is not None: sim.spawn_velocity_world = initial_velocity x, y, yaw = float(init["x"]), float(init["y"]), 0.0 else: q_motor = np.asarray(cfg.llc.fixstand_q, np.float64) x, y, yaw = float(e["spawn"]["x"]), float(e["spawn"]["y"]), float(e["spawn"]["yaw"]) relief = None if "terrain_relief" in e: # opt-in uneven initial CRM surface (relief.py); entries without the key: flat bed from go2nrd.collect.chrono import relief as R
if not crm: raise ValueError(f"episode {e['episode_id']}: terrain_relief needs CRM terrain") relief = R.validate(e["terrain_relief"]) if relief is not None: sim.terrain_relief = relief sim.relief_spawn_xy = (x, y) lift = None if "swing_lift" in e: # opt-in swing-lift perturbation (swing_lift.py); entries without the key: unchanged from go2nrd.collect.chrono import swing_lift as SL
if probe: raise ValueError(f"episode {e['episode_id']}: swing_lift is for task episodes") lift = SL.validate(e["swing_lift"]) bed = tuple(e["bed"]["patch_m"]) if (crm and e.get("bed")) else ((8.0, 4.0) if crm else None) t0 = time.perf_counter() build_stats = sim.build(x, y, q_motor, yaw=yaw, bed=bed, floor_size_m=rigid_floor_size(e, commands)) build_s = time.perf_counter() - t0 surface = sim.surface_z() shard_meta = dict(spec.shard_meta) shard_meta["soil"] = soil shard_meta["policy"] = policy_record(cfg, spec.policy) build_id = canonical_build(backend)[0] # this episode's build (its own soil; URDF by name + sha256) pc = physics_config(backend, cfg, terrain, spec.command_clip, window, soil, spec.torque_clip) pc["robot_mass_kg"] = sim.mass() probe_every = 0 if relief is not None: pc["terrain_relief"] = R.physics_block() # campaign-constant; the episode's own relief is in its meta sp = relief.get("surface_probe") or {} probe_every = int(sp.get("every_records", 0)) surf_maps, surf_index = [], [] if lift is not None: pc["swing_lift"] = SL.physics_block() # campaign-constant; the episode's holds are in its meta shard_meta.setdefault("physics_config", pc) shard_meta.setdefault("contact_rule", C.contact_rule( category, threshold, rule=(f"pair p (leg FL/FR/RL/RR vs soil) on in record interval k if the {CRM_PAIR_RULE} exceeds threshold_n " "in ANY force read acting inside (t_k, t_k + 10 ms]; contact_force = the largest value over those reads") if crm else None, component=CRM_PAIR_RULE if crm else "world z of the foot contact force, clipped at 0", aggregation="max over the force reads acting in the interval", step="FSI exchange 1.0 ms (2 MBD substeps)" if crm else "MBD step 0.5 ms", read_window=list(window), read_timing=("CRM: exchange s is driven by the GetFsiBodyForce values read after exchanges s-2 and s-1 (one " "0.5 ms MBD substep each); rigid: GetContactForce after a step is that step's force"), diagnostics=(f"CRM foot_force / calf_force = max force norm over the same reads; {FREE_FLAG} = all 8 body " f"norms < {CRM_FREE_FORCE_N} N in every read of the interval (contract section 11)") if crm else None))
LowLevel = make_low_level_class() low = LowLevel(cfg, policy, loop_cnt0=0, torque_clip=bool(spec.torque_clip)) source = DirectCommand(policy) rec = Recorder(L, crm) if lift is not None: rec.per_record_extra = dict(swing_lift=np.zeros((L, 12), np.float32)) rec.lift_arrays = dict(swing_lift_offset=np.zeros((L, 12)), swing_lift_weight=np.zeros((L, 4)), swing_lift_env=np.zeros(L), swing_lift_k=np.full(L, -1, np.int64), injection_applied=np.zeros((L, 12))) lift_inj = None rec.reads.append(sim.pair_forces()) state = backend.state() if probe: policy.reset(state) policy.policy_steps = int(e["phase_k0"]) low.mode = "high" n_stand = 0 else: low.enter_fixstand(state) n_stand = max(1, int(round(STAND_S / ll_dt))) inj_motor = np.zeros((len(injection), 12)) inj_motor[:, JMAP] = injection.astype(np.float64) pushes = [(int(p["start_record"]), int(p["stop_record"]), np.asarray(p["force_n"], np.float64)) for p in e.get("pushes", [])] bounds = e["bed"]["bounds_m"] if (crm and e.get("bed")) else None zero3 = np.zeros(3, np.float32) trace = bool(spec.trace_fsi) check_every = 1 if crm else 2 # non-foot kinematics every 1 ms steps = 0
def physics(record: int) -> None: nonlocal steps for j in range(n_tick): sim.step(1) steps += 1 rec.reads.append(sim.pair_forces()) rec.step_record.append(record) if trace: rec.extra["momentum"].append(sim.momentum()) rec.extra["t"].append(sim.time) if crm: rec.extra["torque"].append(sim.fsi_torques()) if record >= 0: if steps % check_every == 0: low_z = sim.nonfoot_clearance(include_calves=not crm) rec.nonfoot_low[record] = min(rec.nonfoot_low[record], low_z) if low_z < 0.0: rec.nonfoot[record] = 1 if not crm and np.any(rec.reads[-1][4] != 0.0): rec.nonfoot[record] = 1
# ---------------------------------------------------------------- stand (task episodes) t_loop = time.perf_counter() for k in range(n_stand): if k > 0: state = backend.state() pad = source.update(zero3) sent = low.tick(state, pad, start=(k == n_stand - 1)) backend.apply(sent.q, sent.kp, sent.kd, sent.tau) physics(-1) stand_wall = time.perf_counter() - t_loop stand_lim = sim.take_limit_stats() rec.stand_limit = dict(torque_max=float(stand_lim[0].max()), pen_max=float(stand_lim[1].max()), steps=int(stand_lim[2].sum()))
# ---------------------------------------------------------------- records terminal = "planned_end" L_end = L pending_nonfoot_endpoint = False info: dict[str, Any] = {} t_rec = time.perf_counter() for r in range(L): if r > 0 or n_stand > 0: state = backend.state() x37 = sim.state37() if not np.isfinite(x37).all(): terminal, L_end = "nonfinite", r break rec.state[r] = x37 rec.t_sim[r] = sim.time rec.com[r, :3] = [sim.base.GetPos().x, sim.base.GetPos().y, sim.base.GetPos().z - surface] v = sim.base.GetPosDt() rec.com[r, 3:] = [v.x, v.y, v.z] fc = sim.foot_centres() fc[:, 2] -= surface rec.feet[r] = fc if probe_every and r % probe_every == 0: smap, (sx0, sy0, st) = R.surface_map(sim, float(sp["half_box_m"]), float(sp["cell_m"])) surf_maps.append(smap) surf_index.append((r, sx0, sy0, st)) c = r // 2 rec.command[r] = commands[min(c, len(commands) - 1)] rec.first_step_of_record[r] = steps # reads index of the first step after record r if pending_nonfoot_endpoint: # The previous iteration already completed both 5ms low-level # ticks. Read this exact grid endpoint, without another action or # simulation step. FSI exceptions never reach this path; a # nonfinite endpoint was rejected above and remains "nonfinite". if r == 0 or abs(rec.t_sim[r] - rec.t_sim[r - 1] - C.RECORD_STEP_S) > 1e-8: raise RuntimeError("nonfoot endpoint is not one completed 10ms record interval later") rec.phase_k[r] = policy.policy_steps if r % 2 == 0 else rec.phase_k[r - 1] rec.action[r] = rec.action[r - 1] if lift is not None: _lift_copy_last(rec, r) terminal, L_end = "nonfoot_contact", r + 1 break tilt = math.acos(max(-1.0, min(1.0, 1.0 - 2.0 * (x37[4] ** 2 + x37[5] ** 2) / float(x37[3:7] @ x37[3:7])))) if x37[2] < C.TERMINATION["min_base_height_m"]: terminal, L_end = "fell", r + 1 elif tilt > C.TERMINATION["max_tilt_rad"]: terminal, L_end = "tilt", r + 1 elif bounds is not None and not (bounds[0][0] + 0.25 <= x37[0] <= bounds[1][0] - 0.25 and bounds[0][1] + 0.25 <= x37[1] <= bounds[1][1] - 0.25): terminal, L_end = "off_bed", r + 1 if terminal != "planned_end" or r == L - 1: rec.phase_k[r] = policy.policy_steps if r % 2 == 0 else rec.phase_k[r - 1] if r % 2 == 1: rec.action[r] = rec.action[r - 1] if lift is not None and r > 0: _lift_copy_last(rec, r) break if spec.flush_every and r > 0 and r % spec.flush_every == 0: ep = assemble(spec, rec, r + 1, "fsi_abort", dict(partial=True, attempt=spec.attempt, soil=soil, build=build_id, **({"terrain_relief": sim.relief_info} if relief is not None else {}), **({"swing_lift": SL.summary(lift)} if lift is not None else {})), window, threshold) save_episode(spec.partial, ep, shard_meta) _test_abort(r, spec.attempt) # the interval [r, r + 1): two low-level ticks push = next((f for a, b, f in pushes if a <= r < b), None) sim.set_push(push) if push is not None: rec.push_force[r] = push if lift is None: low.injection = inj_motor[c] else: # swing_lift: OU + lift offset, constant over control step c if r % 2 == 0 or lift_inj is None: k_now = int(policy.policy_steps) # the counter of this control step's observation (causal) lo, lw, le = SL.offset(lift, k_now, rec.command[r], c) lift_motor = np.zeros(12) lift_motor[JMAP] = lo lift_inj = (inj_motor[c] + lift_motor, lo, lw, le, k_now) low.injection = lift_inj[0] la = rec.lift_arrays la["swing_lift_offset"][r], la["swing_lift_weight"][r] = lift_inj[1], lift_inj[2] la["swing_lift_env"][r], la["swing_lift_k"][r] = lift_inj[3], lift_inj[4] la["injection_applied"][r] = lift_inj[0][JMAP] rec.per_record_extra["swing_lift"][r] = lift_inj[1] for sub in (0, 1): if sub == 1: state = backend.state() pad = source.update(rec.command[r]) sent = low.tick(state, pad) target = sent.q[JMAP] if sub == 0: rec.action[r] = target if low.policy_ran: rec.obs[r] = policy.last_input rec.raw[r] = policy.last_raw rec.phase_k[r] = policy.policy_steps - 1 if lift is not None and rec.phase_k[r] != lift_inj[4]: raise RuntimeError(f"swing_lift: phase counter {lift_inj[4]} != observed {rec.phase_k[r]}") elif r % 2 == 0: raise RuntimeError(f"no policy step at record {r}") else: rec.phase_k[r] = rec.phase_k[r - 1] elif not np.array_equal(target, rec.action[r]): raise RuntimeError(f"target changed inside record {r}") rec.tau_ff[r, sub] = sent.tau[JMAP] backend.apply(sent.q, sent.kp, sent.kd, sent.tau) physics(r) lt, lp, ls = sim.take_limit_stats() rec.limit_torque[r], rec.limit_pen[r], rec.limit_steps[r] = lt[JMAP], lp[JMAP], ls[JMAP] if rec.nonfoot[r]: # rigid and CRM (review D11) pending_nonfoot_endpoint = True sim.set_push(None) loop_wall = time.perf_counter() - t_loop rec_wall = time.perf_counter() - t_rec if L_end < 2: raise RuntimeError(f"episode {e['episode_id']}: only {L_end} records ({terminal})") stats = sim.stats() if initial_velocity is not None: info["initial_velocity"] = dict(e["initial_velocity"], base_angular_world_rad_s=list(initial_velocity["base_ang_vel"]), linear_velocity_origin="base_link_REF", applied_before_record0=True) info["study_initialization_family"] = e.get("study_initialization_family") info.update( terminal_capture=dict(version="finite_10ms_endpoint_v1", last_record=L_end - 1, last_interval_nonfoot=bool(L_end > 1 and rec.nonfoot[L_end - 2]), nonfoot_endpoint_retained=terminal == "nonfoot_contact", note="Finite nonfoot interval endpoint retained in raw data; export may exclude the nonfoot interval."), attempt=spec.attempt, terrain=terrain, build=build_id, soil=soil, read_window=list(window), threshold_n=threshold, overrides=dict(max_records=spec.max_records, command=spec.override_command, sigma_zero=spec.override_sigma_zero) if (spec.max_records or spec.override_command or spec.override_sigma_zero) else None, spawn=dict(build_stats={k: v for k, v in build_stats.items() if isinstance(v, (int, float, str, list))}, probe=sim.spawn_info or None), timing=dict(build_s=build_s, stand_wall_s=stand_wall, record_wall_s=rec_wall, loop_wall_s=loop_wall, sim_s=sim.time, record_sim_s=(L_end - 1) * C.RECORD_STEP_S, wall_per_sim_s=loop_wall / max(sim.time, 1e-9), steps=steps, cfd_s=stats.get("cfd_s"), mbd_s=stats.get("mbd_s"), fsi_s=stats.get("fsi_s"), total_s=time.perf_counter() - t_start), gpu=stats.get("gpu"), pd_calls_per_mbd_step=stats.get("pd_calls_per_mbd_step"), sph_particles=stats.get("sph_particles"), boundary_markers=stats.get("boundary_markers"), rotor_violation=float(sim.rotors.violation()) if sim.rotors is not None else None, nonfoot_records=int(rec.nonfoot[:L_end].sum()), nan_rejections=int(policy.nan_rejections), torque_clip=bool(spec.torque_clip), joint_limits=dict(mode=getattr(sim, "limit_params", None).mode if getattr(sim, "limit_params", None) else None, records_active=int((rec.limit_steps[:L_end] > 0).any(1).sum()), torque_max=float(rec.limit_torque[:L_end].max()), pen_max=float(rec.limit_pen[:L_end].max()), stand=rec.stand_limit), ) if relief is not None: # terrain_relief episodes only: meta block + diag arrays (relief.py) info["terrain_relief"] = dict(sim.relief_info, surface_probe=dict( relief.get("surface_probe") or {}, maps=len(surf_maps)) if probe_every else None) rec.relief_arrays = {} if sim.relief_dk is not None: rec.relief_arrays.update(relief_dk=sim.relief_dk.astype(np.int8), relief_lattice=np.array([sim.params.crm.spacing_m, -0.5 * bed[0], -0.5 * bed[1], sim.params.crm.depth_m])) if probe_every and surf_maps: rec.relief_arrays.update(surface_maps=np.stack(surf_maps), surface_index=np.asarray(surf_index, np.float64)) if lift is not None: # swing_lift episodes only: meta block (the per-step signal is in raw + diag) off = rec.lift_arrays["swing_lift_offset"][:L_end] info["swing_lift"] = dict(SL.summary(lift), records_active=int((np.abs(off).max(1) > 0).sum()), max_calf_offset_rad=float(-off[:, 2::3].min()) if len(off) else 0.0) ep = assemble(spec, rec, L_end, terminal, info, window, threshold) save_diag(spec.diag, rec, L_end, trace) save_episode(spec.out, ep, shard_meta) backend.close() return dict(status="ok", episode_id=int(e["episode_id"]), terminal_reason=terminal, length=L_end, **info)
def main(argv: list[str] | None = None) -> int: argv = sys.argv[1:] if argv is None else argv if len(argv) != 1: print("usage: python -m go2nrd.collect.chrono.episode SPEC.json", file=sys.stderr) return 2 spec = EpisodeSpec.load(argv[0]) try: summary = run_episode(spec) except Exception as exc: # noqa: BLE001 - recorded for the parent, which retries Path(spec.error).parent.mkdir(parents=True, exist_ok=True) Path(spec.error).write_text(json.dumps(dict(error=repr(exc), traceback=traceback.format_exc()), indent=1)) traceback.print_exc() return 2 print(json.dumps({k: summary[k] for k in ("episode_id", "terminal_reason", "length")} | dict( wall_per_sim_s=summary["timing"]["wall_per_sim_s"])), flush=True) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386"""Uneven initial CRM soil surface (terrain relief) for the Chrono collector: opt-in, default off.
New file (lateral_stuck_20261108 crm_collection_design, 2026-11-08). Nothing here runs unless a plan entry carries a``terrain_relief`` block; plans without it build the flat box bed exactly as before (``CollectorGo2Sim._build_crm``then calls the unchanged parent).
What this build of Chrono offers (Chrono f54254fa, ``ChFsiProblemCartesian::Construct`` overloads, the same commit onthe AMD HIP build, the Euler CUDA build and the local E19 copy):
* ``Construct(box_size, pos, side_flags)``: the flat bed of every earlier campaign;* ``Construct(heightmap_file, length, width, height_range, depth, uniform_depth, pos, side_flags)``: an image heightmap (bilinear, rounded to the particle grid);* ``Construct(sph_file, bce_file, pos, use_grid_coordinates)``: explicit particle / boundary-marker grid points.
This module uses the third one: the SPH grid points of the flat bed (identical ``Nx = round(px / s) + 1`` x``Ny`` x ``Nz`` lattice and identical offset ``(-px / 2, -py / 2, 0)``), with each column's top raised or lowered by``dk(i, j) = round(h(x_i, y_j) / s)`` particle layers, and the boundary BCE markers of ``AddBoxContainer`` for thesides X-, X+, Y-, Y+, Z- (``BoxSide_ALL & ~BoxSide_Z_POS``) written out point for point. The relief is forced to zerowithin ``edge_taper_m`` of the bed edge (so the walls are those of the flat bed) and inside ``flat_radius_m`` of thespawn (so the FixStand / hand-over happens on flat soil and the spawn clearance keeps its meaning).
Conventions kept: the bed bottom stays at z = 0, the NOMINAL surface stays the flat-bed top ``z = depth_m``(``sim.surface_z()``); the 37-state z and the foot heights in the diag file stay "above the nominal surface". On arelief bed the non-foot rule (base / hip / thigh geom in the soil ends the episode) uses the LOCAL initial top at thegeom centre, so a thigh cannot pass through a mound unnoticed (diag ``nonfoot_low`` is then local). The local initial surface is ``depth_m + dk * spacing``; the dk grid, its sha256, the drawnparameters and the seed are in ``RawEpisode.meta["terrain_relief"]`` and in the diag file (``relief_dk``), so an NRDcan be conditioned on it. Resolution: the particle spacing (0.02 m): reliefs are whole particle layers.
The relief h(x, y) (world metres) = clip((GRF + sum of features) * spawn_mask * edge_mask, -max_abs, max_abs):
* GRF: ``modes`` random cosine modes, |k| = 2 pi / wavelength * exp(N(0, 0.25^2)), uniform direction and phase, scaled to ``rms_m``; drawn at run time from PCG64(SeedSequence([seed, 0x5E1EF])) in a fixed order;* features (explicit in the plan): ``mound`` / ``dip`` Gaussian bumps (height_m signed, sigma_m) and ``berm`` ridges (height_m, width_m = Gaussian sigma across, length_m, angle_rad of the ridge axis, Gaussian end caps);* masks: smoothstep from 0 at the spawn radius to 1 at radius + blend; exactly 0 within 0.15 m of the bed edge, then a smoothstep to 1 over edge_taper_m.
Optional ``surface_probe`` ({"every_records", "half_box_m", "cell_m"}): the local surface (highest SPH particle percell, minus the nominal surface) around the base, read between steps (physics-neutral reads of particle positions);saved in the diag file (``surface_*``) to measure sand pushed into piles. Allowed on flat ("rms 0, no features")relief blocks as well; a flat block builds with the unchanged box ``Construct``."""
from __future__ import annotations
import hashlibimport inspectimport mathimport osimport shutilimport tempfileimport timefrom typing import Any
import numpy as np
RELIEF_SCHEMA = "go2nrd_crm_relief_v1"GRF_SALT = 0x5E1EFLEGACY_BUILD_SHA256 = "e9c63d098a3b017211f5e4dbf731c1ccefd20f56bf865972bb09e370acc05821""""sha256 of ``inspect.getsource(go2nrd.chrono_robot.build._build_crm_legacy_calf)`` that :func:`build_crm_relief`follows call for call (only the Construct call and the bounding-box check differ); checked at every relief build."""SPEC_KEYS = {"schema", "seed", "grf", "features", "flat_radius_m", "flat_blend_m", "edge_taper_m", "max_abs_m"}OPTIONAL_KEYS = {"grid_sha256", "surface_probe", "note", "draw"}FEATURE_KEYS = {"mound": {"kind", "x", "y", "height_m", "sigma_m"}, "dip": {"kind", "x", "y", "height_m", "sigma_m"}, "berm": {"kind", "x", "y", "height_m", "width_m", "length_m", "angle_rad"}}PROBE_KEYS = {"every_records", "half_box_m", "cell_m"}EDGE_ZERO_M = 0.15"""The relief is exactly zero within this distance of the bed edge (then a smoothstep over edge_taper_m)."""
# ====================================================================== specdef validate(spec: dict | None) -> dict | None: """Strict schema check of a plan entry's ``terrain_relief`` block (absent / None = flat bed, legacy).""" if spec is None: return None if not isinstance(spec, dict) or spec.get("schema") != RELIEF_SCHEMA: raise ValueError(f"terrain_relief must use schema {RELIEF_SCHEMA}") keys = set(spec) if not SPEC_KEYS <= keys or keys - SPEC_KEYS - OPTIONAL_KEYS: raise ValueError(f"terrain_relief keys {sorted(keys)}; need {sorted(SPEC_KEYS)} (+ {sorted(OPTIONAL_KEYS)})") grf = spec["grf"] if set(grf) != {"rms_m", "wavelength_m", "modes"} or grf["rms_m"] < 0 or grf["wavelength_m"] <= 0 \ or int(grf["modes"]) < 1: raise ValueError(f"terrain_relief.grf needs rms_m >= 0, wavelength_m > 0, modes >= 1: {grf}") for f in spec["features"]: want = FEATURE_KEYS.get(f.get("kind")) if want is None or set(f) != want: raise ValueError(f"terrain_relief feature {f}: kind mound|dip|berm with keys {want}") positive = f["kind"] in ("mound", "berm") if (positive and not float(f["height_m"]) > 0) or (not positive and not float(f["height_m"]) < 0): raise ValueError(f"terrain_relief feature {f}: mound / berm height > 0, dip height < 0") for k in ("flat_radius_m", "flat_blend_m", "edge_taper_m", "max_abs_m"): if not (math.isfinite(float(spec[k])) and float(spec[k]) >= 0): raise ValueError(f"terrain_relief.{k} must be finite and >= 0") if float(spec["edge_taper_m"]) < 0.2: raise ValueError("terrain_relief.edge_taper_m >= 0.2 m (the walls must stay those of the flat bed)") probe = spec.get("surface_probe") if probe is not None and (set(probe) != PROBE_KEYS or int(probe["every_records"]) < 1 or not 0 < float(probe["cell_m"]) <= float(probe["half_box_m"])): raise ValueError(f"terrain_relief.surface_probe needs {sorted(PROBE_KEYS)}: {probe}") return spec
def is_flat(spec: dict) -> bool: return float(spec["grf"]["rms_m"]) == 0.0 and not spec["features"]
def physics_block() -> dict: """``physics_config["terrain_relief"]`` (identical for every episode of a campaign whose entries carry a block).""" return dict(schema=RELIEF_SCHEMA, construct=( "ChFsiProblemCartesian::Construct(sph_file, bce_file, (-px/2, -py/2, 0), grid) with the flat-bed lattice and " "column tops shifted by dk = round(h / spacing) layers; AddBoxContainer walls/bottom written point for point; " "flat blocks use the unchanged box Construct"), nominal_surface="z = depth_m (flat-bed top); state z and diag foot z stay relative to it", nonfoot_rule=("relief beds: base / hip / thigh lowest point below the LOCAL initial soil top (nominal + dk * " "spacing at the geom centre) in any 1 ms exchange ends the episode; flat blocks: nominal top"), per_episode="RawEpisode.meta['terrain_relief'] (spec, seed, dk sha256, layer stats); diag relief_dk, surface_*")
# ====================================================================== the height fielddef _smoothstep(t: np.ndarray) -> np.ndarray: t = np.clip(t, 0.0, 1.0) return t * t * (3.0 - 2.0 * t)
def grf_modes(spec: dict) -> np.ndarray: """(M, 4) [kx, ky, phase, 1] of the GRF (fixed draw order: |k| factors, directions, phases).""" g = spec["grf"] m = int(g["modes"]) rng = np.random.Generator(np.random.PCG64(np.random.SeedSequence([int(spec["seed"]) % (1 << 64), GRF_SALT]))) kmag = 2.0 * math.pi / float(g["wavelength_m"]) * np.exp(0.25 * rng.standard_normal(m)) theta = rng.uniform(0.0, 2.0 * math.pi, m) phase = rng.uniform(0.0, 2.0 * math.pi, m) return np.stack([kmag * np.cos(theta), kmag * np.sin(theta), phase, np.ones(m)], 1)
def height(spec: dict, X: np.ndarray, Y: np.ndarray, bed: tuple[float, float], spawn: tuple[float, float]) -> np.ndarray: """h(x, y) in metres at world points (X, Y) of a bed (px, py) centred on the origin, spawn (x, y).""" X = np.asarray(X, np.float64) Y = np.asarray(Y, np.float64) h = np.zeros(np.broadcast(X, Y).shape) rms = float(spec["grf"]["rms_m"]) if rms > 0: modes = grf_modes(spec) acc = np.zeros_like(h) for kx, ky, ph, _ in modes: # fixed order: reproducible sums acc += np.cos(kx * X + ky * Y + ph) h += rms * math.sqrt(2.0 / len(modes)) * acc for f in spec["features"]: dx, dy = X - float(f["x"]), Y - float(f["y"]) if f["kind"] in ("mound", "dip"): s = float(f["sigma_m"]) h += float(f["height_m"]) * np.exp(-0.5 * (dx * dx + dy * dy) / (s * s)) else: a, w, half = float(f["angle_rad"]), float(f["width_m"]), 0.5 * float(f["length_m"]) u = dx * math.cos(a) + dy * math.sin(a) v = -dx * math.sin(a) + dy * math.cos(a) over = np.maximum(np.abs(u) - half, 0.0) h += float(f["height_m"]) * np.exp(-0.5 * (v * v + over * over) / (w * w)) r = np.hypot(X - spawn[0], Y - spawn[1]) blend = max(float(spec["flat_blend_m"]), 1e-9) h *= _smoothstep((r - float(spec["flat_radius_m"])) / blend) px, py = bed edge = np.minimum(np.minimum(X + 0.5 * px, 0.5 * px - X), np.minimum(Y + 0.5 * py, 0.5 * py - Y)) h *= _smoothstep((edge - EDGE_ZERO_M) / float(spec["edge_taper_m"])) # exactly 0 in the outer 0.15 m lim = float(spec["max_abs_m"]) return np.clip(h, -lim, lim)
def lattice(px: float, py: float, depth: float, spacing: float) -> dict: """The flat-bed lattice of ``ChFsiProblemCartesian::Construct(box)`` (std::round of positive values).""" rnd = lambda v: int(math.floor(v + 0.5)) # noqa: E731 nx, ny, nz = rnd(px / spacing) + 1, rnd(py / spacing) + 1, rnd(depth / spacing) + 1 return dict(nx=nx, ny=ny, nz=nz, spacing=float(spacing), offset=(-0.5 * px, -0.5 * py, 0.0))
def layer_grid(spec: dict, px: float, py: float, depth: float, spacing: float, spawn: tuple[float, float]) -> tuple[np.ndarray, dict]: """dk [nx, ny] int16 (particle layers added (> 0) / removed (< 0) at each lattice column) and the lattice.""" lat = lattice(px, py, depth, spacing) xs = spacing * np.arange(lat["nx"]) + lat["offset"][0] ys = spacing * np.arange(lat["ny"]) + lat["offset"][1] X, Y = np.meshgrid(xs, ys, indexing="ij") dk = np.rint(height(spec, X, Y, (px, py), spawn) / spacing).astype(np.int16) if dk.min() <= -(lat["nz"] - 3): raise ValueError(f"terrain_relief: a dip removes {int(-dk.min())} of {lat['nz']} layers") ring = max(2, int(math.ceil(0.1 / spacing))) border = np.ones_like(dk, bool) border[ring:-ring, ring:-ring] = False if np.any(dk[border] != 0): raise ValueError("terrain_relief: non-zero relief within 0.1 m of the bed edge (walls would not fit)") return dk, lat
def grid_sha256(dk: np.ndarray) -> str: a = np.ascontiguousarray(dk, np.int16) return hashlib.sha256(str(a.shape).encode() + a.tobytes()).hexdigest()
# ====================================================================== marker filesdef sph_points(dk: np.ndarray, nz: int) -> np.ndarray: """(N, 3) int32 lattice points: column (i, j) holds k = 0 .. nz - 1 + dk[i, j].""" nx, ny = dk.shape counts = (nz + dk.astype(np.int64)).ravel() ii, jj = np.meshgrid(np.arange(nx), np.arange(ny), indexing="ij") i = np.repeat(ii.ravel(), counts) j = np.repeat(jj.ravel(), counts) starts = np.repeat(np.cumsum(counts) - counts, counts) k = np.arange(int(counts.sum())) - starts return np.stack([i, j, k], 1).astype(np.int32)
def box_bce_points(nx: int, ny: int, nz: int, layers: int) -> np.ndarray: """(M, 3) int32 unique BCE points of ``AddBoxContainer`` with X-, X+, Y-, Y+, Z- (point for point).""" L = int(layers) parts = [] I, J, K = np.meshgrid(np.arange(nx), np.arange(ny), np.arange(-L, 0), indexing="ij") # z_neg parts.append(np.stack([I, J, K], -1).reshape(-1, 3)) kz = np.arange(-L, nz + L) for ix in (np.arange(-L, 0), nx - 1 - np.arange(-L, 0)): # x_neg, x_pos I, J, K = np.meshgrid(ix, np.arange(ny), kz, indexing="ij") parts.append(np.stack([I, J, K], -1).reshape(-1, 3)) for iy in (np.arange(-L, 0), ny - 1 - np.arange(-L, 0)): # y_neg, y_pos I, J, K = np.meshgrid(np.arange(-L, nx + L), iy, kz, indexing="ij") parts.append(np.stack([I, J, K], -1).reshape(-1, 3)) return np.unique(np.concatenate(parts).astype(np.int32), axis=0)
def _write_lines(path: str, pts: np.ndarray) -> int: """Write integer triples as fixed-width text lines ('%7d%7d%7d\\n', vectorised); returns bytes written.""" pts = np.asarray(pts, np.int64) if pts.size and (pts.min() <= -10 ** 5 or pts.max() >= 10 ** 6): raise ValueError("lattice index out of the fixed-width range") w = 7 n = len(pts) out = np.full((n, 3 * w + 1), ord(" "), np.uint8) out[:, -1] = ord("\n") for c in range(3): v = pts[:, c] a = np.abs(v) ndig = 1 + sum((a >= 10 ** d).astype(np.int64) for d in range(1, 6)) for d in range(6): # digit d from the right col = (c + 1) * w - 1 - d digit = (a // 10 ** d) % 10 on = d < ndig out[on, col] = (ord("0") + digit[on]).astype(np.uint8) neg = v < 0 out[neg, (c + 1) * w - 1 - ndig[neg]] = ord("-") with open(path, "wb") as fh: fh.write(out.tobytes()) return int(out.size)
# ====================================================================== the CRM builddef build_crm_relief(sim: Any, system: Any, bodies: Any, px: float, py: float, spec: dict) -> Any: """``go2nrd.chrono_robot.build._build_crm_legacy_calf`` with the relief Construct (see the module docstring).
Call for call the same as the pinned source (:data:`LEGACY_BUILD_SHA256`) except: the SPH / BCE lattice comes from files written here, and the bounding-box check allows the relief's highest column. A flat block (rms 0, no features) must not come here (the scene uses the unchanged box build).""" import pychrono.fsi as fsi import pychrono.vehicle as veh
from go2nrd.chrono_robot import build as B from legged_sim_eval.backends.chrono_backend import CALF_BODIES, FOOT_BODIES, BackendError, crm_api
got = hashlib.sha256(inspect.getsource(B._build_crm_legacy_calf).encode()).hexdigest() if got != LEGACY_BUILD_SHA256: raise RuntimeError(f"_build_crm_legacy_calf changed ({got}); re-check build_crm_relief against it") if not sim.legacy_calf_fsi: raise RuntimeError("terrain_relief needs legacy_calf_fsi (the collector default)") t0 = time.perf_counter() ch, c = sim.chrono, sim.params.crm spawn = tuple(getattr(sim, "relief_spawn_xy", (0.0, 0.0))) dk, lat = layer_grid(spec, px, py, c.depth_m, c.spacing_m, spawn) sha = grid_sha256(dk) # plan-time sha256 of the same grid: a mismatch (different code / numpy / libm) is recorded, not fatal; the # grid that was actually built is saved in the diag file (relief_dk) and its sha256 in the episode meta sha_match = None if not spec.get("grid_sha256") else bool(spec["grid_sha256"] == sha)
names = crm_api(fsi, veh) terrain = veh.CRMTerrain(system, c.spacing_m) terrain.SetVerbose(False) terrain.SetGravitationalAcceleration(system.GetGravitationalAcceleration()) terrain.SetStepSizeCFD(c.cfd_step_s) soil = getattr(fsi, names["soil_properties"])() soil.density = c.soil.density soil.Young_modulus = c.soil.young_modulus_pa soil.Poisson_ratio = c.soil.poisson_ratio soil.mu_I0 = c.soil.mu_i0 soil.mu_fric_s = c.soil.friction soil.mu_fric_2 = c.soil.friction soil.average_diam = c.soil.average_diam_m soil.cohesion_coeff = c.soil.cohesion_pa getattr(terrain, names["set_soil"])(soil) sph = fsi.SPHParameters() sph.integration_scheme = getattr(fsi, f"IntegrationScheme_{c.integration}") sph.initial_spacing = c.spacing_m sph.d0_multiplier = c.d0_multiplier sph.free_surface_threshold = c.free_surface_threshold sph.artificial_viscosity = c.artificial_viscosity sph.shifting_method = fsi.ShiftingMethod_NONE sph.viscosity_method = fsi.ViscosityMethod_ARTIFICIAL_BILATERAL sph.boundary_method = fsi.BoundaryMethod_ADAMI terrain.SetSPHParameters(sph) foot = ch.ChBodyGeometry() foot.coll_spheres.append(ch.SphereShape(ch.VNULL, c.foot_radius_m)) pairs = [(name, foot) for name in FOOT_BODIES] if c.calf_fsi: offsets = B.calf_fsi_offsets(sim.urdf.path) sim.calf_fsi_centres = {} for name in CALF_BODIES: off = offsets[name.split("_")[0]] calf = ch.ChBodyGeometry() calf.coll_cylinders.append( ch.CylinderShape(ch.ChVector3d(*off), ch.QUNIT, c.calf_radius_m, c.calf_length_m) ) sim.calf_fsi_centres[name] = off pairs.append((name, calf)) for name, geometry in pairs: terrain.AddRigidBody(bodies[name], geometry, False) if c.active_domain_m is not None: d = float(c.active_domain_m) terrain.SetActiveDomain(ch.ChVector3d(d, d, d)) getattr(terrain, names["set_active_domain_delay"])(c.active_domain_delay_s) # ---- the one replaced call: the relief lattice instead of Construct(box, origin, ALL & ~Z_POS) layers = int(terrain.GetFluidSystemSPH().GetNumBCELayers()) sph_pts = sph_points(dk, lat["nz"]) bce_pts = box_bce_points(lat["nx"], lat["ny"], lat["nz"], layers) work = tempfile.mkdtemp(prefix="crm_relief_") try: f_sph, f_bce = os.path.join(work, "sph.txt"), os.path.join(work, "bce.txt") nbytes = _write_lines(f_sph, sph_pts) + _write_lines(f_bce, bce_pts) t_files = time.perf_counter() - t0 terrain.Construct(f_sph, f_bce, ch.ChVector3d(-0.5 * px, -0.5 * py, 0.0), True) finally: shutil.rmtree(work, ignore_errors=True) # ---- unchanged fluid = terrain.GetFluidSystemSPH() if hasattr(fluid, "EnableCudaErrorCheck"): fluid.EnableCudaErrorCheck(bool(c.cuda_error_check)) if c.output_level is not None and hasattr(terrain, "SetOutputLevel"): terrain.SetOutputLevel(getattr(fsi, f"OutputLevel_{c.output_level}")) terrain.Initialize() box = terrain.GetSPHBoundingBox() top = c.depth_m + c.spacing_m * max(0, int(dk.max())) want = (-0.5 * px, -0.5 * py, 0.0, 0.5 * px, 0.5 * py, top) # relief: the highest column's top found = (box.min.x, box.min.y, box.min.z, box.max.x, box.max.y, box.max.z) if any(abs(a - b) > 2.0 * c.spacing_m for a, b in zip(want, found, strict=True)): raise BackendError(f"the CRM relief bed is not where it was asked for: {found} vs {want}") mbd = terrain.GetFsiSystemSPH().GetStepSizeMBD() if abs(mbd - sim.mbd_dt) > 1e-12: raise BackendError(f"CRM MBD step is {mbd}, expected {sim.mbd_dt}") n_sph = int(terrain.GetNumSPHParticles()) if n_sph != len(sph_pts): raise BackendError(f"CRM relief: {n_sph} SPH particles built, {len(sph_pts)} written") flat_n = lat["nx"] * lat["ny"] * lat["nz"] sim.relief_dk = dk sim.relief_origin = (lat["offset"][0], lat["offset"][1], float(c.spacing_m)) # non-foot rule: local surface sim.relief_info = dict( spec=spec, grid_sha256=sha, grid_sha256_matches_plan=sha_match, lattice=dict(lat, offset=list(lat["offset"])), bce_layers=layers, layers_added=int(dk[dk > 0].sum()), layers_removed=int(-dk[dk < 0].sum()), dk_min=int(dk.min()), dk_max=int(dk.max()), columns_raised=int((dk > 0).sum()), columns_lowered=int((dk < 0).sum()), relief_rms_m=float(c.spacing_m * np.sqrt(np.mean(dk.astype(float) ** 2))), sph_particles=n_sph, flat_bed_particles=int(flat_n), bce_markers=int(terrain.GetNumBoundaryBCEMarkers()), bce_written=int(len(bce_pts)), file_bytes=nbytes, files_s=t_files, build_s=time.perf_counter() - t0, spawn_xy=list(spawn), sph_bbox=list(found), construct="sph_bce_files") return terrain
# ====================================================================== surface probedef surface_map(sim: Any, half_box: float, cell: float) -> tuple[np.ndarray, tuple[float, float, float]]: """(G, G) float16 highest particle centre per cell minus the nominal surface (NaN = no particle) around the base COM (x, y), and (x0, y0, t) of the map's lower-left corner and the sim time. Read only.""" pos = sim.particles(half_box) base = sim.base.GetPos() x0, y0 = float(base.x) - half_box, float(base.y) - half_box g = int(round(2 * half_box / cell)) out = np.full(g * g, -np.inf) if len(pos): ix = np.clip(((pos[:, 0] - x0) / cell).astype(np.int64), 0, g - 1) iy = np.clip(((pos[:, 1] - y0) / cell).astype(np.int64), 0, g - 1) np.maximum.at(out, ix * g + iy, pos[:, 2] - sim.surface_z()) out[~np.isfinite(out)] = np.nan return out.reshape(g, g).astype(np.float16), (x0, y0, float(sim.time))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349"""Chrono collection of one plan shard: resumable per episode, one subprocess per episode attempt.
New file (go2nrd Chrono collector builder, 2026-10-29). The isolation / retry idea follows legged_sim_eval``runner.py`` (``--isolate``, ``--attempts``; ``/home/harry/go2_sand/legged_rl_deploy/sim_eval``, read-only); the codeis new.
python -B -m go2nrd.collect.chrono.run --campaign crm_prod --shard 3 --out /scratch/.../collect/crm_prod [--episodes 0:10 | --episodes 2] [--terrain crm|rigid] [--attempts 3] [--max-seconds 8] [--episode-ids 11000016,11000021] [--trace-fsi] [--threshold-n 5] [--no-isolate] ... [--soil cohesion_pa=1000 --soil friction=1.0] [--soil-map map.json] [--torque-clip on] [--backend-opt joint_limits=off] [--policy DEPLOY_FOLDER]
Physics of the collector (fix_chrono, 2026-10-30): torqueClip off unless ``--torque-clip on`` (the PD law'sper-MBD-step actuator clamp stays); the robot's MuJoCo soft joint limits (``go2nrd.chrono_robot.limits``; backendoption ``joint_limits=mujoco|mujoco_pd|off``).
Policy (round_tools, 2026-10-30): ``--policy FOLDER`` (a deploy folder of go2nrd.eval.export_onnx, e.g. a PPOfine-tune of the mjlab actor) replaces the mjlab policy's ONNX; the deploy settings stay those of ``--config`` /``--command-clip`` (go2nrd.collect.chrono.deploy.with_policy_folder; the folder's config.yaml must agree with them).Absent: the mjlab policy, as before. Every raw shard meta has a ``policy`` block (ONNX file, sha256, default flag,folder, exported checkpoint); every marker has ``policy_sha256``. A shard directory whose markers name another policyis refused (``--allow-mixed-policy`` overrides; markers without the key count as the default policy).
CRM soil (go2nrd.collect.chrono.soil): ``--soil KEY=VALUE`` sets the campaign base (keys cohesion_pa, friction =mu_s = mu_2, density, young_modulus_pa; defaults = the evaluator's soil); the plan entry's ``soil`` dict and the``--soil-map`` JSON (``{"episodes": {"<id>": {...}}}``, e.g. from ``python -m go2nrd.collect.chrono.soil make-map``)set per-episode values. Each episode's values are in its RawEpisode meta, its raw shard meta and its marker.
Outputs (all below ``OUT/shard_<SSS>/``, so the cluster templates sync only this shard's paths):
* ``ep_<episode_id>.npz`` -- a raw shard (``contract.save_raw_shard``) holding that one episode: the export reads ``--raw OUT/shard_000 OUT/shard_001 ...`` (it globs ``*.npz`` in each directory, not below);* ``ep_<episode_id>.json`` -- the commit marker: status ``ok`` | ``fsi_abort`` | ``failed``, attempts, timing. An episode with a marker is skipped on a rerun (``--retry-failed`` reruns ``failed`` ones);* ``diag/ep_<id>.npz`` -- per-step force reads (z of the 8 FSI bodies / 4 feet + base), COM, feet, torqueClip feed-forward (``--trace-fsi``: full force vectors, FSI torques, robot momentum per step);* ``partial/``, ``work/``, ``logs/`` -- attempt files (partials are flushed every 100 records by the child).
Attempts: a child that exits 0 with its output is a success. A child that dies otherwise (CUDA / FSI abort, signal,or a Python error) is retried up to ``--attempts`` times. If every attempt failed and at least one died withrecords flushed, the longest partial becomes the episode with ``terminal_reason = fsi_abort`` (the records beforethe abort kept); else the marker says ``failed``. Exit 0 = every selected episode has a marker; 143 = SIGTERM (therunning child is stopped; its episode reruns from the start next time); 1 = a parent error; ``--strict``: 3 if anyepisode ended ``failed``."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport osimport signalimport socketimport subprocessimport sysimport timefrom pathlib import Path
import numpy as np
from go2nrd.collect.chrono import soil as Sfrom go2nrd.collect.common import contract as Cfrom go2nrd.collect.common.plan import PlanArrays, load_planfrom go2nrd.collect.chrono.episode import (COLLECTOR_NAME, COLLECTOR_VERSION, EpisodeSpec, category_of, run_episode)
HERE = Path(__file__).resolve().parentDONE = ("ok", "fsi_abort", "failed")_STOP = {"flag": False, "child": None}
def code_sha256() -> str: h = hashlib.sha256() for p in sorted(HERE.glob("*.py")): h.update(p.name.encode()) h.update(p.read_bytes()) return h.hexdigest()
def _on_term(signum, frame): # noqa: ARG001 _STOP["flag"] = True child = _STOP["child"] if child is not None and child.poll() is None: child.terminate()
def select(plan: dict, shard: int, episodes: str | None, ids: str | None) -> list[dict]: if ids: want = [int(v) for v in ids.split(",") if v.strip()] by_id = {e["episode_id"]: e for e in plan["episodes"]} return [by_id[i] for i in want] rows = sorted((e for e in plan["episodes"] if e["shard"] == shard), key=lambda e: e["shard_slot"]) if not episodes: return rows if ":" in episodes: a, b = episodes.split(":") return rows[int(a or 0):int(b) if b else None] return rows[: int(episodes)]
def write_json(path: Path, obj: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name(path.name + ".tmp") tmp.write_text(json.dumps(obj, indent=1, allow_nan=True, default=str)) os.replace(tmp, path)
def _partial_length(path: Path) -> int: try: with np.load(path) as f: return int(f["rec_offsets"][-1]) except Exception: # noqa: BLE001 - a missing / unreadable partial counts as none return 0
def run_one(entry: dict, arrays: dict, args: argparse.Namespace, shard_dir: Path, shard_meta: dict) -> dict: eid = int(entry["episode_id"]) final = shard_dir / f"ep_{eid}.npz" marker = shard_dir / f"ep_{eid}.json" attempts = [] t0 = time.time() for k in range(1, args.attempts + 1): spec = EpisodeSpec( campaign=args.campaign, entry=entry, commands=np.asarray(arrays["commands"]).tolist(), injection=np.asarray(arrays["injection"]).tolist(), terrain=args.terrain, out=str(final), partial=str(shard_dir / "partial" / f"ep_{eid}.a{k}.npz"), diag=str(shard_dir / "diag" / f"ep_{eid}.npz"), error=str(shard_dir / "work" / f"ep_{eid}.a{k}.error.json"), attempt=k, max_records=(int(round(args.max_seconds / C.RECORD_STEP_S)) + 1) if args.max_seconds else None, override_command=[float(v) for v in args.override_command.split(",")] if args.override_command else None, override_sigma_zero=bool(args.sigma_zero), trace_fsi=bool(args.trace_fsi), threshold_n=args.threshold_n, read_window=args.read_window, config=args.config, command_clip=args.command_clip, torque_clip=args.torque_clip == "on", flush_every=args.flush_every, backend_options=dict(args.backend_opt), shard_meta=shard_meta, soil_campaign=dict(args.soil), soil_episode=args.soil_map.get(eid), policy=args.policy) spec_path = shard_dir / "work" / f"ep_{eid}.a{k}.spec.json" for stale in (Path(spec.error), Path(spec.partial), final): # leftovers of a stopped earlier run stale.unlink(missing_ok=True) spec.save(spec_path) log = shard_dir / "logs" / f"ep_{eid}.a{k}.log" log.parent.mkdir(parents=True, exist_ok=True) ta = time.time() if args.no_isolate: try: run_episode(spec) rc = 0 except Exception as exc: # noqa: BLE001 Path(spec.error).write_text(json.dumps(dict(error=repr(exc)))) rc = 2 else: env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1") with open(log, "w") as fh: child = subprocess.Popen([args.python, "-B", "-m", "go2nrd.collect.chrono.episode", str(spec_path)], stdout=fh, stderr=subprocess.STDOUT, env=env, cwd=str(shard_dir)) _STOP["child"] = child rc = child.wait() _STOP["child"] = None if _STOP["flag"]: return dict(status="stopped", episode_id=eid) err = Path(spec.error) kind = "ok" if (rc == 0 and final.exists()) else ("error" if err.exists() else "abort") rec = dict(attempt=k, rc=rc, kind=kind, wall_s=time.time() - ta, log=str(log), partial_records=_partial_length(Path(spec.partial)) if kind == "abort" else 0) if err.exists(): rec["error"] = json.loads(err.read_text()).get("error") attempts.append(rec) print(f"[ep {eid}] attempt {k}: {kind} rc={rc} {rec['wall_s']:.1f} s" + (f" ({rec.get('error')})" if kind == "error" else ""), flush=True) if kind == "ok": with np.load(final) as f: head = json.loads(str(f["episodes_json"]))[0] soil = head["meta"].get("soil") or {} out = dict(status="ok", episode_id=eid, family=entry["family"], terminal_reason=head["terminal_reason"], length=head["length"], attempts=attempts, wall_s=time.time() - t0, host=socket.gethostname(), timing=head["meta"].get("timing"), build=head["meta"].get("build"), soil=soil.get("values"), soil_source=soil.get("source"), policy_sha256=args.policy_sha256) write_json(marker, out) for p in (shard_dir / "partial").glob(f"ep_{eid}.a*.npz"): p.unlink() return out aborts = [a for a in attempts if a["kind"] == "abort" and a["partial_records"] >= 2] if aborts: best = max(aborts, key=lambda a: a["partial_records"]) part = shard_dir / "partial" / f"ep_{eid}.a{best['attempt']}.npz" eps, meta = C.load_raw_shard(part) ep = eps[0] ep.terminal_reason = "fsi_abort" ep.meta.update(partial=False, fsi_abort=dict(attempts=attempts, kept_attempt=best["attempt"])) C.save_raw_shard(final, [ep], meta) soil = ep.meta.get("soil") or {} out = dict(status="fsi_abort", episode_id=eid, family=entry["family"], terminal_reason="fsi_abort", length=ep.length, attempts=attempts, wall_s=time.time() - t0, host=socket.gethostname(), soil=soil.get("values"), soil_source=soil.get("source"), policy_sha256=args.policy_sha256) else: out = dict(status="failed", episode_id=eid, family=entry["family"], attempts=attempts, wall_s=time.time() - t0, host=socket.gethostname(), policy_sha256=args.policy_sha256) write_json(marker, out) return out
def run_policy_sha256(args: argparse.Namespace) -> str | None: """sha256 of this run's policy ONNX (the --policy folder's, or the default config's model; None if the default model cannot be resolved here, e.g. without legged_sim_eval). Also sets args.default_policy_sha256.""" from go2nrd.collect.chrono.deploy import CONFIG_NAMES, policy_dir, resolve_policy_folder
args.default_policy_sha256 = None try: from legged_sim_eval.config import load_deploy_config
base = load_deploy_config(Path(args.config) if args.config else policy_dir() / CONFIG_NAMES[args.command_clip]) args.default_policy_sha256 = base.model_sha256 or None except Exception: # noqa: BLE001 - informational in the parent; the child loads it for real pass if args.policy: return resolve_policy_folder(args.policy)["sha256"] # raises on a folder that is not a deploy folder return args.default_policy_sha256
def marker_policies(shard_dir: Path, sha: str | None, default_sha: str | None) -> list[str]: """Policy sha256 of the existing markers of shard_dir that differ from sha (markers without policy_sha256 were written before the --policy option: the default policy).""" if sha is None or not shard_dir.exists(): return [] seen = set() for m in shard_dir.glob("ep_*.json"): try: got = json.loads(m.read_text()).get("policy_sha256", default_sha) except (OSError, json.JSONDecodeError): continue if got is not None and got != sha: seen.add(got) return sorted(seen)
def parse_backend_opt(items: list[str]) -> list[tuple[str, object]]: out = [] for item in items: key, _, value = item.partition("=") try: v: object = json.loads(value) except json.JSONDecodeError: v = value out.append((key, v)) return out
def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--campaign", required=True, help="campaign name or plan JSON path") ap.add_argument("--shard", type=int, default=0) ap.add_argument("--episodes", help="slot range i:j of the shard, or a count N (= 0:N)") ap.add_argument("--episode-ids", help="comma-separated episode ids (overrides --shard selection)") ap.add_argument("--terrain", choices=("crm", "rigid"), help="default: the plan's category") ap.add_argument("--out", type=Path, required=True) ap.add_argument("--attempts", type=int, default=3) ap.add_argument("--max-seconds", type=float, help="truncate episodes (smoke tests / pilots)") ap.add_argument("--override-command", help="vx,vy,wz for every control step (pilot: standing still)") ap.add_argument("--sigma-zero", action="store_true", help="no OU injection (pilot)") ap.add_argument("--trace-fsi", action="store_true", help="diag: full per-step force vectors, torques, momentum") ap.add_argument("--threshold-n", type=float, help="label threshold (default: episode.CONTACT_THRESHOLD_N)") ap.add_argument("--read-window", type=lambda v: [int(x) for x in v.split(",")], metavar="LO,HI", help="force read window (default: episode.FORCE_READ_WINDOW, CRM 2,1, rigid 0,0)") ap.add_argument("--config", help="deploy config (default: config_noclip.yaml, see deploy.py)") ap.add_argument("--policy", help="deploy folder of go2nrd.eval.export_onnx (its ONNX replaces the mjlab policy's)") ap.add_argument("--allow-mixed-policy", action="store_true", help="run into a shard directory whose markers name another policy") ap.add_argument("--command-clip", choices=("none", "deploy"), default="none") ap.add_argument("--torque-clip", choices=("off", "on"), default="off", help="deploy torqueClip (default off: NRD_PLAN.md section 10; the judge path keeps it on)") ap.add_argument("--flush-every", type=int, default=100) ap.add_argument("--backend-opt", action="append", default=[], metavar="KEY=VALUE") ap.add_argument("--soil", action="append", default=[], metavar="KEY=VALUE", help="CRM campaign base soil: cohesion_pa, friction (= mu_s = mu_2), density, young_modulus_pa") ap.add_argument("--soil-map", type=Path, help='per-episode soil JSON {"episodes": {"<id>": {"cohesion_pa": ...}}}') ap.add_argument("--no-isolate", action="store_true", help="run episodes in this process (rigid smoke tests)") ap.add_argument("--retry-failed", action="store_true") ap.add_argument("--strict", action="store_true") ap.add_argument("--python", default=sys.executable) args = ap.parse_args(argv) args.backend_opt = parse_backend_opt(args.backend_opt) args.soil = S.normalize(dict(parse_backend_opt(args.soil)), "--soil") soil_map_path = args.soil_map args.soil_map, soil_map_sha = S.load_map(soil_map_path)
signal.signal(signal.SIGTERM, _on_term) plan = load_plan(args.campaign) given = Path(args.campaign) side = given.parent / f"{plan['campaign']}_arrays.npz" if given.suffix == ".json" else None plan_dir = given.parent if (side is not None and side.exists()) else None # arrays next to a plan JSON path args.campaign = plan["campaign"] args.terrain = args.terrain or plan["category"] rows = select(plan, args.shard, args.episodes, args.episode_ids) if not rows: print(f"no episodes in shard {args.shard} of {args.campaign}", file=sys.stderr) return 1 shard_dir = args.out / f"shard_{args.shard:03d}" args.policy = str(Path(args.policy).resolve()) if args.policy else None args.policy_sha256 = run_policy_sha256(args) mixed = marker_policies(shard_dir, args.policy_sha256, args.default_policy_sha256) if mixed and not args.allow_mixed_policy: print(f"{shard_dir}: markers of other policies {mixed}; this run's policy is {args.policy_sha256} " f"({args.policy or 'default'}). Use another --out or --allow-mixed-policy", file=sys.stderr) return 1 print(f"policy {args.policy or 'default (mjlab policy)'} sha256 {str(args.policy_sha256)[:16]}...", flush=True) shard_dir.mkdir(parents=True, exist_ok=True) shard_meta = dict(campaign=args.campaign, category=category_of(args.terrain), collector=dict(name=COLLECTOR_NAME, version=COLLECTOR_VERSION, code_sha256=code_sha256())) if soil_map_path: shard_meta["soil_map"] = dict(file=Path(soil_map_path).name, sha256=soil_map_sha) if args.terrain == "crm": # fail before any GPU time on a bad soil key / value / plan-map conflict backend_soil = S.split_backend_options(dict(args.backend_opt))[1] for entry in rows: S.resolve(entry, args.soil, args.soil_map.get(int(entry["episode_id"])), backend_soil) arrays = PlanArrays(plan) if plan_dir is None else PlanArrays(plan, plan_dir=plan_dir) summary_path = shard_dir / "shard.json" results = [] t0 = time.time() print(f"{args.campaign} shard {args.shard}: {len(rows)} episodes, terrain {args.terrain}, out {shard_dir}", flush=True) for entry in rows: eid = int(entry["episode_id"]) marker = shard_dir / f"ep_{eid}.json" if marker.exists(): prev = json.loads(marker.read_text()) if prev.get("status") in DONE and not (args.retry_failed and prev.get("status") == "failed"): results.append(prev) continue out = run_one(entry, arrays(eid), args, shard_dir, shard_meta) if out["status"] == "stopped": print(f"SIGTERM: stopped at episode {eid}", flush=True) return 143 results.append(out) print(f"[ep {eid}] {out['status']} {out.get('terminal_reason', '')} length {out.get('length')} " f"({out['wall_s']:.1f} s)", flush=True) write_json(summary_path, dict(campaign=args.campaign, shard=args.shard, terrain=args.terrain, selected=len(rows), done=len(results), wall_s=time.time() - t0, status={s: sum(r.get("status") == s for r in results) for s in DONE}, complete=False)) if _STOP["flag"]: return 143 status = {s: sum(r.get("status") == s for r in results) for s in DONE} write_json(summary_path, dict(campaign=args.campaign, shard=args.shard, terrain=args.terrain, selected=len(rows), done=len(results), wall_s=time.time() - t0, status=status, complete=True)) print(f"shard {args.shard} complete: {status}", flush=True) return 3 if (args.strict and status["failed"]) else 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Structured SWING-LIFT perturbation of the teacher's joint targets (lateral_stuck_20261108, opt-in, default off).
New file (lateral_stuck_20261108 track A, 2026-11-08). A plan entry with a ``swing_lift`` block makes the Chronocollector (:mod:`go2nrd.collect.chrono.episode`) add, at every control step, an offset to the HighController jointtarget of each leg that is in its SWING phase. The offset folds the leg (extra calf flexion and some thighflexion), so the commanded foot rises. It is added next to the plan's OU target noise (``InjectingLowLevel.injection``,motor order), before ``torqueClip`` and the float32 LowCmd rounding, so the recorded ``action`` (the target the PD lawgets) contains it. Entries without the key run exactly as before (no new arrays, no new meta keys).
Swing detection (causal, no future information): the teacher's own gait clock. The mjlab actor observes the phase``[sin, cos](2 pi gp)``, ``gp = fmod(k * 0.02, 0.6) / 0.6`` with ``k`` = the policy step counter of the observation(legged_sim_eval ``DeployPolicy._gait_phase``; zero when ``||command|| < 0.1``, then the teacher stands). The legschedule of the trained teacher was measured on the exports rigid_prod_v2 and crm_prod(``studies/lateral_stuck_20261108/collect/phase_calibration.json``): a trot, FR + RL off the ground forgp in about [0.03, 0.50] (apex 0.28-0.32), FL + RR for gp in about [0.53, 1.0] (apex 0.78-0.82). So leg ``j`` is inswing for ``s = ((gp - LEG_PHASE_OFFSET[j] - swing_start) mod 1) / swing_length`` in [0, 1); the bump is``sin(pi s)^2`` (zero at lift-off and touch-down, peak in mid swing). The default window starts 0.03 earlier than themeasured lift-off (PD lag of about one control step), so the commanded peak (gp 0.23 / 0.73) leads the natural apex.
Offset of leg j at control step c (policy joint order FL FR RL RR x hip thigh calf, rad)::
a = A_h * ramp_h(c) * sin(pi s_j)^2 (A_h: amplitude of the active hold h, ramp: 0.5 - 0.5 cos in/out) thigh += thigh_per_calf * a ; calf -= a (hip unchanged)
``thigh_per_calf`` = 0.5 keeps the foot's x unchanged at the default pose (go2nrd.policy.fk: calf -0.2 rad andthigh +0.1 rad raise the foot by 34.5 mm with 0.0 mm x change; 0.17 m per rad of calf). The offset is constant overthe control step (both 5 ms ticks of each of its two records), like the OU injection.
Block schema (``SWING_LIFT_SCHEMA``)::
{"schema": "go2nrd_swing_lift_v1", "holds": [{"start_step": a, "end_step": b, "amp_rad": A}, ...], "swing_start": 0.0, "swing_length": 0.46, "thigh_per_calf": 0.5, "ramp_s": 0.3, ...}
``holds`` are control-step ranges [a, b) (20 ms steps of the plan's command grid); an empty list = a control episodethat carries the block (same physics_config) and gets no offset."""
from __future__ import annotations
import math
import numpy as np
SWING_LIFT_SCHEMA = "go2nrd_swing_lift_v1"PERIOD_S = 0.6STEP_DT = 0.02COMMAND_THRESHOLD = 0.1LEG_PHASE_OFFSET = (0.5, 0.0, 0.0, 0.5)"""Phase offset of FL, FR, RL, RR (policy order): FR + RL swing first (gp 0.03-0.50), FL + RR half a period later."""DEFAULTS = dict(swing_start=0.0, swing_length=0.46, thigh_per_calf=0.5, ramp_s=0.3)MAX_AMP_RAD = 0.5
def validate(block: dict) -> dict: """The normalised block (defaults filled in); raises ValueError on a malformed one.""" if not isinstance(block, dict) or block.get("schema") != SWING_LIFT_SCHEMA: raise ValueError(f"swing_lift: schema must be {SWING_LIFT_SCHEMA!r}") out = dict(DEFAULTS) out.update(block) for k in DEFAULTS: out[k] = float(out[k]) if not (0.05 <= out["swing_length"] <= 1.0) or not (0.0 <= out["swing_start"] < 1.0): raise ValueError("swing_lift: swing_start in [0, 1), swing_length in [0.05, 1]") if not (0.0 <= out["thigh_per_calf"] <= 2.0) or out["ramp_s"] < 0.0: raise ValueError("swing_lift: thigh_per_calf in [0, 2], ramp_s >= 0") holds = [] last = -1 for h in out.get("holds", []): a, b, amp = int(h["start_step"]), int(h["end_step"]), float(h["amp_rad"]) if a < 0 or b <= a or a < last or not (0.0 <= amp <= MAX_AMP_RAD): raise ValueError(f"swing_lift: bad hold {h} (ordered, non-overlapping, 0 <= amp <= {MAX_AMP_RAD})") holds.append(dict(h, start_step=a, end_step=b, amp_rad=amp)) last = b out["holds"] = holds return out
def envelope(block: dict, c: int) -> float: """Amplitude (rad) at control step c: the active hold's amp times a smooth (0.5 - 0.5 cos) ramp of ramp_s at both ends of the hold; 0 outside the holds.""" n = max(1, int(round(block["ramp_s"] / STEP_DT))) for h in block["holds"]: a, b = h["start_step"], h["end_step"] if a <= c < b: u = min(1.0, (c - a + 0.5) / n, (b - c - 0.5) / n) return float(h["amp_rad"]) * (0.5 - 0.5 * math.cos(math.pi * max(0.0, u))) return 0.0
def gait_phase(k: int) -> float: """gp of the policy observation with step counter k (``DeployPolicy._gait_phase``, double).""" return math.fmod(int(k) * STEP_DT, PERIOD_S) / PERIOD_S
def leg_weights(block: dict, k: int) -> np.ndarray: """[4] swing bump sin(pi s)^2 of FL FR RL RR at policy step k (0 in stance).""" gp = gait_phase(k) w = np.zeros(4) for j, off in enumerate(LEG_PHASE_OFFSET): s = ((gp - off - block["swing_start"]) % 1.0) / block["swing_length"] if 0.0 <= s < 1.0: w[j] = math.sin(math.pi * s) ** 2 return w
def moving(command) -> bool: """The policy's phase gate: ||command|| >= 0.1 (norm accumulated in double from the float32 components).""" sq = 0.0 for v in np.asarray(command, np.float32).reshape(-1)[:3]: sq += float(v) * float(v) return math.sqrt(sq) >= COMMAND_THRESHOLD
def offset(block: dict, k: int, command, c: int) -> tuple[np.ndarray, np.ndarray, float]: """(offset [12] policy order rad, leg weights [4], envelope rad) at control step c, policy step counter k.""" out = np.zeros(12) env = envelope(block, c) if moving(command) else 0.0 if env == 0.0: return out, np.zeros(4), 0.0 w = leg_weights(block, k) for j in range(4): a = env * w[j] out[3 * j + 1] = block["thigh_per_calf"] * a out[3 * j + 2] = -a return out, w, env
def recompute(block: dict, phase_k: np.ndarray, command: np.ndarray) -> np.ndarray: """[L, 12] offsets of a recorded episode from its raw ``phase_k`` and ``command`` (audit of the diag/raw arrays; record r belongs to control step r // 2, whose offset was computed at its even record; the terminal record L-1 has no interval of its own and repeats record L-2, like its action).""" block = validate(block) L = len(phase_k) out = np.zeros((L, 12)) for r in range(0, L, 2): out[r] = offset(block, int(phase_k[r]), command[r], r // 2)[0] if r + 1 < L: out[r + 1] = out[r] if L >= 2: out[L - 1] = out[L - 2] return out
def physics_block() -> dict: """Campaign-constant physics_config entry of collections whose entries carry a swing_lift block.""" return dict(schema=SWING_LIFT_SCHEMA, module="go2nrd.collect.chrono.swing_lift", rule=("per control step, if ||command|| >= 0.1 and a plan hold is active: leg j in swing (teacher gait " "clock gp = fmod(k*0.02, 0.6)/0.6, leg offsets FL 0.5 FR 0 RL 0 RR 0.5, window [swing_start, " "swing_start + swing_length)) gets calf -= A ramp sin(pi s)^2 and thigh += thigh_per_calf * that; " "added to the HighController target with the OU injection, before torqueClip and float32 LowCmd; " "recorded action contains it"), leg_phase_offset=list(LEG_PHASE_OFFSET), period_s=PERIOD_S, command_threshold=COMMAND_THRESHOLD, raw_per_record="swing_lift [L, 12] policy order (rad)", diag=["swing_lift_offset", "swing_lift_weight", "swing_lift_env", "swing_lift_k", "injection_applied"])
def summary(block: dict) -> dict: """Meta block of an episode.""" return dict(schema=block["schema"], holds=block["holds"], swing_start=block["swing_start"], swing_length=block["swing_length"], thigh_per_calf=block["thigh_per_calf"], ramp_s=block["ramp_s"], episode_lift=bool(block.get("episode_lift", bool(block["holds"]))))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263#!/bin/bash# lateral_stuck_20261108 nrd_v3: one NRD training arm on one AMD MI350X (mi3501x, 4 h cap; resumable chain).# sbatch [-t HH:MM:SS] [--dependency=afterany:JOB] train_amd.sbatch CODE MODE RUNCFG SEED LABEL LIMIT_S [STOP_AT]# Env recipe: module pytorch/2.10.0 (ROCm) + venvs/go2nrd, python3.12, PYTHONPATH appended (cluster/amd/common.sh).# Output (resumable): /work1/dannegrut/harry/lateral_stuck_20261108/nrd_v3/runs/LABEL#SBATCH -J lsn3-nrd#SBATCH -A dannegrut#SBATCH -p mi3501x#SBATCH -N 1#SBATCH -t 04:00:00#SBATCH --signal=B:USR1@300#SBATCH -o /work1/dannegrut/harry/lateral_stuck_20261108/nrd_v3/logs/%x_%j.outset -o pipefailCODE=${1:?capsule}; MODE=${2:?mode}; RUNCFG=${3:?run config name}; SEED=${4:?seed}; LABEL=${5:?label}LIMIT=${6:-13200}; STOPAT=${7:-0}ROOT=/work1/dannegrut/harry/lateral_stuck_20261108/nrd_v3OUT=$ROOT/runs/$LABELmkdir -p "$OUT" "$ROOT/logs"[ ! -f "$ROOT/STOP" ] || { echo "remote STOP present"; exit 0; }[ ! -f "$OUT/complete.json" ] || { echo "$LABEL already complete"; exit 0; }[ ! -f "$OUT/failure.json" ] || { echo "$LABEL has failure.json; review before retry"; exit 4; }source /etc/profilemodule load pytorch/2.10.0 >/dev/null 2>&1 || { echo "module pytorch/2.10.0 failed"; exit 1; }source /work1/dannegrut/harry/venvs/go2nrd/bin/activateexport PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1python3.12 -B - "$OUT/gpu_preflight_${SLURM_JOB_ID}.json" <<'PY'import json, os, pathlib, platform, sys, torchassert torch.cuda.is_available()x = torch.tensor([2.], device='cuda', requires_grad=True); (x * x).sum().backward(); torch.cuda.synchronize()assert float(x.grad.item()) == 4.a = torch.randn(256, 256, device='cuda', dtype=torch.float64)assert torch.allclose((a @ a).cpu(), a.cpu() @ a.cpu(), atol=1e-9)r = dict(job_id=os.environ.get('SLURM_JOB_ID'), host=platform.node(), torch=torch.__version__, hip=getattr(torch.version, 'hip', None), device=torch.cuda.get_device_name(0))pathlib.Path(sys.argv[1]).write_text(json.dumps(r, indent=2) + '\n'); print(json.dumps(r), flush=True)PY[ $? = 0 ] || exit 3ARGS=(--mode "$MODE" --run-config "$CODE/nrd_v3/configs/$RUNCFG" --source-root "$CODE/src" --pins "$CODE/nrd_v3/reference/pins.json" --recipe "$CODE/nrd_v3/reference/full_config.json" --data-root "$ROOT/data/root" --output "$OUT" --seed "$SEED" --device cuda --max-wall-seconds "$LIMIT" --stop-at-update "$STOPAT" --short-module "$CODE/nrd_v3/reference/short_support.py")case "$MODE" in parity-*) ARGS+=(--manifest "$CODE/manifests/splits.json") ;; *) ARGS+=(--manifest "$CODE/manifests/splits_lateral_v2.json") ;;esaccase "$MODE" in cont) ARGS+=(--parent-resume "$ROOT/parents/ref_h50_s61_u13500/resume.pt" --parent-endpoint "$ROOT/parents/ref_h50_s61_u13500/last.pt") ;;esacprintf '%s\n' "$SLURM_JOB_ID $(hostname) $CODE $MODE $RUNCFG $SEED $LABEL $LIMIT $STOPAT $(date -u +%FT%TZ)" >> "$OUT/jobs.txt"CHILD=trap '[ -z "$CHILD" ] || kill -USR1 "$CHILD" 2>/dev/null || true' USR1 TERMcd "$ROOT"python3.12 -B "$CODE/nrd_v3/nrd_v3_train.py" "${ARGS[@]}" > "$OUT/train_${SLURM_JOB_ID}.log" 2>&1 &CHILD=$!(while sleep 60; do [ ! -f "$ROOT/STOP" ] || kill -USR1 "$CHILD" 2>/dev/null || true; kill -0 "$CHILD" 2>/dev/null || exit 0; done) &WATCH=$!wait "$CHILD"; RC=$?if kill -0 "$CHILD" 2>/dev/null; then wait "$CHILD"; RC=$?; fikill "$WATCH" 2>/dev/nullprintf '{"job_id":"%s","trainer_exit":%s,"host":"%s","mode":"%s","seed":%s,"label":"%s","code":"%s","end":"%s"}\n' \ "$SLURM_JOB_ID" "$RC" "$(hostname)" "$MODE" "$SEED" "$LABEL" "$CODE" "$(date -u +%FT%TZ)" > "$OUT/job_${SLURM_JOB_ID}.json"tail -3 "$OUT/train_${SLURM_JOB_ID}.log"exit "$RC"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{ "arm": "mixed_plus_lat_v2", "budget": "matched", "val_arm": "mixed", "extra_val_arm": "lat_v2", "domain_tree": { "rigid": [ 0.5, [ "rigid" ] ], "crm_half": [ 0.5, { "crm_prod": [ 0.5, [ "crm" ] ], "lat_v2": [ 0.5, [ "crm_lat_v2_hip", "crm_lat_v2_cuda" ] ] } ] }, "crm_domains": [ "crm", "crm_lat_v2_hip", "crm_lat_v2_cuda" ], "short": { "lean_batch": 2, "stall_batch": 2, "stall_domains": [ "crm_lat_v2_hip", "crm_lat_v2_cuda" ], "lean_weight": 0.25, "stall_weight": 0.25 }, "forbidden_directories": [ "lateral_stuck_20261108_crm_v2_test_hip" ], "teacher_onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45", "kind": "fresh", "schedule": "reference A(12000)+B(1000)+C(500)=13500"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571"""nrd_v3 trainer: the reference seed61 H50 u13500 frame+short recipe, new lateral data (lateral_stuck_20261108).
One resumable process covers the whole reference schedule with the FROZEN reference code (yaw_correction_v1 src,digest 924630...; pinned file hashes are checked before any go2nrd import):
stage A updates 1..12000 go2nrd.fixed_base.train_three loop (core 1000, collision 1000, joint 10000 = 8000 one-step + 2000 rollout, horizon 10->50, cosine LR 3e-4 -> 3e-5, warmups 200/20) stage B updates 12001..13000 frame_short_factorial_v1 'short': H50 rollout from H50-eligible starts + short lean auxiliary (2 branches H1..5, weight 0.25), constant LR 3e-5 (fresh short RNG seed+5000) stage C updates 13001..13500 horizon100_pilot_v1 'h50': H50 loss from H100-eligible starts + the same auxiliary stage D (mode cont) stage-C objective continued from a parent endpoint for --cont-updates updates
Modes: fresh (A->B->C from scratch), cont (D from --parent-resume), parity-A / parity-B / parity-C (originaldata, original uniform domain balance and the ORIGINAL ShortCrossingSampler; used only to prove the launcher).New-data runs use the samplers.py WeightedWindowSampler (domain tree) and LeanStallShortSampler (adds a'short_stall' term: 2 lateral STALL branches, weight 0.25). Normalization: fresh refits train-only stats on thetraining mixture (frozen initialize_from_train); cont keeps the parent's buffers and scales."""from __future__ import annotations
import argparseimport copyimport hashlibimport importlibimport jsonimport mathimport osfrom pathlib import Pathimport shutilimport signalimport sysimport timeimport traceback
import numpy as npimport torchfrom torch.nn import functional as F
HERE = Path(__file__).resolve().parentSTAGE_END = {"A": 12000, "B": 13000, "C": 13500}
def sha(path): h = hashlib.sha256() with Path(path).open("rb") as f: for block in iter(lambda: f.read(8 << 20), b""): h.update(block) return h.hexdigest()
def digest(value): """Same portable semantic hash as the reference continuation drivers.""" h = hashlib.sha256()
def visit(v): if torch.is_tensor(v): a = v.detach().cpu().contiguous() h.update(f"tensor:{a.dtype}:{tuple(a.shape)}:".encode()) h.update(a.numpy().tobytes()) elif isinstance(v, dict): h.update(b"dict:") for k in sorted(v, key=lambda x: (type(x).__name__, str(x))): visit(k) visit(v[k]) elif isinstance(v, (list, tuple)): h.update(type(v).__name__.encode()) for x in v: visit(x) elif isinstance(v, np.ndarray): h.update(f"array:{v.dtype}:{v.shape}:".encode()) h.update(v.tobytes()) else: h.update(f"{type(v).__name__}:{repr(v)};".encode()) visit(value) return h.hexdigest()
def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") tmp.replace(path)
def save_pt(path, value): path = Path(path) tmp = path.with_suffix(path.suffix + ".tmp") torch.save(value, tmp) tmp.replace(path)
def load_frozen(root, pins): root = Path(root).resolve() tree = {str(p.relative_to(root)): sha(p) for p in sorted(root.rglob("*.py"))} if tree != pins: bad = sorted(set(tree.items()) ^ set(pins.items()))[:5] raise ValueError(f"frozen source tree differs from the reference pins: {bad}") if any(n == "go2nrd" or n.startswith("go2nrd.") for n in sys.modules): raise ValueError("go2nrd imported before frozen source verification") sys.path.insert(0, str(root)) helper = importlib.import_module("go2nrd.fixed_base.three_transformer") trainer = importlib.import_module("go2nrd.fixed_base.train_three") data = importlib.import_module("go2nrd.fixed_base.data") frame = importlib.import_module("go2nrd.fixed_base.yaw_frame") for name, module in list(sys.modules.items()): if name == "go2nrd" or name.startswith("go2nrd."): file = getattr(module, "__file__", None) if file and not Path(file).resolve().is_relative_to(root): raise ValueError(f"foreign go2nrd import: {name}: {file}") return helper, trainer, data, frame, digest(pins)
class TrainingFailure(RuntimeError): def __init__(self, message, payload): super().__init__(message) self.payload = payload
def short_rollout(model, helper, frame, sb, scales): sh, so = sb["hist"], sb["ok"] h = sb["horizon"] loss = 0. for t in range(h): sf = frame.frame_from_state(sh[:, -1, 0]) sp, _ = helper.step(model, sh, so, sb["actions"][:, t], sb["ground"]) error = frame.local_error(sp, sb["targets"][:, t], sf) loss = loss + F.huber_loss(error / scales["state_scale"], torch.zeros_like(sp)) if not torch.isfinite(sp).all(): break sh, so = model.advance(sh, so, sp) return loss / h
def joint_update(model, opt, train, scales, cfg, helper, frame, short, short_kind, eligibility, loss_horizon=50, aux_weight=.25, stall_weight=.25): """Exact reference stage-B/C update (frame_short / horizon100 drivers) + optional short_stall term.""" n = int(cfg["batch"]) b = train.sample(n, kind="all") h, ok, action, ground = b["hist"], b["ok"], b["actions"][:, 0], b["ground"] hc, hf = frame.canonicalize_history(h, ok) cur, diff, lag = model.code(hc, ok) terms = {} logits = model.logits(cur, diff, action, lag, ground=ground) terms["collision"] = F.binary_cross_entropy_with_logits(logits, b["gates"][:, 0]) pred, _ = helper.step(model, h, ok, action, ground, gates=b["gates"][:, 0]) error = frame.local_error(pred, b["targets"][:, 0], hf)[..., 19:] terms["one_step"] = F.huber_loss(error / scales["rate_scale"], torch.zeros_like(error)) free = train.sample(max(16, n // 4), kind="free") fh, ff = frame.canonicalize_history(free["hist"], free["ok"]) fc, fd, fl = model.code(fh, free["ok"]) dc = model.run_core(fc, fd, free["actions"][:, 0], fl) dy = frame.to_local(free["targets"][:, 0], ff) - fh[:, -1] terms["core"] = (((dc - dy)[..., 19:] / scales["rate_scale"]) ** 2).mean() rb = train.sample(cfg["rollout_batch"], eligibility) rh, ro = rb["hist"], rb["ok"] loss = 0. for t in range(loss_horizon): rf = frame.frame_from_state(rh[:, -1, 0]) pred, _ = helper.step(model, rh, ro, rb["actions"][:, t], rb["ground"]) error = frame.local_error(pred, rb["targets"][:, t], rf) loss = loss + F.huber_loss(error / scales["state_scale"], torch.zeros_like(pred)) if not torch.isfinite(pred).all(): break rh, ro = model.advance(rh, ro, pred) terms["rollout"] = loss / loss_horizon * cfg["rollout_weight"] batches = {"ordinary": b, "free": free, "rollout": rb} if short_kind == "original": sb = short.sample(2) stall = None else: sb, stall = short.sample() terms["short_lean"] = short_rollout(model, helper, frame, sb, scales) * aux_weight if stall is not None: terms["short_stall"] = short_rollout(model, helper, frame, stall, scales) * stall_weight loss = sum(terms.values()) if not torch.isfinite(loss): raise TrainingFailure("nonfinite loss", {"batches": batches, "terms": terms}) opt.zero_grad(set_to_none=True) loss.backward() norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.) if not torch.isfinite(norm): raise TrainingFailure("nonfinite gradient", {"batches": batches, "terms": terms, "gradient_norm": norm}) opt.step() sampled = n + len(free["hist"]) + len(rb["hist"]) + len(sb["hist"]) + (len(stall["hist"]) if stall else 0) return {"loss": float(loss.detach()), "terms": {k: float(v.detach()) for k, v in terms.items()}, "gradient_norm": float(norm), "sampled_windows": sampled, "rollout_loss_horizon": loss_horizon, "rollout_start_eligibility_horizon": eligibility, "short_horizon": sb["horizon"], "short_choices": sb["choices"], "stall_choices": stall["choices"] if stall else [], "short_target_states": len(sb["hist"]) * sb["horizon"], "stall_target_states": len(stall["hist"]) * stall["horizon"] if stall else 0, "batch_identity": {k: {x: v[x].detach().cpu().tolist() for x in ("source", "row", "record")} for k, v in batches.items()}}
def stage_a_update(model, opt, train, scales, cfg, helper, frame, update): """Exact go2nrd.fixed_base.train_three loop body (framed branch), returning (stage, terms, loss, samples).""" counts = [cfg["core_updates"], cfg["collision_updates"], cfg["joint_updates"]] stage = "core" if update <= counts[0] else "collision" if update <= sum(counts[:2]) else "joint" joint_step = update - sum(counts[:2]) supervised_joint = cfg.get("joint_one_step_updates", 0) rollout_phase = stage == "joint" and joint_step > supervised_joint phase_step = update if stage == "core" else update - counts[0] if stage == "collision" else joint_step phase_total = counts[0] if stage == "core" else counts[1] if stage == "collision" else counts[2] if stage == "joint" and supervised_joint: phase_step = joint_step - supervised_joint if rollout_phase else joint_step phase_total = counts[2] - supervised_joint if rollout_phase else supervised_joint if cfg.get("cosine_schedule"): warm = cfg.get("rollout_warmup", 20) if rollout_phase else cfg.get("one_step_warmup", 200) warm = min(warm, phase_total) frac = max(0., (phase_step - warm) / max(1, phase_total - warm)) lr = (cfg.get("lr_floor", cfg["lr"] * .1) + (cfg["lr"] - cfg.get("lr_floor", cfg["lr"] * .1)) * .5 * (1 + math.cos(math.pi * frac))) if phase_step <= warm: lr = cfg["lr"] * phase_step / max(1, warm) for group in opt.param_groups: group["lr"] = lr n = int(cfg["batch"]) samples = 0 b = train.sample(n, kind="free" if stage == "core" else "all") samples += n h, ok, action, ground = b["hist"], b["ok"], b["actions"][:, 0], b["ground"] hc, fr = frame.canonicalize_history(h, ok) local_target = frame.to_local(b["targets"][:, 0], fr) cur, diff, lag = model.code(hc, ok) terms = {} horizon = None if stage == "core": dc = model.run_core(cur, diff, action, lag) target = local_target - hc[:, -1] terms["core"] = (((dc - target)[..., 19:] / scales["rate_scale"]) ** 2).mean() else: logits = model.logits(cur, diff, action, lag, ground=ground) terms["collision"] = F.binary_cross_entropy_with_logits(logits, b["gates"][:, 0]) if stage == "joint": pred, _ = helper.step(model, h, ok, action, ground, gates=b["gates"][:, 0]) error = frame.local_error(pred, b["targets"][:, 0], fr)[..., 19:] terms["one_step"] = F.huber_loss(error / scales["rate_scale"], torch.zeros_like(error)) free = train.sample(max(16, n // 4), kind="free") samples += len(free["hist"]) fh, ff = frame.canonicalize_history(free["hist"], free["ok"]) dy = frame.to_local(free["targets"][:, 0], ff) - fh[:, -1] fc, fd, fl = model.code(fh, free["ok"]) dc = model.run_core(fc, fd, free["actions"][:, 0], fl) terms["core"] = (((dc - dy)[..., 19:] / scales["rate_scale"]) ** 2).mean() if rollout_phase and phase_step % cfg["rollout_every"] == 0: frac = (joint_step - supervised_joint) / max(1, counts[2] - supervised_joint) horizon = max(1, round(cfg["horizon_start"] + (cfg["horizon_max"] - cfg["horizon_start"]) * min(1., frac / .5))) rb = train.sample(cfg["rollout_batch"], horizon) samples += len(rb["hist"]) rh, ro = rb["hist"], rb["ok"] loss = 0. for t in range(horizon): rf = frame.frame_from_state(rh[:, -1, 0]) pred, _ = helper.step(model, rh, ro, rb["actions"][:, t], rb["ground"]) error = frame.local_error(pred, rb["targets"][:, t], rf) loss = loss + F.huber_loss(error / scales["state_scale"], torch.zeros_like(pred)) if not torch.isfinite(pred).all(): break rh, ro = model.advance(rh, ro, pred) terms["rollout"] = loss / horizon * cfg["rollout_weight"] loss = sum(terms.values()) return stage, terms, loss, samples, horizon
def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--mode", choices=("fresh", "cont", "parity-A", "parity-B", "parity-C"), required=True) p.add_argument("--run-config", type=Path, required=True, help="nrd_v3 run JSON (arm, tree, recipe, caps)") p.add_argument("--source-root", type=Path, required=True, help="frozen yaw_correction_v1/src") p.add_argument("--pins", type=Path, required=True, help="registration JSON with source_sha256 pins") p.add_argument("--recipe", type=Path, required=True, help="reference full_config.json") p.add_argument("--manifest", type=Path, required=True) p.add_argument("--data-root", type=Path) p.add_argument("--parent-resume", type=Path) p.add_argument("--parent-endpoint", type=Path) p.add_argument("--output", type=Path, required=True) p.add_argument("--seed", type=int, required=True) p.add_argument("--device", default="cuda") p.add_argument("--max-wall-seconds", type=float, default=3300.) p.add_argument("--stop-at-update", type=int, default=0, help="parity/smoke: save and stop after this update") p.add_argument("--log-every", type=int, default=0, help="0 = reference cadence") p.add_argument("--short-module", type=Path, default=HERE / "reference" / "short_support.py") args = p.parse_args() started = time.monotonic() rc = json.loads(args.run_config.read_text()) pins = json.loads(args.pins.read_text())["source_sha256"] helper, trainer, data, frame, source_digest = load_frozen(args.source_root, pins) sys.path.insert(0, str(HERE)) import samplers import stall_support cfg = json.loads(args.recipe.read_text()) parity = args.mode.startswith("parity") arm, budget = rc["arm"], rc.get("budget", "matched") tree = None if parity else rc["domain_tree"] crm_domains = tuple(rc.get("crm_domains", ["crm"])) use_cuda = str(args.device).startswith("cuda")
# ---- identical construction order to train_three.main (torch seed before model build) ---- torch.set_num_threads(int(cfg.get("cpu_threads", 1))) torch.manual_seed(args.seed) manifest = json.loads(args.manifest.read_text()) train_desc = data.load_arm(args.manifest, arm=arm, budget=budget, split="train", data_root=args.data_root) val_desc = data.load_arm(args.manifest, arm=rc.get("val_arm", "mixed"), budget=budget, split="val", data_root=args.data_root) data.verify_sources(train_desc) domains = [d["domain"] for d in train_desc] for forbidden in rc.get("forbidden_directories", []): if any(Path(d["path"]).name == forbidden for d in train_desc + val_desc): raise ValueError(f"held-out directory in training/validation descriptors: {forbidden}") W = samplers.weighted_sampler_class(helper) train = W(train_desc, cfg["history"], args.device, args.seed + 1000, tree=tree, crm_domains=crm_domains) val = helper.WindowSampler(val_desc, cfg["history"], args.device, args.seed + 2000) extra_val = None if rc.get("extra_val_arm"): ed = data.load_arm(args.manifest, arm=rc["extra_val_arm"], budget=budget, split="val", data_root=args.data_root) extra_val = helper.WindowSampler(ed, cfg["history"], args.device, args.seed + 2500) model = helper.build_model(train.system, cfg).to(args.device) opt = torch.optim.AdamW(model.parameters(), lr=cfg["lr"], weight_decay=cfg.get("weight_decay", 0.), betas=tuple(cfg.get("optimizer_betas", (.9, .999)))) root = args.output root.mkdir(parents=True, exist_ok=True) if (root / "failure.json").exists(): raise ValueError("failed attempt retained; review before any retry") resume = root / "resume.pt"
# ---- stage plan ---- if args.mode == "fresh": plan = [("A", 1, 12000), ("B", 12001, 13000), ("C", 13001, 13500)] elif args.mode == "parity-A": plan = [("A", 1, 12000)] elif args.mode == "parity-B": plan = [("B", 12001, 13000)] elif args.mode == "parity-C": plan = [("C", 13001, 13500)] else: plan = None # set from parent update below parent = None if args.mode in ("cont", "parity-B", "parity-C"): if not args.parent_resume: raise ValueError("continuation needs --parent-resume") parent = torch.load(args.parent_resume, map_location="cpu", weights_only=False) if args.parent_endpoint: endpoint = torch.load(args.parent_endpoint, map_location="cpu", weights_only=False) for key in ("model_config", "system", "masks", "model_state_dict", "update", "runtime"): if digest(parent[key]) != digest(endpoint[key]): raise ValueError("parent resume differs from its exported endpoint: " + key) if digest(model.system) != digest(parent["system"]) or digest(model.config) != digest(parent["model_config"]): raise ValueError("model configuration differs from the parent") if args.mode == "cont": pu = int(parent["update"]) plan = [("D", pu + 1, pu + int(rc["cont_updates"]))] elif int(parent["update"]) != plan[0][1] - 1: raise ValueError("parity parent update does not match the stage") stall_report = None lineage = dict(schema="lateral_stuck_20261108_nrd_v3_train_v1", mode=args.mode, arm=arm, budget=budget, seed=args.seed, manifest_sha256=sha(args.manifest), recipe=cfg, recipe_sha256=sha(args.recipe), run_config=rc, domains=domains, source_sha256={d["domain"]: d["source_sha256"] for d in train_desc}, frozen_source_digest=source_digest, driver_sha256=sha(__file__), samplers_sha256=sha(HERE / "samplers.py"), stall_support_sha256=sha(HERE / "stall_support.py"), plan=plan, parent_resume_sha256=sha(args.parent_resume) if args.parent_resume else None, parent_endpoint_sha256=sha(args.parent_endpoint) if args.parent_endpoint else None, normalization=("parent buffers and scales (no refit)" if parent is not None else "fresh train-only refit on the training mixture (frozen initialize_from_train)"), architecture="core_collision_contact_three_transformers", representation=getattr(model, "state_frame", None), short=("reference ShortCrossingSampler" if parity else "LeanStallShortSampler")) lineage = json.loads(json.dumps(lineage)) if (root / "lineage.json").exists() and json.loads((root / "lineage.json").read_text()) != lineage: raise ValueError("resume lineage/config changed; use a new output directory") write_json(root / "lineage.json", lineage)
def make_short(stage): """Short sampler for B/C/D; reference class in parity, lean+stall otherwise.""" nonlocal stall_report if parity: sys.path.insert(0, str(args.short_module.parent)) ss = importlib.import_module(args.short_module.stem) return ss.ShortCrossingSampler(train, manifest, args.seed + 5000), "original" masks, stall_report = stall_support.stall_tables(train.sources, manifest) if rc["short"]["stall_batch"] \ else ({}, None) stall_domains = [d for d in domains if d in rc["short"]["stall_domains"]] s = samplers.LeanStallShortSampler(train, manifest, args.seed + 5000, tree, masks, stall_domains, rc["short"]["lean_batch"], rc["short"]["stall_batch"]) write_json(root / "short_support.json", {"short": s.report, "stall": stall_report}) return s, "lean_stall"
# ---- state ---- short, short_kind = None, None total_samples, best, previous_s, last_val = 0, float("inf"), 0., None if resume.exists(): ck = torch.load(resume, map_location=args.device, weights_only=False) if ck["lineage"] != lineage: raise ValueError("checkpoint lineage differs") model.load_state_dict(ck["model_state_dict"]) opt.load_state_dict(ck["optimizer"]) scales = ck["scales"] train.rng.bit_generator.state = ck["numpy_rng"] torch.set_rng_state(ck["torch_rng"].cpu()) if use_cuda and ck.get("cuda_rng") is not None: torch.cuda.set_rng_state_all([x.cpu() for x in ck["cuda_rng"]]) done = int(ck["update"]) total_samples, best, previous_s = ck["total_sampled_windows"], ck["best"], ck["elapsed_total_s"] last_val = ck.get("validation") if ck.get("short_sampler") is not None: short, short_kind = make_short(ck["stage"]) short.load_state_dict(ck["short_sampler"]) elif parent is not None: model.load_state_dict(parent["model_state_dict"]) opt.load_state_dict(parent["optimizer"]) if any(abs(g["lr"] - 3e-5) > 1e-12 for g in opt.param_groups): raise ValueError("parent optimizer is not at the 3e-5 floor") scales = {k: v.to(args.device) if torch.is_tensor(v) else v for k, v in parent["scales"].items()} done = int(parent["update"]) total_samples = int(parent["total_sampled_windows"]) best = parent.get("best", float("inf")) if args.mode != "cont": # Parity: the reference drivers restored the parent's numpy/torch/CUDA streams. train.rng.bit_generator.state = parent["numpy_rng"] torch.set_rng_state(parent["torch_rng"].cpu()) if use_cuda and parent.get("cuda_rng") is not None: torch.cuda.set_rng_state_all([v.cpu() for v in parent["cuda_rng"]]) short, short_kind = make_short(plan[0][0]) if args.mode == "parity-C": short.load_state_dict(parent["short_sampler"]) else: scales = helper.initialize_from_train(model, train, int(cfg["normalization_samples"])) write_json(root / "initialization.json", {**scales["initialization"], "mixture_probabilities_all_h1": train.probabilities(1, "all").tolist(), "domains": domains}) done = 0 scales = {k: v.to(args.device) if torch.is_tensor(v) else v for k, v in scales.items()} model.train() halt = [False] for s_ in (signal.SIGTERM, signal.SIGINT, signal.SIGUSR1): signal.signal(s_, lambda *_: halt.__setitem__(0, True)) final = plan[-1][2] launch = dict(job_id=os.environ.get("SLURM_JOB_ID"), host=os.uname().nodename, resumed_at=done, device=args.device, torch=torch.__version__, cuda=torch.version.cuda, hip=getattr(torch.version, "hip", None), gpu=torch.cuda.get_device_name(0) if use_cuda else None, numpy=np.__version__, python=sys.version.split()[0], max_wall_seconds=args.max_wall_seconds, stop_at_update=args.stop_at_update, t=time.strftime("%Y-%m-%dT%H:%M:%S")) write_json(root / "starts" / f"launch_{time.time_ns()}.json", launch) if not (root / "start.json").exists(): write_json(root / "start.json", launch)
def elapsed(): return previous_s + time.monotonic() - started
def stage_of(u): for name, a, b in plan: if a <= u <= b: return name return plan[-1][0]
def packet(u): return dict(model_config=model.config, system=model.system, masks=model.smask.tolist(), model_state_dict=model.state_dict(), stage="fixed_base_joint", update=u, sigma=[[0.] * 37], runtime=lineage, validation=last_val)
def save(u, finished=False): ck = {**packet(u), "lineage": lineage, "optimizer": opt.state_dict(), "scales": scales, "numpy_rng": copy.deepcopy(train.rng.bit_generator.state), "torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state_all() if use_cuda else None, "short_sampler": short.state_dict() if short is not None else None, "stage": stage_of(max(u, 1)), "best": best, "elapsed_total_s": elapsed(), "total_sampled_windows": total_samples} save_pt(resume, ck) save_pt(root / "last.pt", packet(u)) write_json(root / "progress.json", dict(update=u, planned_updates=final, finished=finished, stage=stage_of(max(u, 1)), elapsed_total_s=elapsed(), total_sampled_windows=total_samples, source_draws_this_launch=train.draw_counts, short_counts=(dict(short.counts) if short is not None else None), checkpoint_sha256=sha(root / "last.pt"), job_id=os.environ.get("SLURM_JOB_ID")))
def validate(u): nonlocal last_val last_val = trainer.validate(model, val, scales, cfg["validation_batch"], tuple(cfg["validation_horizons"])) write_json(root / f"validation_{u:07d}.json", last_val) if extra_val is not None: ev = trainer.validate(model, extra_val, scales, cfg["validation_batch"], tuple(cfg["validation_horizons"])) write_json(root / f"validation_lat_{u:07d}.json", ev) (root / "checkpoints").mkdir(exist_ok=True) save_pt(root / "checkpoints" / f"update_{u:07d}.pt", packet(u))
def log(event, every_default): every = args.log_every or every_default u = event["update"] if u % every == 0 or u == 1 or every_default == 1: with (root / "train.jsonl").open("a") as f: f.write(json.dumps(event, allow_nan=False) + "\n") if u % 50 == 0 or u == 1: print(json.dumps({k: v for k, v in event.items() if k not in ("batch_identity",)}), flush=True)
if done == 0: pass elif not resume.exists(): save(done) first = done + 1 u = done try: for u in range(first, final + 1): stage = stage_of(u) if stage in ("B", "C", "D") and short is None: short, short_kind = make_short(stage) # fresh pipeline enters stage B: new short RNG seed+5000 if use_cuda: torch.cuda.synchronize() t0 = time.monotonic() if stage == "A": sub, terms, loss, ns, horizon = stage_a_update(model, opt, train, scales, cfg, helper, frame, u) if not torch.isfinite(loss): raise TrainingFailure(f"nonfinite loss at {u}: {sub}", {"terms": terms}) opt.zero_grad(set_to_none=True) loss.backward() norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.) if not torch.isfinite(norm): raise TrainingFailure(f"nonfinite gradient at {u}: {sub}", {"terms": terms}) opt.step() total_samples += ns event = dict(update=u, stage=sub, loss=float(loss.detach()), terms={k: float(v.detach()) for k, v in terms.items()}, elapsed_s=elapsed(), total_sampled_windows=total_samples, lr=opt.param_groups[0]["lr"], horizon=horizon) log(event, cfg["log_every"]) counts = [cfg["core_updates"], cfg["collision_updates"], cfg["joint_updates"]] if sub == "joint" and (u % cfg["evaluate_every"] == 0 or u == sum(counts)): validate(u) if math.isfinite(last_val["selection_score"]) and last_val["selection_score"] < best: best = last_val["selection_score"] else: elig = 50 if stage == "B" else 100 sw = rc.get("short", {}) m = joint_update(model, opt, train, scales, cfg, helper, frame, short, short_kind, elig, aux_weight=float(sw.get("lean_weight", .25)) if not parity else .25, stall_weight=float(sw.get("stall_weight", .25))) total_samples += m.pop("sampled_windows") if use_cuda: torch.cuda.synchronize() m.update(update=u, stage=stage, lr=opt.param_groups[0]["lr"], elapsed_s=elapsed(), update_wall_s=time.monotonic() - t0, total_sampled_windows=total_samples) log(m, 1) if u % 250 == 0 or u == final: validate(u) if u in (STAGE_END["A"], STAGE_END["B"]) and args.mode == "fresh" and u != final: (root / "checkpoints").mkdir(exist_ok=True) save_pt(root / "checkpoints" / f"update_{u:07d}.pt", packet(u)) save(u) shutil.copy2(resume, root / "checkpoints" / f"resume_stage{stage}_{u:07d}.pt") stop = halt[0] or elapsed() - previous_s >= args.max_wall_seconds or u == args.stop_at_update if u % cfg["checkpoint_every"] == 0 or stop or u == final: save(u, finished=u == final) if stop and u < final: print(json.dumps({"bounded_stop": True, "update": u, "resume": str(resume)}), flush=True) return write_json(root / "complete.json", dict(complete=True, update=final, checkpoint_sha256=sha(root / "last.pt"), resume_sha256=sha(resume), elapsed_total_s=elapsed(), lineage=lineage, short_counts=dict(short.counts) if short is not None else None, completion_means="schedule finished, not a research milestone")) except Exception as exc: failed = {"attempted_update": u, "exception": repr(exc)} if isinstance(exc, TrainingFailure): failed["failure_payload"] = exc.payload save_pt(root / "failed_attempt.pt", failed) write_json(root / "failure.json", {"exception": repr(exc), "traceback": traceback.format_exc(), "attempted_update": u, "elapsed_s": elapsed(), "no_automatic_resume": True, "previous_durable_checkpoint_retained": resume.exists()}) raise
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326"""nrd_v3 samplers: domain-weighted WindowSampler and the lean + stall short-window sampler.
Both wrap the FROZEN reference implementation (yaw_correction_v1 src, digest 924630...). With ``tree=None`` thewindow sampler calls the frozen ``sample`` unchanged (bitwise original draw stream). The only other change is thatCRM-type lateral sources get the same ``crm_free`` rule as domain ``crm`` for free-core windows."""from __future__ import annotations
from collections import Counter, defaultdictimport copyimport hashlibimport json
import numpy as npimport torch
# Default nrd_v3 domain tree: rigid 50 % of draws; the CRM half split 50/50 between crm_prod and lat_v2, and lat_v2# pooled over the HIP and CUDA exports by eligible-window count (uniform over its windows).DEFAULT_TREE = {"rigid": [0.5, ["rigid"]], "crm_half": [0.5, {"crm_prod": [0.5, ["crm"]], "lat_v2": [0.5, ["crm_lat_v2_hip", "crm_lat_v2_cuda"]]}]}
def leaf_probabilities(tree, domains, sizes): """Per-source probability from a weight tree; empty branches pass their mass to nonempty siblings.""" sizes = np.asarray(sizes, float) index = {d: i for i, d in enumerate(domains)} p = np.zeros(len(domains))
def total(node): if isinstance(node, list) and node and isinstance(node[0], str): return sum(sizes[index[d]] for d in node if d in index) return sum(total(child[1]) for child in node.values())
def assign(node, mass): if isinstance(node, list) and node and isinstance(node[0], str): idx = [index[d] for d in node if d in index] s = sizes[idx] p[idx] += mass * s / s.sum() return live = {k: v for k, v in node.items() if total(v[1]) > 0} w = sum(v[0] for v in live.values()) for v in live.values(): assign(v[1], mass * v[0] / w)
if total(tree) <= 0: raise ValueError("no eligible windows in any weighted domain") assign(tree, 1.0) listed = set()
def leaves(node): if isinstance(node, list) and node and isinstance(node[0], str): listed.update(node) else: for v in node.values(): leaves(v[1]) leaves(tree) if set(domains) - listed: raise ValueError(f"domains missing from the weight tree: {sorted(set(domains) - listed)}") return p
def weighted_sampler_class(helper): """Subclass of the frozen helper.WindowSampler (imported from the verified frozen source).""" base = helper.WindowSampler averaged = helper.averaged
class WeightedWindowSampler(base): def __init__(self, descriptors, history=4, device="cpu", seed=0, tree=None, crm_domains=("crm",)): super().__init__(descriptors, history, device, seed, balance_domains=True) self.tree = copy.deepcopy(tree) self.crm_domains = tuple(crm_domains) self.domains = [s["desc"]["domain"] for s in self.sources] if self.tree is not None: leaf_probabilities(self.tree, self.domains, np.ones(len(self.domains))) # coverage check self.summary["weight_tree"] = self.tree self.summary["crm_free_domains"] = list(self.crm_domains)
def _pools(self, horizon, kind): if self.crm_domains == ("crm",): return super()._pools(horizon, kind) key = int(horizon), kind if key in self.cache: return self.cache[key] pools = [] for src in self.sources: a = src["arrays"] all_rows, all_records = [], [] for row in src["rows"]: rs = np.arange(2 * self.k, int(a["lengths"][row]) - 2 * horizon, 2, dtype=np.int64) if kind != "all" and len(rs): labels = np.asarray(a["contacts"][row])[rs[:, None] + np.arange(-2, 2)].any(1) count = labels.sum(-1) keep = count == 0 if kind == "free" else count == 1 if kind == "single" else count > 0 if kind == "free": keep &= ~np.asarray(a["contacts"][row])[rs - 3].any(-1) if src["desc"]["domain"] in self.crm_domains: if "crm_free" not in a: raise ValueError("CRM free-core windows require crm_free evidence") keep &= np.asarray(a["crm_free"][row])[rs[:, None] + np.arange(-2, 2)].all(1) rs = rs[keep] all_rows.append(np.full(len(rs), row, dtype=np.int64)) all_records.append(rs) pools.append(np.stack((np.concatenate(all_rows), np.concatenate(all_records)), axis=1)) if sum(map(len, pools)) == 0: raise ValueError(f"no {kind} windows with horizon {horizon}") self.cache[key] = pools return pools
def probabilities(self, horizon=1, kind="all"): sizes = np.array(list(map(len, self._pools(horizon, kind))), float) if self.tree is None: prob = (sizes > 0).astype(float) return prob / prob.sum() return leaf_probabilities(self.tree, self.domains, sizes)
def sample(self, batch, horizon=1, kind="all"): if self.tree is None: return super().sample(batch, horizon, kind) # frozen original stream pools = self._pools(horizon, kind) prob = self.probabilities(horizon, kind) # Same RNG call sequence as the frozen sampler; only the source probabilities differ. src_choices = self.rng.choice(len(pools), int(batch), p=prob / prob.sum()) chunks = [] for si in np.unique(src_choices): n = int((src_choices == si).sum()) src, pool = self.sources[si], pools[si] picks = pool[self.rng.integers(len(pool), size=n)] e, r = picks[:, 0], picks[:, 1] a = src["arrays"] hr = r[:, None] + 2 * np.arange(1 - self.k, 1)[None] tr = r[:, None] + 2 * np.arange(1, horizon + 1)[None] ar = r[:, None] + 2 * np.arange(horizon)[None] d = lambda x, dtype=torch.float64: torch.as_tensor(np.array(x), dtype=dtype, device=self.device) hist_raw, hist_prev = d(a["robot"][e[:, None], hr]), d(a["robot"][e[:, None], hr - 2]) truth_raw, truth_prev = d(a["robot"][e[:, None], tr]), d(a["robot"][e[:, None], tr - 2]) contact_r = ar[:, :, None] + np.arange(-2, 2)[None, None] gate = np.asarray(a["contacts"][e[:, None, None], contact_r]).any(2) out = dict(hist=averaged(hist_raw, hist_prev)[:, :, None], targets=averaged(truth_raw, truth_prev)[:, :, None], actions=d(a["action"][e[:, None], ar])[:, :, None], gates=d(gate), ground=d(a["ground_features"][e]), instantaneous=hist_raw[:, -1], command=d(a["command"][e, r]), phase_k=d(a["phase_k"][e, r], torch.long), last_action=d(a["raw_action"][e, r - 2]), source=torch.full((n,), int(si), device=self.device), row=d(e, torch.long), record=d(r, torch.long)) out["ok"] = torch.ones((n, self.k), dtype=torch.bool, device=self.device) chunks.append(out) domain = src["desc"]["domain"] self.draw_counts[domain] = self.draw_counts.get(domain, 0) + n return {k: torch.cat([c[k] for c in chunks]) for k in chunks[0]}
return WeightedWindowSampler
def _digest(value): return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
def _tilt(q): q = np.asarray(q, np.float64) norm = (q * q).sum(-1) if not np.isfinite(q).all() or np.any(norm < 1e-12): raise ValueError("invalid recorded quaternion") return np.rad2deg(np.arccos(np.clip(1 - 2 * (q[..., 1:3] ** 2).sum(-1) / norm, -1, 1)))
class LeanStallShortSampler: """Short H1..5 branches: lean (original 45 deg crossing endpoints) + lateral STALL starts. Independent RNG.
Lean pools use the exact ShortCrossingSampler eligibility (first <=45 -> >45 crossings on the 20 ms grid, history >= 2k, parent action alignment, no earlier severe target). Lean domain choice follows ``tree`` over the sources that have support at the drawn horizon, then uniform parent, then uniform start (a pooled leaf such as lat_v2 = HIP + CUDA is pooled by parent count, i.e. uniform over its parents). Stall pools: TRAIN rows of ``stall_domains``; start r and every branch state r+2, ..., r+2H inside the STALL mask (stall_support.py: union of STALLED 1 s lateral windows), same history/alignment/same-piece rules. One horizon per update for both; ``lean_batch`` + ``stall_batch`` draws. """
def __init__(self, base, manifest, seed, tree, stall_masks, stall_domains, lean_batch=2, stall_batch=2): if any(s["desc"].get("split") != "train" for s in base.sources): raise ValueError("short objective requires explicit TRAIN descriptors") self.base, self.rng = base, np.random.default_rng(seed) self.tree, self.lean_batch, self.stall_batch = copy.deepcopy(tree), int(lean_batch), int(stall_batch) self.domains = [s["desc"]["domain"] for s in base.sources] self.stall_domains = tuple(stall_domains) self.lean = {h: [] for h in range(1, 6)} self.stall = {h: [] for h in range(1, 6)} self.counts, self.seen = Counter(), set() self.report = dict(history=base.k, split="train", lean_target="first20ms below-to-above45 crossing", stall_target="start and all H targets inside a STALLED lateral 1 s window", horizons=list(range(1, 6)), lean_batch=self.lean_batch, stall_batch=self.stall_batch, tree=self.tree, stall_domains=list(self.stall_domains), domains={}, no_normalization_fit=True) identity = [] for si, src in enumerate(base.sources): domain = src["desc"]["domain"] rows = {r["index"]: r for r in manifest["sources"][domain]["rows"]} lean = {h: defaultdict(list) for h in range(1, 6)} stall = {h: defaultdict(list) for h in range(1, 6)} counts = Counter() masks = stall_masks.get(si, {}) if domain in self.stall_domains else {} for row in src["rows"]: row = int(row) meta = rows[row] if meta["split"] != "train" or int(meta["length"]) != int(src["arrays"]["lengths"][row]): raise ValueError("split/length mismatch") n = int(meta["length"]) high = _tilt(src["arrays"]["robot"][row, :n, 3:7]) > 45 grid = np.arange(0, n, 2) events = grid[1:][~high[grid[:-1]] & high[grid[1:]]] counts["rows_scanned"] += 1 counts["new45_events"] += len(events) parent = int(meta["parent_id"]) off = int(meta["record_offset"]) for h in range(1, 6): for endpoint in events: start = int(endpoint - 2 * h) if start < 2 * base.k: counts[f"H{h}/lean_excluded_history"] += 1 continue if (start + off) % 2: counts[f"H{h}/lean_excluded_alignment"] += 1 continue if high[start:int(endpoint):2].any(): counts[f"H{h}/lean_excluded_prior_severe"] += 1 continue lean[h][parent].append((row, start)) identity.append(("lean", domain, h, parent, row, start)) counts[f"H{h}/lean_eligible"] += 1 mask = masks.get(row) if mask is None: continue starts = np.arange(2 * base.k, n, 2, dtype=np.int64) starts = starts[(starts + off) % 2 == 0] for h in range(1, 6): ok = starts[starts + 2 * h < n] keep = np.ones(len(ok), bool) for j in range(0, h + 1): keep &= mask[ok + 2 * j] ok = ok[keep & ~high[ok]] for start in ok.tolist(): stall[h][parent].append((row, start)) if len(ok): identity.append(("stall", domain, h, parent, row, int(ok.min()), int(ok.max()), len(ok))) counts[f"H{h}/stall_eligible"] += len(ok) self.report["domains"][domain] = dict( counts=dict(counts), lean_parents={str(h): len(lean[h]) for h in lean}, stall_parents={str(h): len(stall[h]) for h in stall}, lean_families={str(h): dict(Counter(rows[r]["family"] for w in lean[h].values() for r, _ in w)) for h in lean}) for h in range(1, 6): self.lean[h].append({p: np.array(v, dtype=np.int64) for p, v in sorted(lean[h].items())}) self.stall[h].append({p: np.array(v, dtype=np.int64) for p, v in sorted(stall[h].items())}) for h in range(1, 6): if not any(self.lean[h]): raise ValueError(f"no lean support at H{h}") if self.stall_batch and not any(self.stall[h]): raise ValueError(f"no stall support at H{h}") self.pool_sha256 = _digest(sorted(map(list, identity))) self.report["pool_sha256"] = self.pool_sha256
def _source_probabilities(self, pools, restrict=None): sizes = np.array([len(p) if (restrict is None or d in restrict) else 0 for p, d in zip(pools, self.domains)], float) if restrict is not None: prob = sizes / sizes.sum() # stall: pooled over the lateral exports by parent count else: prob = leaf_probabilities(self.tree, self.domains, sizes) return prob
def _draw(self, pools, n, kind, h, restrict=None): prob = self._source_probabilities(pools, restrict) choices = [] for _ in range(n): si = int(self.rng.choice(len(pools), p=prob)) parents = list(pools[si]) parent = int(parents[int(self.rng.integers(len(parents)))]) pool = pools[si][parent] row, start = map(int, pool[int(self.rng.integers(len(pool)))]) choices.append((si, parent, row, start)) chunks = [] average = __import__("go2nrd.fixed_base.three_transformer", fromlist=["averaged"]).averaged for si, parent, row, start in choices: src = self.base.sources[si] a = src["arrays"] hr = start + 2 * np.arange(1 - self.base.k, 1) tr = start + 2 * np.arange(1, h + 1) ar = start + 2 * np.arange(h) d = lambda x: torch.as_tensor(np.array(x), dtype=torch.float64, device=self.base.device) hist = average(d(a["robot"][row, hr]), d(a["robot"][row, hr - 2]))[None, :, None] targets = average(d(a["robot"][row, tr]), d(a["robot"][row, tr - 2]))[None, :, None] action = d(a["action"][row, ar])[None, :, None] ground = d(a["ground_features"][row])[None] if not all(torch.isfinite(v).all() for v in (hist, targets, action, ground)): raise ValueError("nonfinite short branch input") chunks.append(dict(hist=hist, targets=targets, actions=action, ground=ground, ok=torch.ones((1, self.base.k), dtype=torch.bool, device=self.base.device))) domain = src["desc"]["domain"] self.counts[f"{kind}/{domain}/H{h}"] += 1 self.counts[f"{kind}/{domain}/parent/{parent}"] += 1 self.seen.add((kind, domain, h, row, start)) out = {k: torch.cat([c[k] for c in chunks]) for k in chunks[0]} out["choices"] = choices out["horizon"] = h return out
def sample(self): h = int(self.rng.integers(1, 6)) lean = self._draw(self.lean[h], self.lean_batch, "lean", h) stall = self._draw(self.stall[h], self.stall_batch, "stall", h, restrict=self.stall_domains) \ if self.stall_batch else None return lean, stall
def state_dict(self): return dict(pool_sha256=self.pool_sha256, rng=copy.deepcopy(self.rng.bit_generator.state), counts=dict(self.counts), seen=sorted(map(list, self.seen)))
def load_state_dict(self, value): if value["pool_sha256"] != self.pool_sha256: raise ValueError("short support differs on resume") self.rng.bit_generator.state = value["rng"] self.counts = Counter(value["counts"]) self.seen = set(map(tuple, value["seen"]))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""Train-only lateral STALL masks on exported pieces (lateral_stuck_20261108, track nrd_v3).
Same definition as the track-A QA (collect/scripts/qa_episodes.py), applied inside one exported piece:
* command c = exported ``command`` per record; lateral-dominant run: |vy_cmd| >= 0.2 and |vy_cmd| >= |vx_cmd|, one constant command run (any change of the 3 command values starts a new run);* achieved = world base velocity (robot[:, 19:22], instantaneous) rotated by -yaw, y component, times sign(vy_cmd);* 1.0 s windows (100 records), stride 0.1 s, settled: start >= 0.5 s after the run start. A run that begins at the piece start is treated as starting there (conservative: never a window across a cut);* ratio = mean(achieved) / |vy_cmd|; STUCK < 0.4, STALLED < 0.2.
The per-record STALL mask is the union of all STALLED windows. Numpy only. No labels, no fitting, no held-out data."""from __future__ import annotations
import hashlibimport json
import numpy as np
DT, WIN, STRIDE, SETTLE = 0.01, 100, 10, 50VY_MIN, STALLED, STUCK = 0.2, 0.2, 0.4
def yaw_of(q): w, x, y, z = np.asarray(q, np.float64).T return np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
def piece_windows(robot, command, length): """[(w0, ratio, |vy|)] settled lateral 1 s windows of one piece and the per-record STALL mask.""" n = int(length) st = np.asarray(robot[:n], np.float64) cmd = np.asarray(command[:n], np.float64) yaw = yaw_of(st[:, 3:7]) vw = st[:, 19:22] v_head_y = -np.sin(yaw) * vw[:, 0] + np.cos(yaw) * vw[:, 1] change = np.ones(n, bool) change[1:] = np.any(cmd[1:] != cmd[:-1], 1) starts = list(np.flatnonzero(change)) + [n] wins, mask = [], np.zeros(n, bool) for a, b in zip(starts[:-1], starts[1:]): c = cmd[a] avy, avx = abs(c[1]), abs(c[0]) if not (avy >= VY_MIN and avy >= avx): continue along = v_head_y * np.sign(c[1]) for w0 in range(a + SETTLE, b - WIN + 1, STRIDE): r = float(along[w0:w0 + WIN].mean() / avy) wins.append((w0, r, avy)) if r < STALLED: mask[w0:w0 + WIN] = True return wins, mask
def stall_tables(sources, manifest): """Per lateral TRAIN source: {row: STALL mask}; plus a report. ``sources`` = WindowSampler.sources.""" out, report, identity = {}, {}, [] for si, src in enumerate(sources): d = src["desc"] if d.get("split") != "train": raise ValueError("stall support is TRAIN only") a = src["arrays"] rows_meta = {r["index"]: r for r in manifest["sources"][d["domain"]]["rows"]} masks, nwin, nstuck, nstalled, ratios = {}, 0, 0, 0, [] for row in src["rows"]: row = int(row) meta = rows_meta[row] if meta["split"] != "train" or int(meta["length"]) != int(a["lengths"][row]): raise ValueError("split/length mismatch in stall support") wins, mask = piece_windows(a["robot"][row], a["command"][row], a["lengths"][row]) nwin += len(wins) r = np.array([w[1] for w in wins]) if wins else np.zeros(0) nstuck += int((r < STUCK).sum()) nstalled += int((r < STALLED).sum()) ratios += r.tolist() if mask.any(): masks[row] = mask identity.append((d["domain"], row, hashlib.sha256(np.packbits(mask).tobytes()).hexdigest())) out[si] = masks report[d["domain"]] = dict(lateral_windows=nwin, stuck=nstuck, stalled=nstalled, stuck_share=nstuck / max(1, nwin), stalled_share=nstalled / max(1, nwin), median_ratio=float(np.median(ratios)) if ratios else None, rows_with_stall=len(masks), stall_records=int(sum(m.sum() for m in masks.values()))) digest = hashlib.sha256(json.dumps(sorted(identity)).encode()).hexdigest() return out, dict(definition=__doc__.strip().splitlines()[0], vy_min=VY_MIN, stalled=STALLED, stuck=STUCK, window_s=WIN * DT, stride_s=STRIDE * DT, settle_s=SETTLE * DT, domains=report, mask_sha256=digest)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436"""Fixed-policy 3NN primitives; retained ContactNRD architecture, audited data views.
This is a new training recipe, not the legacy trainer. All fitted quantities usethe training split, and every model call uses the same xy recentering as PPO."""from __future__ import annotations
import hashlibimport jsonimport copyfrom pathlib import Path
import numpy as npimport torch
from go2nrd.contact_nrd.model import ContactNRD, model_configfrom go2nrd.sim.bank import npz_membersfrom go2nrd.sim.quat import step_rotvec
def sha256(path): h = hashlib.sha256() with open(path, "rb") as f: for x in iter(lambda: f.read(8 << 20), b""): h.update(x) return h.hexdigest()
def atomic_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") tmp.replace(path)
def averaged(raw, previous, dt=0.02): out = raw.clone() out[..., 19:22] = (raw[..., :3] - previous[..., :3]) / dt out[..., 22:25] = step_rotvec(previous[..., 3:7], raw[..., 3:7]) / dt out[..., 25:37] = (raw[..., 7:19] - previous[..., 7:19]) / dt return out
class WindowSampler: """Sample complete 20ms histories and branches within audited episode pieces.
`descriptors` comes from fixed_base.data.load_arm. No cached source split is used here: only its explicit audited row indices. The first state in a history has two preceding records, so all rates are averaged and no history crosses a cut. Sampling is balanced by domain when requested; otherwise it is uniform over eligible control windows, including probes. """
def __init__(self, descriptors, history=4, device="cpu", seed=0, balance_domains=True): self.sources = [] self.k, self.device = int(history), torch.device(device) self.rng = np.random.default_rng(seed) self.balance_domains = balance_domains self.cache = {} self.draw_counts = {} for desc in descriptors: p = Path(desc["path"]) system = json.loads((p / "system.json").read_text()) if abs(system["record_step_s"] - .01) > 1e-12: raise ValueError("WindowSampler requires 10ms source records") arrays = npz_members(p / "unified_data.npz") rows = np.array(desc["indices"], dtype=np.int64) if not len(rows): continue self.sources.append(dict(desc=desc, arrays=arrays, rows=rows, system=system)) if not self.sources: raise ValueError("no source episodes") self.system = self.sources[0]["system"] for s in self.sources[1:]: for key in ("bodies", "pairs", "record_step_s", "model_step_s"): if s["system"][key] != self.system[key]: raise ValueError(f"source structure differs: {key}") self.summary = {"history": self.k, "representation": "world37_avg20_xy_recentered", "rows": {s["desc"]["domain"]: len(s["rows"]) for s in self.sources}, "balanced_domains": bool(balance_domains), "boundary_history": "full, earliest record >= 2"}
def _pools(self, horizon, kind): key = int(horizon), kind if key in self.cache: return self.cache[key] pools = [] for src in self.sources: a = src["arrays"] all_rows, all_records = [], [] for row in src["rows"]: rs = np.arange(2 * self.k, int(a["lengths"][row]) - 2 * horizon, 2, dtype=np.int64) if kind != "all" and len(rs): # Averaged-rate target uses current AND previous model interval. labels = np.asarray(a["contacts"][row])[rs[:, None] + np.arange(-2, 2)].any(1) count = labels.sum(-1) keep = count == 0 if kind == "free" else count == 1 if kind == "single" else count > 0 if kind == "free": # Legacy core excludes residual response immediately after a labelled interval. keep &= ~np.asarray(a["contacts"][row])[rs - 3].any(-1) if src["desc"]["domain"] == "crm": if "crm_free" not in a: raise ValueError("CRM free-core windows require crm_free evidence") keep &= np.asarray(a["crm_free"][row])[rs[:, None] + np.arange(-2, 2)].all(1) rs = rs[keep] all_rows.append(np.full(len(rs), row, dtype=np.int64)) all_records.append(rs) pools.append(np.stack((np.concatenate(all_rows), np.concatenate(all_records)), axis=1)) if sum(map(len, pools)) == 0: raise ValueError(f"no {kind} windows with horizon {horizon}") self.cache[key] = pools return pools
def sample(self, batch, horizon=1, kind="all"): pools = self._pools(horizon, kind) sizes = np.array(list(map(len, pools)), float) prob = (sizes > 0).astype(float) if self.balance_domains else sizes src_choices = self.rng.choice(len(pools), int(batch), p=prob / prob.sum()) chunks = [] for si in np.unique(src_choices): n = int((src_choices == si).sum()) src, pool = self.sources[si], pools[si] picks = pool[self.rng.integers(len(pool), size=n)] e, r = picks[:, 0], picks[:, 1] a = src["arrays"] hr = r[:, None] + 2 * np.arange(1 - self.k, 1)[None] tr = r[:, None] + 2 * np.arange(1, horizon + 1)[None] ar = r[:, None] + 2 * np.arange(horizon)[None] d = lambda x, dtype=torch.float64: torch.as_tensor(np.array(x), dtype=dtype, device=self.device) hist_raw, hist_prev = d(a["robot"][e[:, None], hr]), d(a["robot"][e[:, None], hr - 2]) truth_raw, truth_prev = d(a["robot"][e[:, None], tr]), d(a["robot"][e[:, None], tr - 2]) contact_r = ar[:, :, None] + np.arange(-2, 2)[None, None] gate = np.asarray(a["contacts"][e[:, None, None], contact_r]).any(2) out = dict(hist=averaged(hist_raw, hist_prev)[:, :, None], targets=averaged(truth_raw, truth_prev)[:, :, None], actions=d(a["action"][e[:, None], ar])[:, :, None], gates=d(gate), ground=d(a["ground_features"][e]), instantaneous=hist_raw[:, -1], command=d(a["command"][e, r]), phase_k=d(a["phase_k"][e, r], torch.long), last_action=d(a["raw_action"][e, r - 2]), source=torch.full((n,), int(si), device=self.device), row=d(e, torch.long), record=d(r, torch.long)) out["ok"] = torch.ones((n, self.k), dtype=torch.bool, device=self.device) chunks.append(out) domain = src["desc"]["domain"] self.draw_counts[domain] = self.draw_counts.get(domain, 0) + n return {k: torch.cat([c[k] for c in chunks]) for k in chunks[0]}
class RareRolloutSampler: """Opt-in train-only replacements after an unchanged uniform rollout draw.
The independent RNG never touches the base sampler, torch RNG, one-step draws, initialization or validation. A rare start has at least one future *20ms target pose* above the threshold within its fully available branch. Replacements remain in the original domain and sample uniformly over that domain's eligible rare windows. Nothing pads or joins exported pieces. """
def __init__(self, sampler, manifest_path, fraction=.25, tilt_degrees=30., seed=0): self.sampler = sampler self.fraction, self.tilt_degrees = float(fraction), float(tilt_degrees) if not 0 <= self.fraction <= 1 or not 0 < self.tilt_degrees < 180: raise ValueError("invalid rare rollout fraction/tilt threshold") manifest = json.loads(Path(manifest_path).read_text()) digest = sha256(manifest_path) self.parents = [] for src in sampler.sources: d = src["desc"] if d["split"] != "train" or d["manifest_sha256"] != digest: raise ValueError("rare rollout sampling requires the pinned training split") rows = {r["index"]: r for r in manifest["sources"][d["domain"]]["rows"]} train_parents = {rows[int(i)]["parent_id"] for i in src["rows"]} if any(r["parent_id"] in train_parents and r["split"] != "train" for r in rows.values()): raise ValueError("rare rollout parent crosses the training split") self.parents.append({int(i): rows[int(i)]["parent_id"] for i in src["rows"]}) self.rng = np.random.default_rng(seed) self.config = dict(fraction=self.fraction, tilt_degrees=self.tilt_degrees, seed=int(seed), manifest_sha256=digest, definition="any future20ms target tilt strictly above threshold") self.cache, self.stats, self.prefixes = {}, {}, {}
def _pool(self, horizon, si): key = int(horizon), int(si) if key in self.cache: return self.cache[key] pool = self.sampler._pools(horizon, "all")[si] src = self.sampler.sources[si] a, pieces = src["arrays"], [] cosine = np.cos(np.deg2rad(self.tilt_degrees)) # Prefix sums avoid a windows x horizon allocation at every curriculum H. rows, first, sizes = np.unique(pool[:, 0], return_index=True, return_counts=True) for row, begin, size in zip(rows, first, sizes): starts = pool[begin:begin + size, 1] if (si, int(row)) not in self.prefixes: q = np.asarray(a["robot"][row, :int(a["lengths"][row]):2, 3:7], dtype=np.float64) cos_tilt = 1 - 2 * (q[:, 1:3] ** 2).sum(-1) / (q ** 2).sum(-1) self.prefixes[si, int(row)] = np.r_[0, np.cumsum(cos_tilt < cosine)] prefix = self.prefixes[si, int(row)] control = starts // 2 keep = prefix[control + horizon + 1] - prefix[control + 1] > 0 pieces.append(np.stack((np.full(int(keep.sum()), row, dtype=np.int64), starts[keep]), 1)) rare = np.concatenate(pieces) if pieces else np.empty((0, 2), dtype=np.int64) self.cache[key] = rare tag = f"{horizon}/{src['desc']['domain']}" available = dict(eligible_uniform_windows=len(pool), eligible_rare_windows=len(rare), eligible_rare_parents=len({self.parents[si][int(row)] for row in rare[:, 0]}), rare_pool_sha256=hashlib.sha256(rare.astype('<i8', copy=False).tobytes()).hexdigest()) if tag in self.stats: if any(self.stats[tag][k] != v for k, v in available.items()): raise ValueError("resumed rare pool differs from checkpoint") else: self.stats[tag] = {**available, "uniform_draws": 0, "requested_replacements": 0, "applied_replacements": 0, "empty_pool_fallbacks": 0, "uniform_rare_draws": 0, "returned_rare_draws": 0, "replacement_parent_draws": {}, "replacement_start_draws": {}} return rare
def _gather(self, si, picks, horizon): """Materialize already-audited rare picks without consuming any RNG.""" src, k = self.sampler.sources[si], self.sampler.k a, e, r = src["arrays"], picks[:, 0], picks[:, 1] # Explicit boundaries protect against accidental cache/schema changes. if not np.isin(e, src["rows"]).all() or not ((r >= 2 * k) & (r % 2 == 0) & (r + 2 * horizon < np.asarray(a["lengths"])[e])).all(): raise ValueError("rare pick violates training row or same-piece history") hr = r[:, None] + 2 * np.arange(1 - k, 1)[None] tr = r[:, None] + 2 * np.arange(1, horizon + 1)[None] ar = r[:, None] + 2 * np.arange(horizon)[None] d = lambda x, dtype=torch.float64: torch.as_tensor(np.array(x), dtype=dtype, device=self.sampler.device) gate = np.asarray(a["contacts"][e[:, None, None], ar[:, :, None] + np.arange(-2, 2)]).any(2) n = len(picks) return dict(hist=averaged(d(a["robot"][e[:, None], hr]), d(a["robot"][e[:, None], hr - 2]))[:, :, None], targets=averaged(d(a["robot"][e[:, None], tr]), d(a["robot"][e[:, None], tr - 2]))[:, :, None], actions=d(a["action"][e[:, None], ar])[:, :, None], gates=d(gate), ground=d(a["ground_features"][e]), instantaneous=d(a["robot"][e, r]), command=d(a["command"][e, r]), phase_k=d(a["phase_k"][e, r], torch.long), last_action=d(a["raw_action"][e, r - 2]), source=torch.full((n,), int(si), device=self.sampler.device), row=d(e, torch.long), record=d(r, torch.long), ok=torch.ones((n, k), dtype=torch.bool, device=self.sampler.device))
def _is_rare(self, targets): q = targets[..., 3:7] cosine = 1 - 2 * q[..., 1:3].square().sum(-1) / q.square().sum(-1) return (cosine < np.cos(np.deg2rad(self.tilt_degrees))).any((1, 2))
def sample(self, batch, horizon): b = self.sampler.sample(batch, horizon) if self.fraction == 0: return b # Exact opt-out, including no independent RNG consumption. requested = self.rng.random(int(batch)) < self.fraction for si, src in enumerate(self.sampler.sources): positions = np.flatnonzero(b["source"].cpu().numpy() == si) if not len(positions): continue rare = self._pool(horizon, si) stats = self.stats[f"{horizon}/{src['desc']['domain']}"] chosen = positions[requested[positions]] stats["uniform_draws"] += len(positions) stats["requested_replacements"] += len(chosen) stats["uniform_rare_draws"] += int(self._is_rare(b["targets"][positions]).sum()) if len(rare) and len(chosen): picks = rare[self.rng.integers(len(rare), size=len(chosen))] replacement = self._gather(si, picks, horizon) for key in b: b[key][chosen] = replacement[key] stats["applied_replacements"] += len(chosen) for row, record in picks: for key, value in (("replacement_parent_draws", str(self.parents[si][int(row)])), ("replacement_start_draws", f"{row}:{record}")): stats[key][value] = stats[key].get(value, 0) + 1 elif len(chosen): stats["empty_pool_fallbacks"] += len(chosen) stats["returned_rare_draws"] += int(self._is_rare(b["targets"][positions]).sum()) return b
def state_dict(self): return copy.deepcopy(dict(config=self.config, rng=self.rng.bit_generator.state, stats=self.stats))
def load_state_dict(self, state): if state["config"] != self.config: raise ValueError("rare rollout checkpoint config differs") self.rng.bit_generator.state = copy.deepcopy(state["rng"]) self.stats = copy.deepcopy(state["stats"]) self.cache.clear()
def report(self, horizon=None): def exposure(v): parents, starts = v["replacement_parent_draws"], v["replacement_start_draws"] return dict(applied_fraction=v["applied_replacements"] / max(1, v["uniform_draws"]), returned_rare_fraction=v["returned_rare_draws"] / max(1, v["uniform_draws"]), unique_replacement_parents=len(parents), unique_replacement_starts=len(starts), maximum_replacement_parent_draws=max(parents.values(), default=0), maximum_replacement_start_draws=max(starts.values(), default=0), repeated_start_draws=sum(starts.values()) - len(starts)) counters = ("replacement_parent_draws", "replacement_start_draws") rows, totals = {}, {} for key, value in self.stats.items(): if horizon is None or key.startswith(f"{horizon}/"): rows[key] = {**{k: v for k, v in value.items() if k not in counters}, **exposure(value)} domain = key.split('/', 1)[1] total = totals.setdefault(domain, dict(uniform_draws=0, applied_replacements=0, returned_rare_draws=0, replacement_parent_draws={}, replacement_start_draws={})) for k in ("uniform_draws", "applied_replacements", "returned_rare_draws"): total[k] += value[k] for k in counters: for item, count in value[k].items(): total[k][item] = total[k].get(item, 0) + count return dict(config=self.config, by_horizon_domain=rows, cumulative_by_domain={k: {**{n: v for n, v in t.items() if n not in counters}, **exposure(t)} for k, t in totals.items()})
def recenter(hist): off = hist[:, -1:, :, :2] return torch.cat((hist[..., :2] - off, hist[..., 2:]), -1), off[:, 0]
def step(model, hist, ok, action, ground, gates=None): """Identical xy convention to Go2NrdSim; optional teacher gates for fitting.""" if getattr(model, "state_frame", None) is not None: return model.world_step(hist, ok, action, ground=ground, gates=gates) hc, off = recenter(hist) if gates is None: nxt, info = model.details(hc, ok, action, ground=ground) else: cur, diff, lag = model.code(hc, ok) core = model.run_core(cur, diff, action, lag) logits = model.logits(cur, diff, action, lag, ground=ground) change = model.contact_sum(cur, diff, action, lag, gates, ground=ground) nxt = model.assemble(cur, core, change) info = dict(logits=logits, gates=gates, core=core, contact=change) return torch.cat((nxt[..., :2] + off, nxt[..., 2:]), -1), info
def build_model(system, config): mc = model_config(.02, config["history"], config["network"], ["articulated"], 3, 32) if "state_frame" in config: from .yaw_frame import FRAME_VERSION from .yaw_frame_adapter import YawFrameContactNRD if config["state_frame"] != FRAME_VERSION: raise ValueError("Unsupported training state frame") mc["state_frame"] = FRAME_VERSION return YawFrameContactNRD(mc, system, [[1.] * 37]) return ContactNRD(mc, system, [[1.] * 37])
@torch.no_grad()def initialize_from_train(model, sampler, samples=8192, ridge=.1): """Train-only maps; free-motion core ridge, isolated-contact residual ridge.
No validation statistics, teacher weights, old NRD weights, or old fitted normalization are consumed. Contact supervision stays the stored label. """ if any(s["desc"].get("split", "train") != "train" for s in sampler.sources): raise ValueError("normalization sampler must be training only") state_frame = getattr(model, "state_frame", None) if state_frame is not None: from types import SimpleNamespace from .yaw_frame import FRAME_VERSION, canonicalize_history, to_local if state_frame != FRAME_VERSION: raise ValueError("Unsupported normalization state frame") original_sampler = sampler
def canonical_sample(*args, **kwargs): batch = original_sampler.sample(*args, **kwargs) history, frame = canonicalize_history(batch["hist"], batch["ok"]) return {**batch, "hist": history, "targets": to_local(batch["targets"], frame)}
# Same three draw calls/order/RNG; every fitted map sees local coordinates. sampler = SimpleNamespace(sources=original_sampler.sources, sample=canonical_sample) b = sampler.sample(samples) h, _ = recenter(b["hist"]) cur, diff, act = h[:, -1, 0], h[:, 1:, 0] - h[:, :-1, 0], b["actions"][:, 0, 0] floor = torch.tensor([.01] * 3 + [.01] * 4 + [.01] * 12 + [.05] * 6 + [.1] * 12, device=cur.device) mean, std = cur.mean(0), cur.std(0).clamp_min(floor) dstd = diff.flatten(0, 1).std(0).clamp_min(floor * .1) amean, astd = act.mean(0), act.std(0).clamp_min(.01) for net in (model.core, model.collision, model.contact): net.in_mean[:, 0] = mean net.in_std[:, 0] = std net.diff_std[:, 0] = dstd net.act_mean[:, 0] = amean net.act_std[:, 0] = astd delta = b["targets"][:, 0, 0] - b["hist"][:, -1, 0] rate_scale = delta[:, 19:].std(0).clamp_min(torch.tensor([.02] * 6 + [.1] * 12, device=cur.device)) state_scale = std.clone() state_scale[:2] = .2 state_scale[2] = .05 state_scale[3:7] = .1 state_scale[7:19] = state_scale[7:19].clamp_min(.1) free = sampler.sample(samples, kind="free") fh, _ = recenter(free["hist"]) fc = fh[:, -1, 0] fa = free["actions"][:, 0, 0] y = free["targets"][:, 0, 0] - free["hist"][:, -1, 0]
def fit(x, y, lam): ym = y.mean(0) eye = torch.eye(x.shape[1], dtype=x.dtype, device=x.device) beta = torch.linalg.solve(x.T @ x + lam * eye, x.T @ (y - ym)) residual = y - ym - x @ beta ys = residual.std(0).clamp_min(1e-4) return ym, ys, beta / ys
x = torch.cat(((fc - mean) / std, (fa - amean) / astd, torch.ones_like(fc[:, :1])), -1) ym, ys, beta = fit(x, y, ridge) model.core.out_mean[0] = ym model.core.out_std[0] = ys model.core.lin[0] = beta single = sampler.sample(samples, kind="single") sh, _ = recenter(single["hist"]) sc, sd, sl = model.code(sh, single["ok"]) sa = single["actions"][:, 0] dc = model.run_core(sc, sd, sa, sl) residual = single["targets"][:, 0] - single["hist"][:, -1] - dc counts = [] for p in range(4): sel = single["gates"][:, 0, p].bool() count = int(sel.sum()) counts.append(count) model.contact.out_std[p, :37] = delta.std(0).clamp_min(1e-4) if count < 32: continue cc, aa = sc[sel, 0], sa[sel, 0] # Contact TokenNet has 2 role slots; the fixed partner is zero padding. x = torch.cat(((cc - mean) / std, torch.zeros_like(cc), (aa - amean) / astd, torch.zeros_like(aa), torch.ones_like(cc[:, :1])), -1) ym, ys, beta = fit(x, residual[sel, 0], ridge) model.contact.out_mean[p, :37] = ym model.contact.out_std[p, :37] = ys model.contact.lin[p, :, :37] = beta initialization = {"samples": samples, "single_contact_counts": counts, "normalization_split": "train", "core": "free-window ridge", "contact": "single-pair ridge", "history_noise": "none"} if state_frame is not None: from .yaw_frame import metadata initialization["state_frame"] = metadata() initialization["draws"] = "Same ordered general/free/single training draws; no extra sampling" return dict(rate_scale=rate_scale, state_scale=state_scale, initialization=initialization)12345678910111213141516171819202122232425262728293031323334353637383940414243444546#!/bin/bash# lateral_stuck_20261108 track P2 (ppo_nrdv3; copy of the track P script): one PPO run (recipe, seed) in the frozen nrd_v3 FRESH-b NRD# (loader 501c9b8d) + its train-only CRM OOD reference (overlay_nrdv3_ood.json) on one Euler GPU.# sbatch -w NODE ppo_nrdv3_euler.sbatch CODE_SNAPSHOT RECIPE.json SEED LABEL# Output (durable, NFS, resumable from last.pt): /srv/home/hzhang699/go2nrd/studies/lateral_stuck_20261108/ppo_nrdv3/runs/LABEL#SBATCH -J lsp-ppo-nrdv3#SBATCH -p research#SBATCH --gres=gpu:1#SBATCH -c 8#SBATCH --mem=24G#SBATCH -t 01:00:00#SBATCH --signal=B:USR1@180#SBATCH -o /srv/home/hzhang699/go2nrd/studies/lateral_stuck_20261108/ppo_nrdv3/logs/%x_%j.outset -eo pipefailCODE=${1:?code snapshot}; RECIPE=${2:?recipe json name}; SEED=${3:?seed}; LABEL=${4:?label}ROOT=/srv/home/hzhang699/go2nrd/studies/lateral_stuck_20261108OUT=$ROOT/ppo_nrdv3/runs/$LABELmkdir -p "$OUT" "$ROOT/ppo_nrdv3/logs"for P in /scratch/hzhang699/go2nrd_envs/go2eval/bin/python /scratch/hzhang699/envs/go2eval/bin/python; do [ -x "$P" ] && PY=$P && breakdone[ -n "$PY" ] || { echo "no go2eval python on $(hostname)"; exit 3; }export PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 OMP_NUM_THREADS=8 OPENBLAS_NUM_THREADS=1export PYTHONPATH=$ROOT/env/ppo_v3_pydeps:$CODE/src"$PY" -B - <<'PY'import torch, importlib.metadata as m, rsl_rl, tensordictassert torch.__version__.startswith('2.12.') and torch.cuda.is_available(), torch.__version__assert m.version('rsl-rl-lib') == '5.0.1' and tensordict.__version__ == '0.14.3', (m.version('rsl-rl-lib'), tensordict.__version__)x = torch.tensor([2.], device='cuda', requires_grad=True); (x * x).sum().backward(); torch.cuda.synchronize()assert x.grad.item() == 4.print('torch', torch.__version__, torch.cuda.get_device_name(0), 'rsl-rl-lib 5.0.1', rsl_rl.__file__, flush=True)PYCHILD=trap '[ -z "$CHILD" ] || kill -USR1 "$CHILD" 2>/dev/null || true' USR1 TERMcd "$OUT"timeout --signal=USR1 --kill-after=60s 3300 "$PY" -B -m go2nrd.fixed_base.ppo_lateral_v3 \ --base "$CODE/recipes/base_ppo71_config.json" --recipe "$CODE/recipes/$RECIPE" --paths "$CODE/recipes/paths_euler_nrdv3.json" --overlay "$CODE/recipes/overlay_nrdv3_ood.json" --nrd-sha256 501c9b8da022caf9594ad9cd7c50a7eda1e00424e5d4c9c7c8add65ee788848c \ --seed "$SEED" --output "$OUT" --device cuda --max-seconds 3000 --track P2_ppo_nrdv3 > "$OUT/train_${SLURM_JOB_ID}.log" 2>&1 &CHILD=$!set +ewait "$CHILD"; RC=$?if kill -0 "$CHILD" 2>/dev/null; then wait "$CHILD"; RC=$?; fiprintf '{"job_id":"%s","exit_code":%s,"host":"%s","recipe":"%s","seed":%s,"label":"%s","code":"%s"}\n' \ "$SLURM_JOB_ID" "$RC" "$(hostname)" "$RECIPE" "$SEED" "$LABEL" "$CODE" > "$OUT/job_${SLURM_JOB_ID}.json"tail -3 "$OUT/train_${SLURM_JOB_ID}.log"exit "$RC"123456789{ "name": "nrdv3_FRESHb_ood_reference_v1", "description": "NRD arm overlay of track P2 (ppo_nrdv3): the CRM kNN OOD reference rows = the train-only FRESH-b CRM corpus (8000 crm_prod PPO-pool starts = half of the old draw + 8000 lateral v2 TRAIN starts, HIP + CUDA), build_ood_reference.py; all thresholds recomputed from these rows by the env code (stock for V2, nominal-family p99 for V3). Rigid reference unchanged. Merged after the recipe; the recipe files are unchanged.", "ood": { "reference_file": { "crm": "@ood_ref_crm" } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071{ "name": "v3_V2", "description": "V2 = V1 + gait terms: swing_peak (clock-swing peak foot-bottom height vs 8 cm, weight -6), foot_drag (relu(-h) |v_foot,xy|, weight -20), lateral_shortfall (relu(1 - v_along/|vy_cmd|), weight -1).", "env": { "branch_s_lateral": 4.0, "commands": { "lateral_mix": { "lateral": 0.5, "diagonal": 0.15, "vy": [ 0.2, 0.5 ], "lateral_vx": 0.1, "wz": 0.15, "diag_vx": [ 0.2, 0.5 ], "diag_forward_fraction": 0.6, "sign_from_start": true, "sign_min_vy": 0.15 } }, "start": { "groups": { "file": "@start_groups", "share": { "stuck_drag": 0.15, "stuck": 0.15, "soft": 0.15, "other": 0.55 }, "grounds": [ "crm" ] } } }, "rewards": { "anchor": { "command_scale": { "lateral": 0.2, "other": 1.0, "vy_min": 0.2 } }, "terms": { "ood": { "weight": -1.0, "dt_scale": false } }, "gait_terms": { "swing_peak": { "weight": -6.0, "target_m": 0.08 }, "foot_drag": { "weight": -20.0 }, "lateral_shortfall": { "weight": -1.0, "vy_min": 0.2 } } }, "ppo": { "std_max": 0.2 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""Export an rsl_rl 5.0.1 checkpoint of the mjlab Go2 actor layout into a deploy folder (policy.onnx + config.yaml).
New code (judges worker, 2026-10-30). The deploy format is the one of``legged_rl_deploy_push/policies/go2/unitree_rl_mjlab/velocity/policy.onnx`` (mjlab's own export of model_10000.pt,sha256 c58a3494...): the actor's observation normaliser ``(obs - mean) / (std + 0.01)`` followed by the47-512-256-128-12 ELU MLP, the deterministic mean as output; input ``obs`` float32 [1, 47], output ``actions`` float32[1, 12]; opset 18; static shapes; one file; ops Sub, Div, Gemm, Elu, Gemm, Elu, Gemm, Elu, Gemm; initializers``obs_normalizer._mean``, ``mlp.{0,2,4,6}.{weight,bias}`` and the folded ``std + eps``; mjlab's metadata(``run_path``, ``joint_names``, ``joint_stiffness``, ``joint_damping``, ``default_joint_pos``, ``command_names``,``observation_names``, ``action_scale``). Method: the ``state_dict`` path of the reference exporter(legged_rl_deploy/policies/go2/unitree_rl_mjlab/velocity/export_onnx.py): rebuild the actor from ``actor_state_dict``(strict load into :class:`go2nrd.policy.mjlab_policy.MjlabActor`, the rsl_rl 5.0.1 key layout), ``torch.onnx.export``with the same arguments (``dynamo=False``), metadata copied from the reference ONNX with ``run_path`` set to the newrun's name. None of the copied fields depends on the iteration; the fine-tune keeps the joint order, gains, defaults,observation and action scale (the export refuses a checkpoint whose layout differs).
Outputs in ``--out``: ``policy.onnx``; ``config.yaml`` = the mjlab deploy config (``--template``) with ``model_path``set to the absolute path of the new ONNX and a provenance comment; ``policy_export.json`` (checkpoint sha256 /iteration, the ONNX description, the structure check against the reference, the torch-vs-ONNX verification).
Run (env ``go2eval``: torch 2.12, onnx 1.22, onnxruntime 1.30; or env ``unitree_rl_mjlab``, then the check uses``onnx.reference``)::
PYTHONPATH=/home/harry/go2_sand/nrd/src python -B -m go2nrd.eval.export_onnx --checkpoint RUN/model_X.pt \\ --out /home/harry/go2_sand/nrd_data/eval/policies/<name> [--run-name NAME]
Then ``python -m go2nrd.eval.parity --folder OUT`` (env go2eval) checks it against legged_sim_eval's DeployPolicy onrecorded observations."""from __future__ import annotations
import argparseimport datetime as _dtimport hashlibimport ioimport jsonimport osimport sysimport tempfilefrom pathlib import Path
import numpy as np
REFERENCE_ONNX = Path("/home/harry/go2_sand/legged_rl_deploy_push/policies/go2/unitree_rl_mjlab/velocity/policy.onnx")REFERENCE_SHA256 = "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45"TEMPLATE_CONFIG = Path("/home/harry/go2_sand/legged_rl_deploy/policies/go2/unitree_rl_mjlab/velocity/config.yaml")OBS_DIM, ACT_DIM, OPSET = 47, 12, 18FIXED_METADATA = ("joint_names", "joint_stiffness", "joint_damping", "default_joint_pos", "command_names", "observation_names", "action_scale")
def sha256_bytes(b: bytes) -> str: return hashlib.sha256(b).hexdigest()
def load_actor(ckpt_path: Path): """(MjlabActor in eval mode on the CPU, checkpoint description). Strict load: the layout must be the mjlab one.""" import torch
from go2nrd.policy.mjlab_policy import MjlabActor
data = Path(ckpt_path).read_bytes() ckpt = torch.load(io.BytesIO(data), map_location="cpu", weights_only=False) if isinstance(ckpt, dict) and "actor_state_dict" not in ckpt and "obs_normalizer._mean" in ckpt: ckpt = {"actor_state_dict": ckpt, "iter": -1} # a bare actor state_dict (same keys) if not isinstance(ckpt, dict) or "actor_state_dict" not in ckpt: raise ValueError(f"{ckpt_path}: not an rsl_rl 5 checkpoint (no actor_state_dict)") actor = MjlabActor() actor.load_state_dict(ckpt["actor_state_dict"], strict=True) actor = actor.float().eval() for p in actor.parameters(): p.requires_grad_(False) infos = ckpt.get("infos") or {} desc = dict(file=str(Path(ckpt_path).resolve()), sha256=sha256_bytes(data), size_bytes=len(data), iteration=int(ckpt.get("iter", -1)), common_step_counter=(infos.get("env_state") or {}).get("common_step_counter"), actor_normaliser_count=int(ckpt["actor_state_dict"]["obs_normalizer.count"]), std=[float(x) for x in ckpt["actor_state_dict"]["distribution.std_param"]]) return actor, desc
def describe_onnx(path: Path) -> dict: import onnx from onnx import numpy_helper
m = onnx.load(str(path), load_external_data=False) shape = lambda v: [d.dim_value if d.HasField("dim_value") else d.dim_param for d in v.type.tensor_type.shape.dim] # noqa: E731 inits = {i.name: list(numpy_helper.to_array(i).shape) for i in m.graph.initializer} return dict(file=str(path), sha256=sha256_bytes(Path(path).read_bytes()), size_bytes=Path(path).stat().st_size, opset=[int(o.version) for o in m.opset_import if o.domain in ("", "ai.onnx")], inputs={i.name: shape(i) for i in m.graph.input}, outputs={o.name: shape(o) for o in m.graph.output}, ops=[n.op_type for n in m.graph.node], initializers=inits, dtypes={i.name: int(i.type.tensor_type.elem_type) for i in [*m.graph.input, *m.graph.output]}, external_data=any(t.data_location == onnx.TensorProto.EXTERNAL for t in m.graph.initializer), metadata={p.key: p.value for p in m.metadata_props}, ir_version=int(m.ir_version))
def structure_check(new: dict, ref: dict) -> dict: """The new ONNX has the reference's IO names / shapes / dtypes, opset, op list, initializer shapes (by role) and metadata keys (and the fixed metadata values).""" shapes_new = sorted(map(tuple, new["initializers"].values())) shapes_ref = sorted(map(tuple, ref["initializers"].values())) named = [k for k in ref["initializers"] if not k.startswith("onnx::")] checks = dict( inputs=new["inputs"] == ref["inputs"], outputs=new["outputs"] == ref["outputs"], dtypes=new["dtypes"] == ref["dtypes"], opset=new["opset"] == ref["opset"], ops=new["ops"] == ref["ops"], initializer_shapes=shapes_new == shapes_ref, initializer_names=all(new["initializers"].get(k) == ref["initializers"][k] for k in named), metadata_keys=sorted(new["metadata"]) == sorted(ref["metadata"]), metadata_fixed_values=all(new["metadata"].get(k) == ref["metadata"][k] for k in FIXED_METADATA), single_file=not new["external_data"]) return dict(checks=checks, ok=bool(all(checks.values())))
def export(actor, out: Path, metadata: dict) -> None: import onnx import torch
fd, tmp = tempfile.mkstemp(prefix=".policy_", suffix=".onnx", dir=out.parent) os.close(fd) torch.onnx.export(actor, (torch.zeros(1, OBS_DIM),), tmp, export_params=True, opset_version=OPSET, input_names=["obs"], output_names=["actions"], dynamic_axes={}, dynamo=False) model = onnx.load(tmp) del model.metadata_props[:] for k, v in metadata.items(): e = onnx.StringStringEntryProto() e.key, e.value = k, v model.metadata_props.append(e) onnx.checker.check_model(model) onnx.save(model, tmp) os.chmod(tmp, 0o644) os.replace(tmp, out)
def onnx_runner(path: Path): """(fn obs [n, 47] -> [n, 12] row by row (static batch 1, as the deploy), evaluator name).""" try: import onnxruntime as ort
so = ort.SessionOptions() so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC so.intra_op_num_threads = 1 sess = ort.InferenceSession(str(path), sess_options=so, providers=["CPUExecutionProvider"]) fn = lambda obs: np.concatenate([sess.run(None, {"obs": r[None]})[0] for r in obs.astype(np.float32)]) # noqa: E731 return fn, f"onnxruntime {ort.__version__} (CPU, ORT_ENABLE_BASIC, 1 thread)" except ImportError: import onnx from onnx.reference import ReferenceEvaluator
ev = ReferenceEvaluator(str(path)) fn = lambda obs: np.concatenate([ev.run(None, {"obs": r[None]})[0] for r in obs.astype(np.float32)]) # noqa: E731 return fn, f"onnx.reference {onnx.__version__}"
def verify(path: Path, actor, n: int = 1000, seed: int = 0, extra_obs: np.ndarray | None = None) -> dict: """max |ONNX - torch actor| on N(0, 1), normaliser mean + std N(0, 1) and (optional) recorded observations.""" import torch
fn, evaluator = onnx_runner(path) rng = np.random.default_rng(seed) mean = actor.obs_normalizer._mean.numpy().reshape(-1).astype(np.float64) std = actor.obs_normalizer._std.numpy().reshape(-1).astype(np.float64) sets = {"random": rng.standard_normal((n, OBS_DIM)).astype(np.float32), "realistic": (mean + std * rng.standard_normal((n, OBS_DIM))).astype(np.float32)} if extra_obs is not None: sets["recorded"] = np.asarray(extra_obs, np.float32) res = dict(evaluator=evaluator, n_per_set={k: int(len(v)) for k, v in sets.items()}, seed=seed, max_abs_diff={}) for name, obs in sets.items(): with torch.no_grad(): y_t = actor(torch.from_numpy(obs)).numpy() y_o = fn(obs) res["max_abs_diff"][name] = float(np.abs(y_o - y_t).max()) res["max_abs_diff"][f"{name}/max_abs_action"] = float(np.abs(y_o).max()) res["max_onnx_vs_torch"] = max(v for k, v in res["max_abs_diff"].items() if "/" not in k) return res
def config_text(template: Path, model_path: Path, provenance: str) -> str: lines = template.read_text().splitlines() out, n = [], 0 for ln in lines: if ln.strip().startswith("model_path:"): ind = ln[: len(ln) - len(ln.lstrip())] out.append(f"{ind}# go2nrd.eval.export_onnx: {provenance}") ln = f"{ind}model_path: {model_path}" n += 1 out.append(ln) if n != 1: raise ValueError(f"{template}: expected one model_path line, found {n}") return "\n".join(out) + "\n"
def recorded_obs(n: int = 2048, seed: int = 0) -> np.ndarray | None: """Policy observations recorded in mjlab (rigid_test raw shard 0, the mjlab collector), n rows at random.""" shard = Path("/home/harry/go2_sand/nrd_data/raw/rigid_test/rigid_test_s0000.npz") if not shard.exists(): return None from go2nrd.collect.common.contract import load_raw_shard
eps, _ = load_raw_shard(shard) obs = np.concatenate([e.obs for e in eps]) obs = obs[np.isfinite(obs).all(1)] return obs[np.random.default_rng(seed).choice(len(obs), min(n, len(obs)), replace=False)]
def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--checkpoint", required=True, help="rsl_rl 5.0.1 model_<it>.pt with actor_state_dict") ap.add_argument("--out", required=True, help="deploy folder to write (policy.onnx, config.yaml, policy_export.json)") ap.add_argument("--run-name", default=None, help="metadata run_path (default: the checkpoint's folder name)") ap.add_argument("--reference", default=str(REFERENCE_ONNX), help="reference deploy ONNX (metadata + structure)") ap.add_argument("--template", default=str(TEMPLATE_CONFIG), help="deploy config.yaml template") ap.add_argument("--atol", type=float, default=1e-4) args = ap.parse_args(argv) out = Path(args.out).resolve() out.mkdir(parents=True, exist_ok=True) ref = Path(args.reference) ref_desc = describe_onnx(ref) actor, ck = load_actor(Path(args.checkpoint)) run_name = args.run_name or Path(args.checkpoint).resolve().parent.name metadata = dict(ref_desc["metadata"]) metadata["run_path"] = run_name onnx_path = out / "policy.onnx" export(actor, onnx_path, metadata) desc = describe_onnx(onnx_path) struct = structure_check(desc, ref_desc) check = verify(onnx_path, actor, extra_obs=recorded_obs()) prov = f"{Path(args.checkpoint).resolve()} (iteration {ck['iteration']}, sha256 {ck['sha256'][:16]}...)" (out / "config.yaml").write_text(config_text(Path(args.template), onnx_path, prov)) import onnx import torch record = dict(exporter="go2nrd.eval.export_onnx", method="state_dict (MjlabActor strict load, torch.onnx.export " "opset 18, dynamo=False, static [1, 47]; metadata copied from the reference, run_path replaced)", checkpoint=ck, run_path=run_name, exported_at=_dt.datetime.now().isoformat(timespec="seconds"), python=sys.executable, versions=dict(torch=torch.__version__, onnx=onnx.__version__, numpy=np.__version__), reference=dict(file=str(ref), sha256=ref_desc["sha256"], is_mjlab_export=ref_desc["sha256"] == REFERENCE_SHA256), onnx=desc, structure=struct, verification=check, config=dict(file=str(out / "config.yaml"), template=str(args.template), template_sha256=sha256_bytes(Path(args.template).read_bytes()))) (out / "policy_export.json").write_text(json.dumps(record, indent=1) + "\n") print(json.dumps(dict(onnx=str(onnx_path), sha256=desc["sha256"], structure=struct, verification=check), indent=1)) ok = struct["ok"] and check["max_onnx_vs_torch"] <= args.atol print(f"[export_onnx] {'OK' if ok else 'FAILED'} -> {out}") return 0 if ok else 1
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""PPO v3 entrypoint (lateral_stuck_20261108 track B): the PPO71/72 recipe in the same frozen NRD with a recipe overlay.
Base = the exact executed PPO71 config (runs/fixed_base_20261102/ppo/horizon_h50_u13500_s61_p71_diagnostic_v1/config.json: start rows, 1024 envs, rewards, OOD reference, PPO settings). Only paths are remapped to the host(data dirs by basename, NRD member, teacher = init checkpoint = anchor reference) and the overlay is deep-merged(dicts merged, other values replaced; "@start_groups" -> paths.start_groups). An empty overlay reproduces PPO71'srecipe (tested against the original runtime capsule: tests in studies/lateral_stuck_20261108/ppo_v3).
Checks: NRD sha256 5c33043b... (seed61 H50 u13500 frame+short), teacher sha256 7ee303f9...; NRD weights frozen(tensor digest before / after), actor normaliser unchanged, consumed OOD reference unchanged (ppo_study helpers).Outputs (RUN): config.json, recipe.json (overlay + lateral_v3 description), start.json, metrics.jsonl, model_*.pt,last.pt, complete.json, frozen_audit.json, policy.onnx (runner export). Re-running the same command resumes.
python -m go2nrd.fixed_base.ppo_lateral_v3 --base BASE_CONFIG.json --recipe RECIPE.json --paths PATHS.json \ --seed 81 --output RUN [--device cuda] [--max-seconds S]
Track P2 options (lateral_stuck_20261108 ppo_nrdv3; default off, the commands above are unchanged bit for bit): --nrd-sha256 SHA the expected sha256 of paths.nrd (default the seed61 NRD 5c33043b...), e.g. the retrained NRD nrd_v3 FRESH-b loader export 501c9b8d...; recorded as lineage nrd_sha256. --overlay FILE an NRD-arm overlay JSON deep-merged AFTER the recipe ("@key" -> paths[key]), e.g. the train-only OOD reference of that NRD (ood.reference_file); recorded as lineage overlay / overlay_sha256."""from __future__ import annotations
import argparseimport copyimport jsonimport osimport threadingimport timefrom pathlib import Path
import torch
from .data import sha256_filefrom .ppo_study import TEACHER_SHA, capture_ood_reference, tensor_digestfrom go2nrd.rl.config import strip_commentsfrom go2nrd.rl.runner import FineTuneRunner, write_config
NRD_SHA = "5c33043b55951658d3bc2ccce0f442124218f2a5c294d8ae6a7f8c0affcd5bbe"
def deep_merge(base, over): out = copy.deepcopy(base) for k, v in over.items(): if k.startswith("_"): continue if isinstance(v, dict) and isinstance(out.get(k), dict): out[k] = deep_merge(out[k], v) else: out[k] = copy.deepcopy(v) return out
def substitute(x, table): if isinstance(x, dict): return {k: substitute(v, table) for k, v in x.items()} if isinstance(x, list): return [substitute(v, table) for v in x] if isinstance(x, str) and x.startswith("@"): return table[x[1:]] return x
def build_config(base, recipe, paths, seed): cfg = copy.deepcopy(base) cfg.pop("fixed_base_lineage", None) data = paths["data"] cfg["data"] = [dict(d, dir=data[Path(d["dir"]).name]) for d in cfg["data"]] cfg["nrd"]["members"] = [paths["nrd"]] cfg["init_checkpoint"] = paths["teacher"] cfg["rewards"]["anchor"]["reference"] = paths["teacher"] over = substitute({k: v for k, v in recipe.items() if k not in ("name", "description")}, paths) cfg = deep_merge(cfg, over) cfg["seed"] = int(seed) return strip_comments(cfg)
class V3Runner(FineTuneRunner): def _infos(self): return dict(super()._infos(), lateral_v3_lineage=self.cfg.get("lateral_v3_lineage"))
def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--base", type=Path, required=True) p.add_argument("--recipe", type=Path, required=True) p.add_argument("--paths", type=Path, required=True) p.add_argument("--seed", type=int, required=True) p.add_argument("--output", type=Path, required=True) p.add_argument("--device", default="cuda") p.add_argument("--max-seconds", type=float, default=None, help="stop (save last.pt) after this many seconds") p.add_argument("--skip-sha", action="store_true", help="tests only: do not check NRD / teacher hashes") p.add_argument("--max-iterations", type=int, default=None, help="smoke: override runner.max_iterations") p.add_argument("--warmup", type=int, default=None, help="smoke: override runner.warmup_iterations") p.add_argument("--track", default="B_ppo", help="lineage track label (default B_ppo, the Track B runs)") p.add_argument("--nrd-sha256", default=NRD_SHA, help="expected sha256 of paths.nrd (default seed61 5c33043b...)") p.add_argument("--overlay", type=Path, default=None, help="NRD-arm overlay JSON merged after the recipe") a = p.parse_args() base = json.loads(a.base.read_text()) recipe = json.loads(a.recipe.read_text()) paths = json.loads(a.paths.read_text()) if not a.skip_sha: if sha256_file(paths["teacher"]) != TEACHER_SHA: raise ValueError("teacher checkpoint changed") if sha256_file(paths["nrd"]) != a.nrd_sha256: raise ValueError(f"NRD checkpoint sha256 is not {a.nrd_sha256[:8]}... (default: seed61 H50 u13500 5c33043b...)") cfg = build_config(base, recipe, paths, a.seed) overlay = None if a.overlay is not None: # Track P2: NRD-arm overlay after the recipe overlay = json.loads(a.overlay.read_text()) cfg = strip_comments(deep_merge(cfg, substitute({k: v for k, v in overlay.items() if k not in ("name", "description")}, paths))) if a.max_iterations is not None: cfg["runner"]["max_iterations"] = a.max_iterations if a.warmup is not None: cfg["runner"]["warmup_iterations"] = a.warmup cfg["lateral_v3_lineage"] = dict(study="lateral_stuck_20261108", track=a.track, recipe=recipe.get("name"), recipe_sha256=sha256_file(a.recipe), base_config_sha256=sha256_file(a.base), nrd_sha256=a.nrd_sha256, teacher_sha256=TEACHER_SHA, original47_actor=True, training="PPO inside frozen NRD", final_eligible=False) if overlay is not None: cfg["lateral_v3_lineage"].update(overlay=overlay.get("name"), overlay_sha256=sha256_file(a.overlay)) a.output.mkdir(parents=True, exist_ok=True) existing = a.output / "config.json" if existing.exists() and json.loads(existing.read_text()) != json.loads(json.dumps(cfg)): raise ValueError("resume configuration changed; use a new output directory") write_config(cfg, a.output) if (a.output / "complete.json").exists(): print("already complete") return t0 = time.time() runner = V3Runner(cfg, a.output, a.device) env = runner.env rec = dict(recipe=recipe, v3=env.v3.describe() if env.v3 is not None else None, host=os.uname().nodename, torch=torch.__version__, gpu=torch.cuda.get_device_name(0) if torch.cuda.is_available() else None) (a.output / "recipe.json").write_text(json.dumps(rec, indent=1) + "\n") frozen = env.sim.models if any(q.requires_grad for m in frozen for q in m.parameters()): raise AssertionError("dynamics parameters are not frozen") before = tensor_digest(frozen) norm_before = {k: v.clone() for k, v in runner.actor.state_dict().items() if k.startswith("obs_normalizer.")} ood_before = capture_ood_reference(env, a.output) if a.max_seconds: def stop_later(): time.sleep(max(1.0, a.max_seconds - (time.time() - t0))) runner._stop = True print(f"[max-seconds] {a.max_seconds:.0f} s reached: stop after this iteration", flush=True) threading.Thread(target=stop_later, daemon=True).start() result = runner.learn() after = tensor_digest(frozen) norm_ok = all(torch.equal(v, runner.actor.state_dict()[k]) for k, v in norm_before.items()) audit = dict(reason=result, nrd_before_sha256=before, nrd_after_sha256=after, unchanged=before == after, teacher_actor_normalization_unchanged=norm_ok, ood_reference=capture_ood_reference(env, a.output), lineage=cfg["lateral_v3_lineage"], wall_s=time.time() - t0) if audit["ood_reference"] != ood_before: raise AssertionError("consumed OOD reference changed") (a.output / "frozen_audit.json").write_text(json.dumps(audit, indent=2) + "\n") if before != after or not norm_ok: raise AssertionError("frozen dynamics or original actor normalization changed")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898"""Go2NrdVecEnv: the rsl_rl 5.0.1 VecEnv of the fine-tune, around go2nrd.sim (Go2NrdSim + NrdPolicyLoop + StartBank).
New code (go2nrd PPO worker, 2026-10-30). One env step = one policy step = one 20 ms NRD step.
Starts: recorded K-state NRD histories (20 ms step-average rates; K = the NRD's history, sim.k: 4 for the contractmodels) of the training split (StartBank(history=K), default task families nominal + difficult, k >= K - 1 (env.startmin_k, raised to K - 1 if lower: 3 for K = 4, as before) so the history is full and the last raw action is therecorded one, review D8),with the recorded phase counter k, last raw action, collision switches and air time. Environments are split intoone block per ground present in the data (rigid / CRM: equal shares when both exist), and inside a block intosub-blocks per NRD member serving that ground; each block always restarts from its own ground's starts. The groundid (and, for a sim that takes them, the per-start continuous ground features) goes to the NRD.Commands: per branch, with probability recorded_fraction the recorded command stream of the start's episode(command[2 (k0 + t)], held after the recording ends); otherwise uniform in the evaluation envelope (vx [-0.5, 1],vy [-0.5, 0.5], wz [-1, 1]) with standing_fraction zero commands, resampled once at a random step of the branch.commands.vx_draw "balanced" (reward set C): vx of an envelope draw is forward (U[0, vx_hi]) with probabilityforward_fraction (default 0.5), else backward (U[vx_lo, 0]); vy, wz stay uniform (sample_envelope).Branches: branch_s seconds (default 5 s = 250 steps); the first branch of each env has a random length (staggeredtime-outs); time-outs are bootstrapped with V(final observation) (extras["final_obs"], FineTunePPO).Terminations (model rules): base z < 0.15 m or tilt > 45 deg, non-finite NRD output; reward term `termination`.Observations: TensorDict(actor [n, 47] = go2nrd.policy.obs actor terms + mjlab's training noise (uniform additive,env.yaml: gyro 0.2, gravity 0.05, joint pos 0.01, joint vel 1.5; off in eval), critic [n, 74] clean, contact forcesfilled by force_fill (default "contact_mean", build_nrd_step.md section 5)).Logging: per-ground sums kept on the device (no host sync per step); pop_log() at the end of an iteration.Labels (labels_base, 2026-11-01): the start banks take contact_prev / gate_prev / air time from the config's"labels" (top level, or per data entry {"dir": D, "labels": FILE}; a go2nrd.labels override of that data dir; none= the stored contacts, as before). check_labels refuses a bank whose label rule_id differs from the training labelsof the NRD members (env.labels_check false to allow it). The config (with the labels) is saved in RUN/config.json.
Round-1 exploitation options (ppo_anchor worker, 2026-10-30; all default off, arms A-D unchanged bit for bit): rewards.anchor {weight, grounds ["crm"], mode "centered" | "sample", dt_scale true, reference null}: action anchor reward -weight x dt x A (weight >= 0) on the envs whose start ground is in `grounds`, A = |a - a_ref|^2 - |a - mu|^2 ("centered", default) or |a - a_ref|^2 ("sample"); a = the raw (sampled) action, mu = the acting policy's mean of this step (set by the runner in env.action_mean; a if not given), a_ref = the frozen reference actor's mean (rsl_rl MLPModel, weights of `reference` or init_checkpoint) on the SAME noisy actor observation. E[A] = |mu - a_ref|^2 in both modes; "centered" is exactly 0 while mu = a_ref (iteration 0, critic warm-up) and has no gradient on the action std (the "sample" form also pays the exploration noise 12 std^2). env.start.crm_bin_share {soft, medium, firm} (or a list in that order): CRM starts drawn by soil bin to these shares (bin chosen first, then a uniform start of that bin); bins = the nrdeval rule on the start episode's ground features (soft: cohesion < 250 Pa and friction < 0.7; firm: cohesion > 1500 Pa; medium: the rest). env.log_soil_bins (default: on when either option above is on): per-soil-bin logs of the CRM block. The termination penalty is rewards.terms.termination.weight (x dt; -10 = -0.2 per model-rule termination).
Soft-soil robustness options (arm ppo_soft worker, 2026-10-31; nrd/reports/arm_ppo_soft.md; all default off, arms A-Eunchanged bit for bit): env.disturb {grounds, bin_scale, kicks {...}, lean {...}}: (a) Poisson base roll / pitch-rate kicks and (b) sustained roll (/ pitch) rate-bias windows of 0.5-3 s ("sinking side") added to the NRD's predicted base angular rate on the envs of `grounds` (default CRM), with the quaternion re-integrated by the NRD's own rule (go2nrd.rl.disturb). The rewards, terminations and the next NRD step see the disturbed state. Logged per soil bin (crm.disturb). ood.threshold {family "nominal", quantile 0.99, scale 1, value null, grounds null}: (c) the out-of-corpus threshold of each ground's kNN reference = the quantile of the leave-one-out mean kNN distance of the reference draw's rows of that family (vx_diag.md: nominal p99 about 4.8 vs the stock 10.0 set by the difficult family's tail), or a fixed value; ood.ground_weight {rigid, crm}: per-ground multiplier of the OOD cost (the term weight stays rewards.terms.ood.weight). ood.reference_file {ground: npz} (lateral_stuck_20261108 track P2, default off): (d) the kNN reference draw rows of that ground come from a precomputed file (feat [M, 45], family [M], family_names) instead of the start pool, e.g. the train-only corpus of a retrained NRD; whitening, reference points, stock and family thresholds are then computed from these rows by the same code (Go2NrdVecEnv._reference_rows). rewards.anchor.ground_weight {rigid, crm}: per-ground multiplier of the anchor weight w on the anchored grounds (e.g. grounds ["rigid", "crm"], ground_weight {"rigid": 3}: rigid envs priced 3 w; keeps the gait on rigid-ground states near the reference while the CRM envs learn the lean response).
Lateral-sand recipe options (lateral_stuck_20261108 track B, "PPO v3"; go2nrd.rl.lateral_v3; all default off,every earlier config unchanged bit for bit): env.commands.lateral_mix (lateral / diagonal command draws inside thedeploy clip), env.branch_s_lateral (longer lateral branches), env.start.groups (start-pool weighting, e.g. towardthe STUCK CRM starts), rewards.anchor.command_scale (anchor weight by command), rewards.gait_terms (swing_peak,foot_drag, lateral_shortfall). See the module docstring of go2nrd.rl.lateral_v3.
Everything runs under torch.inference_mode (buffers are inference tensors)."""from __future__ import annotations
import inspectimport ioimport mathfrom pathlib import Path
import torchfrom tensordict import TensorDict
from rsl_rl.env import VecEnv
from go2nrd.collect.common import contract as Cfrom go2nrd.nrdeval.common import FIRM_COHESION_PA, SOFT_COHESION_PA, SOFT_FRICTIONfrom go2nrd.policy.obs import ACTORfrom go2nrd.rl import lateral_v3from go2nrd.rl.disturb import RateDisturbance, apply_rate_perturbation, heading_ratesfrom go2nrd.rl.ood import CorpusReference, GroundOOD, ood_featuresfrom go2nrd.rl.rewards import RewardTerms, tilt_terminated, total_commandfrom go2nrd.sim.bank import StartBankfrom go2nrd.sim.loop import NrdPolicyLoopfrom go2nrd.sim.nrd_sim import Go2NrdSim, MemberLayout
GROUND_NAMES = {v: k for k, v in C.GROUND_IDS.items()} # 0 rigid, 1 crmNOISE_COLS = dict(base_ang_vel=ACTOR["base_ang_vel"], projected_gravity=ACTOR["projected_gravity"], joint_pos=ACTOR["joint_pos"], joint_vel=ACTOR["joint_vel"])LOG_KEYS = ("steps", "reward", "track_err_vx", "track_err_vy", "track_err_wz", "track_steps", "power_w", "tau_sat_frac", "tau_085_frac", "tau_peak_rel", "ood_cost", "ood_active", "ood_knn", "ood_cost_all", "terminated", "fell", "nonfinite", "time_out", "ends", "contact_duty", "roll_abs", "pitch_abs", "roll_abs_lat", "lat_steps")LATERAL_VY = 0.2 # "lateral" envs for the in-NRD lean signal (vx_diag.md 1b): |cmd vy| >= 0.2, settledSOIL_BINS = ("soft", "medium", "firm")BIN_LOG_KEYS = ("steps", "reward", "track_err_vx", "track_err_vy", "track_err_wz", "track_steps", "power_w", "terminated", "fell", "anchor", "anchor_dev", "anchor_weighted", "starts")DIST_LOG_KEYS = ("steps", "applied", "lean_on", "kick_on", "new_lean", "new_kick", "d_roll_abs", "d_pitch_abs", "roll_abs", "pitch_abs", "roll_rate_abs", "pitch_rate_abs", "roll_abs_lean", "fell", "fell_lean", "ood_cost")DIST_ROWS = ("soft", "medium", "firm", "other")
def soil_bin_index(ground_features): """[n] long soil bin of version-B ground features [n, 3]: -1 rigid (is_crm 0), 0 soft, 1 medium, 2 firm (the nrdeval rule: c = 250 (17^f1 - 1) Pa, mu = 0.6 + 0.3 f2; soft c < 250 and mu < 0.7, firm c > 1500, medium otherwise).""" f = torch.nan_to_num(torch.as_tensor(ground_features).to(torch.float64)) crm = f[:, 0] > 0.5 c = 250.0 * torch.expm1(f[:, 1] * math.log(17.0)) mu = 0.6 + 0.3 * f[:, 2] b = torch.ones(len(f), dtype=torch.long, device=f.device) b = torch.where((c < SOFT_COHESION_PA) & (mu < SOFT_FRICTION), torch.zeros_like(b), b) b = torch.where(c > FIRM_COHESION_PA, torch.full_like(b, 2), b) return torch.where(crm, b, torch.full_like(b, -1))
def parse_bin_share(share): """{soft, medium, firm} dict or a 3-list -> float64 tensor [3] (normalised to sum 1).""" if isinstance(share, dict): extra = set(share) - set(SOIL_BINS) if extra: raise ValueError(f"crm_bin_share: unknown bins {sorted(extra)} (soft, medium, firm)") v = [float(share.get(b, 0.0)) for b in SOIL_BINS] else: v = [float(x) for x in share] if len(v) != 3: raise ValueError("crm_bin_share: 3 values (soft, medium, firm)") if min(v) < 0 or sum(v) <= 0: raise ValueError(f"crm_bin_share {share}: non-negative, sum > 0") t = torch.tensor(v, dtype=torch.float64) return t / t.sum()
def sample_envelope(lo, hi, n, gen, standing_fraction=0.1, vx_draw="uniform", forward_fraction=0.5): """Envelope commands [n, 3]: u = U[0, 1)^3 (one torch.rand(n, 3) draw), c = lo + (hi - lo) u, then a zero command with probability standing_fraction (one torch.rand(n) draw). vx_draw "balanced": vx = hi_x u_x / f if u_x < f else lo_x (u_x - f) / (1 - f), f = forward_fraction (needs lo_x < 0 < hi_x): forward U[0, hi_x] with probability f, backward U[lo_x, 0] otherwise, from the same uniform (the random stream is the uniform draw's).""" u = torch.rand(n, 3, device=lo.device, generator=gen) c = lo + (hi - lo) * u if vx_draw == "balanced": f = float(forward_fraction) if not (0.0 < f < 1.0) or not (float(lo[0]) < 0.0 < float(hi[0])): raise ValueError(f"balanced vx draw needs 0 < forward_fraction < 1 and vx_lo < 0 < vx_hi ({lo[0]}, {hi[0]})") ux = u[:, 0] c[:, 0] = torch.where(ux < f, hi[0] * (ux / f), lo[0] * ((ux - f) / (1.0 - f))) elif vx_draw != "uniform": raise ValueError(f"commands.vx_draw {vx_draw!r}: uniform or balanced") stand = torch.rand(n, device=lo.device, generator=gen) < standing_fraction return torch.where(stand[:, None], torch.zeros_like(c), c)
def bank_labels(d, cfg): """StartBank keyword for the labels of one data entry (go2nrd.labels, 2026-11-01): the entry's "labels", else the config's top-level "labels" (a <name>.labels.npz of that data dir); none = the stored contacts (no keyword, the bank of before).""" spec = d.get("labels", cfg.get("labels")) return {} if spec is None or spec == "stored" else {"labels": spec}
def check_labels(banks, sim, enabled=True): """The start banks must carry the labels of the NRD they serve ("stored" = the exported contacts): every member's training labels (checkpoint runtime) and every bank's labels have one rule (go2nrd.labels.io.rule_key: rule, ground and params, numbers as floats; labels_review 2026-11-01: rule_id alone refused 25 vs 25.0). Raises ValueError on a mismatch unless env.labels_check is false.""" if not enabled: return from go2nrd.labels.io import rule_key ids, keys = {}, set() who = [(f"NRD {p}", pk.get("labels") or {}) for p, pk in zip(getattr(sim, "paths", []), getattr(sim, "packets", []))] who += [(f"bank {b.root}", getattr(b, "labels", None) or {}) for b in banks] for name, lab in who: ids.setdefault(lab.get("rule_id", "stored"), []).append(name) keys.add(rule_key(lab)) if len(ids) > 1 and len(keys) > 1: # one rule_id, or one canonical rule (numbers as floats): accepted raise ValueError(f"labels of the NRD members and the start banks differ (rule_id: who): {ids}; give the bank " "the labels file of the NRD's rule for this data dir (config labels / data[i].labels, " "rl.train --labels), or set env.labels_check false")
def ground_features_of(start, ground): """Version-B continuous ground features f [n, 3] (NRD_PLAN section 10): [is_crm, log1p(cohesion / 250) / log(17), (friction - 0.6) / 0.3] for CRM, 0 for rigid. From start["ground_features"] if the bank gives them, else from start["soil"] [n, 4] (cohesion, friction, density, E), else is_crm only.""" if "ground_features" in start: return torch.nan_to_num(start["ground_features"].to(torch.float64)) is_crm = (ground == C.GROUND_IDS["crm"]).to(torch.float64) f = torch.zeros(len(ground), 3, dtype=torch.float64, device=ground.device) f[:, 0] = is_crm if "soil" in start: soil = torch.nan_to_num(start["soil"].to(torch.float64)) f[:, 1] = torch.log1p(soil[:, 0] / 250.0) / math.log(17.0) * is_crm f[:, 2] = (soil[:, 1] - 0.6) / 0.3 * is_crm return f
def ground_mode(sim): """How the sim takes the ground of each env: "kw" (a ground_features= keyword), "features" (ground= [B, F] float features: members expose n_ground_features, the continuous version-B code of NRD_PLAN section 10) or "ids" (ground= [B] long ids: the discrete code of the first vendored model; version-A members ignore either).""" if "ground_features" in inspect.signature(sim.step).parameters: return "kw" if hasattr(sim, "n_ground_features") or any(hasattr(m, "n_ground_features") for m in getattr(sim, "models", [])): return "features" return "ids"
class _Loop(NrdPolicyLoop): """NrdPolicyLoop whose step passes each env's ground to the sim in the form the sim takes (ground_mode)."""
def __init__(self, *a, mode="ids", **kw): super().__init__(*a, **kw) self.mode = mode if not hasattr(self, "ground_features"): # older NrdPolicyLoop (ground ids only) self.ground_features = torch.zeros(self.n, 3, dtype=torch.float64, device=self.device)
@torch.inference_mode() def step(self, raw_action): raw = raw_action.to(torch.float32) target = self.default + C.ACTION_SCALE * raw.to(torch.float64) if self.mode == "kw": gk = dict(ground=self.ground, ground_features=self.ground_features) elif self.mode == "features": gk = dict(ground=self.ground_features) else: gk = dict(ground=self.ground) nxt, g, lg, info = self.sim.step(self.hist, self.ok, target, member=self.layout, **gk) self.hist, self.ok = Go2NrdSim.advance(self.hist, self.ok, nxt) self.k = self.k + 1 self.steps = self.steps + 1 self.last_action = raw self.gates = g self.air.update(g) info["logits"] = lg return nxt, g, info
class Go2NrdVecEnv(VecEnv): def __init__(self, cfg: dict, device="cuda", train=True, sim=None, banks=None): """cfg: the full fine-tune config (keys nrd, data, env, rewards, ood). train=False: no observation noise (evaluation). sim / banks: reuse already built objects (tests).""" with torch.inference_mode(): self._build(cfg, device, train, sim, banks)
# ---------------------------------------------------------------------------------------------- build def _build(self, cfg, device, train, sim, banks): self.cfg = cfg ec = cfg["env"] self.device = torch.device(device) self.train = bool(train) self.num_envs = n = int(ec["num_envs"]) self.num_actions = C.ACTION_DIM self.dt = C.CONTROL_STEP_S self.branch_steps = int(round(float(ec.get("branch_s", 5.0)) / self.dt)) self.max_episode_length = self.branch_steps self.gen = torch.Generator(device=self.device).manual_seed(int(cfg.get("seed", 0)) + 12345) nc = cfg["nrd"] members = [m if isinstance(m, dict) else {"path": m} for m in nc["members"]] if sim is None: sim = Go2NrdSim([m["path"] for m in members], self.device, max_batch=nc.get("max_batch", 4096)) self.sim = sim self.ground_arg = ground_mode(sim) # banks and per-ground pools sc = ec.get("start", {}) data = [d if isinstance(d, dict) else {"dir": d} for d in cfg["data"]] K = int(getattr(sim, "k", 4)) # NRD history length (arm nrd_hist) if banks is None: banks = [StartBank(d["dir"], splits=tuple(sc.get("splits", (0,))), families=sc.get("families"), min_steps_left=int(sc.get("min_steps_left", 1)), min_k=max(int(sc.get("min_k", K - 1)), K - 1), device=self.device, history=K, rows=d.get("rows"), **bank_labels(d, cfg)) for d in data] for bank in banks: if int(getattr(bank, "history", 4)) != K: raise ValueError(f"start bank with history {getattr(bank, 'history', 4)}, the NRD has history {K}") check_labels(banks, sim, ec.get("labels_check", True)) self.banks = banks min_pk = sc.get("min_phase_k", {}) pools = {} # ground id -> (bank index, start indices) for b, bank in enumerate(banks): pk = bank.phase_k[bank.start_e, 2 * bank.start_k] for g in sorted(set(bank.ground.tolist())): m = (bank.ground[bank.start_e] == g) & (pk >= int(min_pk.get(GROUND_NAMES.get(g, str(g)), 0))) idx = torch.nonzero(m).flatten() if g in pools: raise ValueError(f"ground {g} appears in two data dirs; merge them or pass one") if len(idx): pools[g] = (b, idx) want = ec.get("grounds") # optional subset, names or ids if want is not None: ids = [C.GROUND_IDS[w] if isinstance(w, str) else int(w) for w in want] pools = {g: pools[g] for g in ids} self.ground_ids = sorted(pools) self.ground_names = [GROUND_NAMES.get(g, str(g)) for g in self.ground_ids] G = len(self.ground_ids) shares = ec.get("ground_share") or [1.0 / G] * G sizes = [int(round(n * s / sum(shares))) for s in shares] sizes[-1] = n - sum(sizes[:-1]) # member layout: ground block -> members serving it, even sub-blocks parts, a = [], 0 self.blocks = [] # (ground id, bank index, pool, slice) for g, size in zip(self.ground_ids, sizes): serving = [i for i, m in enumerate(members) if m.get("grounds") is None or g in [C.GROUND_IDS[x] if isinstance(x, str) else int(x) for x in m["grounds"]]] if not serving: raise ValueError(f"no NRD member serves ground {g}") base, extra = divmod(size, len(serving)) for j, mi in enumerate(serving): c = base + (j < extra) if c: parts.append((mi, slice(a, a + c))) a += c b, pool = pools[g] self.blocks.append((g, b, pool, slice(a - size, a))) self.layout = MemberLayout(parts, n) dev = self.device self.ground_idx = torch.zeros(n, dtype=torch.long, device=dev) # index into ground_ids ground = torch.zeros(n, dtype=torch.long, device=dev) for gi, (g, b, pool, s) in enumerate(self.blocks): self.ground_idx[s] = gi ground[s] = g # soil-weighted CRM starts (env.start.crm_bin_share; off by default) self.bin_sampling = {} # block index -> (starts by bin, offsets, counts, share) share = sc.get("crm_bin_share") if share is not None: sh = parse_bin_share(share).to(dev) for bi, (g, b, pool, s) in enumerate(self.blocks): if GROUND_NAMES.get(g) != "crm": continue bank = self.banks[b] sb = soil_bin_index(bank.ground_features[bank.start_e[pool]]) subs = [pool[sb == i] for i in range(3)] cnt = torch.tensor([len(x) for x in subs], dtype=torch.long, device=dev) empty = [SOIL_BINS[i] for i in range(3) if cnt[i] == 0 and sh[i] > 0] if empty: raise ValueError(f"crm_bin_share: no CRM starts in bin(s) {empty}") off = torch.cumsum(cnt, 0) - cnt self.bin_sampling[bi] = (torch.cat(subs), off, cnt, sh) if not self.bin_sampling: raise ValueError("crm_bin_share set but there is no CRM block") # policy loop critic_mean = None fill = ec.get("critic_force_fill", "contact_mean") if fill == "mean": critic_mean = torch.load(cfg["init_checkpoint"], map_location="cpu", weights_only=False)[ "critic_state_dict"]["obs_normalizer._mean"] self.loop = _Loop(sim, n, layout=self.layout, ground=ground, critic_mean=critic_mean, force_fill=fill, mode=self.ground_arg) # commands cc = ec.get("commands", {}) env_rng = cc.get("envelope", dict(vx=C.EVALUATION_ENVELOPE["vx"], vy=C.EVALUATION_ENVELOPE["vy"], wz=C.EVALUATION_ENVELOPE["wz"])) self.cmd_lo = torch.tensor([env_rng["vx"][0], env_rng["vy"][0], env_rng["wz"][0]], device=dev) self.cmd_hi = torch.tensor([env_rng["vx"][1], env_rng["vy"][1], env_rng["wz"][1]], device=dev) self.recorded_fraction = float(cc.get("recorded_fraction", 0.5)) self.standing_fraction = float(cc.get("standing_fraction", 0.1)) self.vx_draw = str(cc.get("vx_draw", "uniform")) self.forward_fraction = float(cc.get("forward_fraction", 0.5)) self.resamples = int(cc.get("resamples", 1)) if self.resamples not in (0, 1): raise ValueError("commands.resamples: 0 or 1") # observation noise (mjlab env.yaml actor group, uniform additive) nz = ec.get("obs_noise", {}) self.noise_on = bool(nz.get("enabled", True)) and self.train self.noise = torch.zeros(47, device=dev) for k, sl in NOISE_COLS.items(): self.noise[sl] = float(nz.get(k, dict(base_ang_vel=0.2, projected_gravity=0.05, joint_pos=0.01, joint_vel=1.5)[k])) tc = ec.get("termination", {}) self.min_z, self.max_tilt = float(tc.get("min_base_z", 0.15)), float(tc.get("max_tilt_deg", 45.0)) self.settle = int(ec.get("log_settle_steps", 25)) # rewards and OOD self.rewards = RewardTerms(cfg["rewards"], dev) oc = cfg.get("ood", {}) self.ood = self._build_ood(oc) if oc.get("enabled", True) else None self.ood_grace = int(oc.get("grace_steps", 25)) # per-env buffers z = lambda *s, dt=torch.float32: torch.zeros(*s, dtype=dt, device=dev) self.episode_length_buf = z(n, dt=torch.long) # steps since the branch start self.limit = torch.full((n,), self.branch_steps, dtype=torch.long, device=dev) self.rec_e, self.rec_k0 = z(n, dt=torch.long), z(n, dt=torch.long) self.cmd_mode = z(n, dt=torch.bool) # True = recorded stream self.env_cmd, self.resample_at = z(n, 3), z(n, dt=torch.long) self.cmd_prev = z(n, 3) self.lag_ok = z(n, dt=torch.bool) self.env_bin = torch.full((n,), -1, dtype=torch.long, device=dev) # soil bin of each env's start (-1 rigid) self.bin_starts = z(3, dt=torch.float64) # starts drawn per soil bin (logged) self.log_sums = z(G, len(LOG_KEYS), dt=torch.float64) # action anchor (rewards.anchor; off by default) self.anchor = self._anchor_cfg(cfg, ground) self.action_mean = None # set by the runner before step() (centered anchor) self.extra_scales = {"anchor": self.anchor["scale"]} if self.anchor else {} lb = ec.get("log_soil_bins") self.log_bins = bool(self.anchor is not None or self.bin_sampling) if lb is None else bool(lb) # attitude-rate disturbances (env.disturb; off by default) self.disturb = None dc = ec.get("disturb") if dc: rd = RateDisturbance(dc, n, ground, dev, seed=int(cfg.get("seed", 0)), dt=self.dt) if rd.enabled: self.disturb = rd self.log_bins = True # env_bin drives the bin scale self.dist_sums = z(len(DIST_ROWS), len(DIST_LOG_KEYS), dt=torch.float64) self.bin_sums = z(3, len(BIN_LOG_KEYS), dt=torch.float64) self.log_terms = {} self.log_peak = z(G, dt=torch.float64) # lateral-sand recipe (go2nrd.rl.lateral_v3; off by default: no object, no draws) self.v3 = lateral_v3.LateralV3(cfg, self) if lateral_v3.enabled(cfg) else None if self.v3 is not None: self.extra_scales.update(self.v3.scales) # first reset: all envs, staggered first branch lengths self._reset(torch.ones(n, dtype=torch.bool, device=dev)) if ec.get("stagger", True): self.limit = torch.randint(1, self.branch_steps + 1, (n,), device=dev, generator=self.gen) if self.v3 is not None: self.v3.after_stagger() self._obs_cache = self._observations() if self.anchor is not None: self.anchor["ref"] = self._build_reference(cfg, self.anchor["reference"])
def _anchor_cfg(self, cfg, ground): ac = cfg.get("rewards", {}).get("anchor") if not ac or float(ac.get("weight", 0.0)) == 0.0: return None mode = str(ac.get("mode", "centered")) if mode not in ("centered", "sample"): raise ValueError(f"rewards.anchor.mode {mode!r}: centered or sample") names = ac.get("grounds", ["crm"]) ids = [C.GROUND_IDS[x] if isinstance(x, str) else int(x) for x in names] w = float(ac["weight"]) if w < 0: raise ValueError("rewards.anchor.weight is the positive penalty weight w (reward -w x dt x A)") dt_scale = bool(ac.get("dt_scale", True)) and bool(cfg["rewards"].get("scale_by_dt", True)) mask = torch.isin(ground, torch.tensor(ids, dtype=torch.long, device=ground.device)) gw = ac.get("ground_weight") # per-ground multiplier of w (ppo_soft; off by default) if gw: extra = set(gw) - set(names) if extra: raise ValueError(f"rewards.anchor.ground_weight: {sorted(extra)} not in anchor grounds {names}") rel = torch.zeros(len(ground), dtype=torch.float32, device=ground.device) for nm, gid in zip(names, ids): v = float(gw.get(nm, gw.get(str(gid), 1.0))) if v < 0: raise ValueError("rewards.anchor.ground_weight must be >= 0") rel = torch.where(ground == gid, torch.full_like(rel, v), rel) mask = rel return dict(weight=w, scale=-w * (0.02 if dt_scale else 1.0), mode=mode, grounds=ids, mask=mask, reference=ac.get("reference") or cfg["init_checkpoint"])
def _build_reference(self, cfg, path): """Frozen reference actor: rsl_rl MLPModel of the fine-tune's layout (the runner's actor class), weights of `path` (rsl_rl checkpoint); built without touching the global RNG streams.""" from rsl_rl.models import MLPModel from rsl_rl.modules.distribution import GaussianDistribution hid = tuple(cfg.get("ppo", {}).get("hidden_dims", (512, 256, 128))) with torch.random.fork_rng(devices=[]): ref = MLPModel(self._obs_cache, {"actor": ["actor"], "critic": ["critic"]}, "actor", self.num_actions, hidden_dims=hid, activation="elu", obs_normalization=True, distribution_cfg=dict(class_name=GaussianDistribution, init_std=1.0, std_type="scalar")) ck = torch.load(path, map_location="cpu", weights_only=False) ref.load_state_dict(ck["actor_state_dict"], strict=True) ref = ref.to(self.device).eval() for prm in ref.parameters(): prm.requires_grad_(False) ref.obs_normalizer.until = 1 return ref
def _build_ood(self, oc): refs = [] tc = oc.get("threshold") # (c) family threshold (off by default) self.ood_thresh_info = {} rfile = oc.get("reference_file") or {} # (d) precomputed reference rows (off by default) unknown = set(rfile) - set(GROUND_NAMES.get(g, str(g)) for g, *_ in self.blocks) if unknown: raise ValueError(f"ood.reference_file: grounds {sorted(unknown)} not in the env") for g, b, pool, s in self.blocks: bank = self.banks[b] m = int(oc.get("max_points", 4000)) name = GROUND_NAMES.get(g, str(g)) if name in rfile: feat, family = self._reference_rows(rfile[name], bank, name) else: gen = torch.Generator(device=self.device).manual_seed(int(oc.get("seed", 0))) take = min(len(pool), 4 * m) # distinct start rows (the S4 draw size) idx = pool[torch.randperm(len(pool), device=self.device, generator=gen)[:take]] st = bank.draw(idx) feat = ood_features(st["hist"][:, -1], st["action"]) family = st["family"] ref = CorpusReference(feat, seed=int(oc.get("seed", 0)), max_points=m, k=int(oc.get("k", 8)), quantile=float(oc.get("quantile", 0.99)), device=self.device) if tc and (tc.get("grounds") is None or name in tc["grounds"] or g in tc["grounds"]): self.ood_thresh_info[name] = self._family_threshold(ref, feat, family, bank, tc) refs.append(ref) gw = oc.get("ground_weight") weights = None if gw: extra = set(gw) - set(self.ground_names) if extra: raise ValueError(f"ood.ground_weight: grounds {sorted(extra)} not in the env {self.ground_names}") weights = [float(gw.get(nm, 1.0)) for nm in self.ground_names] if min(weights) < 0: raise ValueError("ood.ground_weight must be >= 0 (the sign is the term weight's)") return GroundOOD(refs, weights=weights)
def _reference_rows(self, path, bank, name): """(d) ood.reference_file {ground: npz}: the reference draw rows of a ground from a file instead of the start pool (e.g. the training corpus of another NRD: lateral_stuck_20261108 ppo_nrdv3/build_ood_reference.py). npz: feat [M, 45] float64 (ood_features of the recorded state and applied target), family [M] (family ids), family_names [F] (must equal the bank's system.json family names). CorpusReference and the family threshold then run on these rows exactly as on a pool draw. Recorded in ood_summary (path, sha256, rows).""" import hashlib import numpy as np raw = Path(path).read_bytes() z = np.load(io.BytesIO(raw), allow_pickle=False) feat = torch.as_tensor(np.asarray(z["feat"], dtype=np.float64), device=self.device) family = torch.as_tensor(np.asarray(z["family"]).astype(np.int64), device=self.device) names = [str(x) for x in z["family_names"]] want = [f["name"] for f in bank.system.get("families", [])] if feat.ndim != 2 or feat.shape[1] != 45 or len(family) != len(feat): raise ValueError(f"ood.reference_file[{name}]: feat {tuple(feat.shape)}, family {tuple(family.shape)}") if names != want: raise ValueError(f"ood.reference_file[{name}]: family names {names} != the bank's {want}") if not bool(torch.isfinite(feat).all()): raise ValueError(f"ood.reference_file[{name}]: non-finite features") if not hasattr(self, "ood_reference_files"): self.ood_reference_files = {} self.ood_reference_files[name] = dict(path=str(path), sha256=hashlib.sha256(raw).hexdigest(), rows=int(len(feat))) return feat, family
@staticmethod def _family_threshold(ref, feat, family, bank, tc): """(c): set ref.thresh to the quantile of the leave-one-out mean kNN distance of the draw's rows of one family (or to a fixed value); returns the record for the logs / start.json.""" stock = ref.thresh if tc.get("value") is not None: ref.thresh = float(tc["value"]) rec = dict(source="value", thresh=ref.thresh, stock=stock) else: fam = tc.get("family", "nominal") names = [f["name"] for f in bank.system.get("families", [])] fid = names.index(fam) if isinstance(fam, str) else int(fam) rows = feat[family == fid] if len(rows) <= ref.k: raise ValueError(f"ood.threshold: {len(rows)} rows of family {fam} in the reference draw") d = ref.knn_loo(rows) q = float(tc.get("quantile", 0.99)) base = float(torch.quantile(d.double(), q)) ref.thresh = base * float(tc.get("scale", 1.0)) rec = dict(source=f"family {fam}", rows=int(len(rows)), quantile=q, scale=float(tc.get("scale", 1.0)), loo_knn_mean=float(d.double().mean()), loo_knn_q=base, thresh=ref.thresh, stock=stock) return rec
def ood_summary(self): if self.ood is None: return None out = {name: r.summary() for name, r in zip(self.ground_names, self.ood.refs)} for name, rec in getattr(self, "ood_thresh_info", {}).items(): out[name]["family_threshold"] = rec for name, rec in getattr(self, "ood_reference_files", {}).items(): # (d), only when ood.reference_file is set out[name]["reference_file"] = rec if self.ood.weights is not None: for name, wgt in zip(self.ground_names, self.ood.weights): out[name]["ground_weight"] = wgt return out
# ---------------------------------------------------------------------------------------------- resets def _draw(self): """One start per env (each block from its ground's pool), concatenated in env order.""" outs = [] for bi, (g, b, pool, s) in enumerate(self.blocks): if self.v3 is not None and bi in self.v3.group_sampling: st = self.v3.draw_block(bi, b, pool, s.stop - s.start, self.gen) elif bi in self.bin_sampling: m = s.stop - s.start cat, off, cnt, sh = self.bin_sampling[bi] k = torch.multinomial(sh, m, replacement=True, generator=self.gen) u = torch.rand(m, device=self.device, generator=self.gen) j = torch.minimum((u * cnt[k]).long(), cnt[k] - 1) st = self.banks[b].draw(cat[off[k] + j]) else: st = self.banks[b].sample(s.stop - s.start, generator=self.gen, pool=pool) st["ground_features"] = ground_features_of(st, st["ground"]) outs.append(st) if len(outs) == 1: return outs[0] return {k: torch.cat([o[k] for o in outs]) for k in outs[0]}
def _sample_envelope(self, n): return sample_envelope(self.cmd_lo, self.cmd_hi, n, self.gen, self.standing_fraction, self.vx_draw, self.forward_fraction)
def _recorded_command(self, steps_ahead): """Recorded command at control step k0 + steps_ahead of each env's start episode [n, 3].""" out = torch.zeros(self.num_envs, 3, device=self.device) for g, b, pool, s in self.blocks: bank = self.banks[b] e = self.rec_e[s] r = (2 * (self.rec_k0[s] + steps_ahead[s])).clamp_max(bank.lengths[e] - 1) out[s] = bank.command[e, r].float() return out
def _reset(self, mask, start=None): n, dev = self.num_envs, self.device start = self._draw() if start is None else start m = mask self.loop.reset_where(m, start) w = lambda new, old: torch.where(m.view(-1, *([1] * (old.dim() - 1))), new.to(old.dtype), old) self.loop.ground_features = w(start["ground_features"], self.loop.ground_features) if self.log_bins: self.env_bin = w(soil_bin_index(start["ground_features"]), self.env_bin) self.bin_starts.index_add_(0, self.env_bin.clamp_min(0), (m & (self.env_bin >= 0)).to(torch.float64)) self.rec_e, self.rec_k0 = w(start["episode"], self.rec_e), w(start["k"], self.rec_k0) mode = torch.rand(n, device=dev, generator=self.gen) < self.recorded_fraction self.cmd_mode = w(mode, self.cmd_mode) self.env_cmd = w(self._sample_envelope(n), self.env_cmd) ra = torch.randint(1, max(2, self.branch_steps), (n,), device=dev, generator=self.gen) if self.resamples \ else torch.full((n,), -1, dtype=torch.long, device=dev) self.resample_at = w(ra, self.resample_at) self.loop.command = w(torch.where(self.cmd_mode[:, None], start["command"].float(), self.env_cmd), self.loop.command) self.episode_length_buf = w(torch.zeros_like(self.episode_length_buf), self.episode_length_buf) self.limit = w(torch.full_like(self.limit, self.branch_steps), self.limit) self.lag_ok = w(torch.zeros_like(self.lag_ok), self.lag_ok) self.cmd_prev = w(self.loop.command, self.cmd_prev) if self.v3 is not None: self.v3.on_reset(m, start) if self.disturb is not None: self.disturb.reset(m)
def set_starts(self, start, cmd_mode, env_cmd, resample_at=None, limit=None): """Explicit reset of all envs (evaluation): start dict of n starts, cmd_mode [n] bool (recorded stream), env_cmd [n, 3] (envelope command), resample_at [n] (-1 = never), limit [n] branch length.""" with torch.inference_mode(): n = self.num_envs start = dict(start) start.setdefault("ground_features", ground_features_of(start, start["ground"])) all_ = torch.ones(n, dtype=torch.bool, device=self.device) self.loop.reset_where(all_, start) self.loop.ground_features = start["ground_features"].to(self.loop.ground_features.dtype).clone() if self.log_bins: self.env_bin = soil_bin_index(start["ground_features"]) self.rec_e, self.rec_k0 = start["episode"].clone(), start["k"].clone() self.cmd_mode = cmd_mode.to(self.device).bool().clone() self.env_cmd = env_cmd.to(self.device).float().clone() self.resample_at = (torch.full((n,), -1, dtype=torch.long, device=self.device) if resample_at is None else resample_at.to(self.device).long().clone()) self.loop.command = torch.where(self.cmd_mode[:, None], start["command"].float(), self.env_cmd) self.episode_length_buf = torch.zeros_like(self.episode_length_buf) self.limit = (torch.full_like(self.limit, self.branch_steps) if limit is None else limit.to(self.device).long().clone()) self.lag_ok = torch.zeros_like(self.lag_ok) self.cmd_prev = self.loop.command.clone() if self.v3 is not None: # trackers only (no command / branch draws) self.v3.valid = torch.zeros_like(self.v3.valid) self.v3.swing_prev = self.v3.clock_swing(self.loop.k) if self.disturb is not None: self.disturb.reset(all_) self._obs_cache = self._observations() return self._obs_cache
# ---------------------------------------------------------------------------------------------- obs def _observations(self, noise=None): actor = self.loop.actor_obs() if (self.noise_on if noise is None else noise): u = torch.rand(actor.shape, device=self.device, generator=self.gen) * 2.0 - 1.0 actor = actor + u * self.noise critic = self.loop.critic_obs() return TensorDict({"actor": actor, "critic": critic}, batch_size=[self.num_envs], device=self.device)
def get_observations(self) -> TensorDict: return self._obs_cache
# ---------------------------------------------------------------------------------------------- step def step(self, actions): with torch.inference_mode(): return self._step(actions)
def _step(self, actions): lp = self.loop raw = actions.to(self.device, torch.float32) s0 = lp.hist[:, -1] g0, k0, cmd, raw_prev = lp.gates, lp.k, lp.command, lp.last_action target = lp.default + C.ACTION_SCALE * raw.to(torch.float64) if self.ood is not None: feat = ood_features(s0, target) ood_all, knn = self.ood.cost_knn(feat, self.ground_idx) # grace: no OOD price in the first grace_steps of a branch (the start transient: a clean action at a # recorded noisy state, tests/rl/diag_ood.py), so price and guard see the states the policy produced ood = ood_all * (self.episode_length_buf >= self.ood_grace).to(ood_all.dtype) else: ood = ood_all = knn = torch.zeros(self.num_envs, device=self.device) s1, g1, info = lp.step(raw) self.episode_length_buf = self.episode_length_buf + 1 nonfinite = info["nonfinite"] if self.disturb is not None: # (a) kicks / (b) lean on the NRD's rates d, applied = self.disturb.step(self.env_bin, s0) s1 = apply_rate_perturbation(s0, s1, d, applied & ~nonfinite, self.dt) lp.hist = torch.cat((lp.hist[:, :-1], s1[:, None]), 1) self.last_s1, self.last_nonfinite, self.last_gates = s1, nonfinite, g1 # before any reset fell = tilt_terminated(s1, self.min_z, self.max_tilt) terminated = fell | nonfinite time_out = (self.episode_length_buf >= self.limit) & ~terminated rew, terms, rx = self.rewards.compute(s0, s1, raw, raw_prev, target, cmd, self.cmd_prev, k0, g0, g1, self.lag_ok, terminated, ood) if self.anchor is not None: rew, terms = self._apply_anchor(raw, rew, terms, cmd) if self.v3 is not None: # gait terms (weight 0 / absent: logged only) rew, terms = self.v3.apply(s1, k0, cmd, rew, terms) self._accumulate(rew, terms, rx, cmd, ood, ood_all, knn, terminated, fell, nonfinite, time_out) if self.v3 is not None: self.v3.accumulate(terms, cmd, ood, self.episode_length_buf >= self.settle) if self.disturb is not None: self._accumulate_disturb(s1, rx, fell, ood) # next command (recorded stream / envelope resample) rec = self._recorded_command(self.episode_length_buf) hit = self.episode_length_buf == self.resample_at self.env_cmd = torch.where(hit[:, None], self._sample_envelope(self.num_envs), self.env_cmd) self.cmd_prev = cmd lp.command = torch.where(self.cmd_mode[:, None], rec, self.env_cmd) self.lag_ok = torch.ones_like(self.lag_ok) done = terminated | time_out final_obs = self._observations(noise=False) self._reset(done) obs = self._observations() self._obs_cache = obs extras = {"time_outs": time_out, "final_obs": final_obs, "terminated": terminated} return obs, rew, done, extras
def _apply_anchor(self, raw, rew, terms, cmd=None): """reward += scale A, scale = -w (x dt), on the anchored envs (module docstring); a_ref from the observation the policy acted on (self._obs_cache, before this step's reset); env.action_mean is consumed (None afterwards).""" an = self.anchor a_ref = an["ref"](self._obs_cache).to(torch.float32) mu = raw if self.action_mean is None else self.action_mean.to(self.device, torch.float32) self.action_mean = None d_ref = (raw - a_ref).square().sum(-1) A = d_ref - (raw - mu).square().sum(-1) if an["mode"] == "centered" else d_ref A = A * an["mask"].to(A.dtype) if self.v3 is not None and self.v3.anchor_scale is not None and cmd is not None: A = A * self.v3.anchor_factor(cmd).to(A.dtype) # (c) command-conditioned anchor weight terms = dict(terms) terms["anchor"] = A terms["anchor_dev"] = (mu - a_ref).square().sum(-1) * (an["mask"] > 0).to(A.dtype) # logged: |mu - a_ref|^2 return rew + an["scale"] * A, terms
# ---------------------------------------------------------------------------------------------- logging def _accumulate(self, rew, terms, rx, cmd, ood, ood_all, knn, terminated, fell, nonfinite, time_out): f = torch.float64 vb, wb = rx["vb"], rx["wb"] trk = (self.episode_length_buf >= self.settle).to(f) tau_u, eff = rx["tau_u"], self.rewards.effort rel = tau_u.abs() / eff lat = trk * (cmd[:, 1].abs() >= LATERAL_VY).to(f) roll_abs, pitch_abs = rx["roll"].abs().to(f), rx["pitch"].abs().to(f) cols = [torch.ones_like(trk), rew.to(f), (vb[:, 0] - cmd[:, 0]).abs() * trk, (vb[:, 1] - cmd[:, 1]).abs() * trk, (wb[:, 2] - cmd[:, 2]).abs() * trk, trk, rx["power"].to(f), (rel >= 1.0).to(f).mean(-1), (rel >= 0.85).to(f).mean(-1), rel.max(-1).values.to(f), ood.to(f), (ood > 0).to(f), knn.to(f), ood_all.to(f), terminated.to(f), fell.to(f), nonfinite.to(f), time_out.to(f), (terminated | time_out).to(f), rx["contact"].to(f).mean(-1), roll_abs * trk, pitch_abs * trk, roll_abs * lat, lat] x = torch.stack(cols, -1) self.log_sums.index_add_(0, self.ground_idx, x) for k, v in terms.items(): w = self.rewards.scales.get(k, self.extra_scales.get(k, 0.0)) val = torch.stack((v.to(f), (w * v).to(f)), -1) if k not in self.log_terms: self.log_terms[k] = torch.zeros(len(self.ground_ids), 2, dtype=f, device=self.device) self.log_terms[k].index_add_(0, self.ground_idx, val) self.log_peak = torch.maximum(self.log_peak, torch.zeros_like(self.log_peak).index_reduce_( 0, self.ground_idx, rel.max(-1).values.to(f), "amax", include_self=True)) if self.log_bins: zero = torch.zeros_like(trk) an = terms.get("anchor", zero).to(f) bc = [torch.ones_like(trk), rew.to(f), (vb[:, 0] - cmd[:, 0]).abs() * trk, (vb[:, 1] - cmd[:, 1]).abs() * trk, (wb[:, 2] - cmd[:, 2]).abs() * trk, trk, rx["power"].to(f), terminated.to(f), fell.to(f), an, terms.get("anchor_dev", zero).to(f), self.extra_scales.get("anchor", 0.0) * an, zero] x = torch.stack(bc, -1) keep = self.env_bin >= 0 self.bin_sums.index_add_(0, self.env_bin.clamp_min(0), x * keep.to(f)[:, None])
def _accumulate_disturb(self, s1, rx, fell, ood): f = torch.float64 L = self.disturb.last rr, pr = heading_rates(s1) lean = L["lean"].to(f) roll_abs = rx["roll"].abs().to(f) cols = [torch.ones_like(lean), L["applied"].to(f), lean, L["kick"].to(f), L["new_lean"].to(f), L["new_kick"].to(f), L["d"][:, 0].abs(), L["d"][:, 1].abs(), roll_abs, rx["pitch"].abs().to(f), rr.abs(), pr.abs(), roll_abs * lean, fell.to(f), fell.to(f) * lean, ood.to(f)] row = torch.where(self.env_bin >= 0, self.env_bin, torch.full_like(self.env_bin, 3)) self.dist_sums.index_add_(0, row, torch.stack(cols, -1) * self.disturb.mask.to(f)[:, None])
def _pop_disturb(self): sums = self.dist_sums.cpu().numpy() self.dist_sums.zero_() K = {k: i for i, k in enumerate(DIST_LOG_KEYS)} out = {} for i, name in enumerate(DIST_ROWS): r = sums[i] st = r[K["steps"]] if st <= 0: continue ln = max(r[K["lean_on"]], 1.0) out[name] = dict(env_steps=float(st), applied_frac=float(r[K["applied"]] / st), lean_frac=float(r[K["lean_on"]] / st), kick_frac=float(r[K["kick_on"]] / st), lean_starts_per_s=float(r[K["new_lean"]] / st / self.dt), kicks_per_s=float(r[K["new_kick"]] / st / self.dt), d_roll_abs=float(r[K["d_roll_abs"]] / st), d_pitch_abs=float(r[K["d_pitch_abs"]] / st), roll_abs=float(r[K["roll_abs"]] / st), pitch_abs=float(r[K["pitch_abs"]] / st), roll_rate_abs=float(r[K["roll_rate_abs"]] / st), pitch_rate_abs=float(r[K["pitch_rate_abs"]] / st), roll_abs_in_lean=float(r[K["roll_abs_lean"]] / ln), falls=float(r[K["fell"]]), falls_in_lean=float(r[K["fell_lean"]]), falls_per_1k_steps=float(1000.0 * r[K["fell"]] / st), ood_cost=float(r[K["ood_cost"]] / st)) return out
def pop_log(self): """Per-ground means of the logged quantities since the last call (one host sync); resets the sums.""" with torch.inference_mode(): sums = self.log_sums.cpu().numpy() terms = {k: v.cpu().numpy() for k, v in self.log_terms.items()} peak = self.log_peak.cpu().numpy() self.log_sums.zero_() for v in self.log_terms.values(): v.zero_() self.log_peak.zero_() bins = self.bin_sums.cpu().numpy() if self.log_bins else None if bins is not None: bins[:, BIN_LOG_KEYS.index("starts")] = self.bin_starts.cpu().numpy() self.bin_sums.zero_() self.bin_starts.zero_() K = {k: i for i, k in enumerate(LOG_KEYS)} out = {} for gi, name in enumerate(self.ground_names + ["all"]): row = sums.sum(0) if name == "all" else sums[gi] st = max(row[K["steps"]], 1.0) ts = max(row[K["track_steps"]], 1.0) ends = row[K["ends"]] d = dict(env_steps=float(row[K["steps"]]), reward_per_step=row[K["reward"]] / st, track_err=[row[K["track_err_vx"]] / ts, row[K["track_err_vy"]] / ts, row[K["track_err_wz"]] / ts], power_w=row[K["power_w"]] / st, tau_sat_frac=row[K["tau_sat_frac"]] / st, tau_085_frac=row[K["tau_085_frac"]] / st, tau_peak_rel=float(peak.max() if name == "all" else peak[gi]), ood_cost=row[K["ood_cost"]] / st, ood_active_frac=row[K["ood_active"]] / st, ood_knn=row[K["ood_knn"]] / st, ood_cost_all=row[K["ood_cost_all"]] / st, terminations=float(row[K["terminated"]]), falls=float(row[K["fell"]]), nonfinite=float(row[K["nonfinite"]]), time_outs=float(row[K["time_out"]]), fall_frac_of_ends=float(row[K["fell"]] / ends) if ends > 0 else 0.0, falls_per_1k_steps=1000.0 * row[K["fell"]] / st, contact_duty=row[K["contact_duty"]] / st, roll_abs=row[K["roll_abs"]] / ts, pitch_abs=row[K["pitch_abs"]] / ts, roll_abs_lat=row[K["roll_abs_lat"]] / max(row[K["lat_steps"]], 1.0), lat_share=row[K["lat_steps"]] / ts) d["terms"] = {k: dict(raw=float((v.sum(0) if name == "all" else v[gi])[0] / st), weighted=float((v.sum(0) if name == "all" else v[gi])[1] / st)) for k, v in terms.items()} out[name] = {k: (float(v) if not isinstance(v, (list, dict)) else ([float(x) for x in v] if isinstance(v, list) else v)) for k, v in d.items()} if bins is not None and "crm" in out: B = {k: i for i, k in enumerate(BIN_LOG_KEYS)} tot = max(float(bins[:, B["steps"]].sum()), 1.0) tot_st = max(float(bins[:, B["starts"]].sum()), 1.0) out["crm"]["bins"] = {} for i, b in enumerate(SOIL_BINS): r = bins[i] st, ts = max(r[B["steps"]], 1.0), max(r[B["track_steps"]], 1.0) out["crm"]["bins"][b] = dict( env_steps=float(r[B["steps"]]), step_share=float(r[B["steps"]] / tot), start_share=float(r[B["starts"]] / tot_st), reward_per_step=float(r[B["reward"]] / st), track_err=[float(r[B["track_err_vx"]] / ts), float(r[B["track_err_vy"]] / ts), float(r[B["track_err_wz"]] / ts)], power_w=float(r[B["power_w"]] / st), terminations=float(r[B["terminated"]]), falls=float(r[B["fell"]]), falls_per_1k_steps=float(1000.0 * r[B["fell"]] / st), anchor=float(r[B["anchor"]] / st), anchor_dev=float(r[B["anchor_dev"]] / st), anchor_weighted=float(r[B["anchor_weighted"]] / st)) if self.disturb is not None: with torch.inference_mode(): out["all"]["disturb"] = self._pop_disturb() if self.v3 is not None: with torch.inference_mode(): v3 = self.v3.pop() for name in self.ground_names: out[name]["v3"] = v3.get(name, {}) if "start_groups" in v3: out["all"]["v3_start_groups"] = v3["start_groups"] return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529"""Lateral-sand PPO recipe options (lateral_stuck_20261108 track B, "PPO v3"). All default off: a config without thekeys below builds no LateralV3 object and Go2NrdVecEnv runs exactly as before (same random draws, same rewards, samelogs).
Config keys (each optional; any one of them turns the helper on): env.commands.lateral_mix {lateral 0.5, diagonal 0.15, vy [0.2, 0.5], lateral_vx 0.1, wz 0.15, diag_vx [0.2, 0.5], diag_forward_fraction 0.6, sign_from_start true, sign_min_vy 0.15, grounds null} (a) Per branch: with probability `lateral` a lateral-dominant command (vy = s U(vy), vx = U(-lateral_vx, lateral_vx), wz = U(-wz, wz)), with probability `diagonal` a diagonal command (vy = s U(vy), vx = +-U(diag_vx), forward with diag_forward_fraction, wz = U(-wz, wz)); otherwise the original sampler (recorded stream / envelope) is kept. Lateral and diagonal commands are held for the whole branch (no resample). s = the sign of the start's recorded vy when |vy_rec| >= sign_min_vy and sign_from_start, else +-1 at random. env.branch_s_lateral 4.0 (f) Branch length (s) of the lateral-dominant command draws (the other draws keep env.branch_s). The first (staggered) branch is stretched by the same ratio. env.start.groups {file, share {group: share, ..., "soft": s, "other": s}, grounds ["crm"]} (b) Start-pool weighting of a ground's block: the npz `file` lists intervals (row = export row, lo / hi = record range [lo, hi), group = index into names); a start (row, k) is in a group when 2k is inside one of its intervals (first listed group wins). Built-in groups: "soft" (CRM soil bin soft, not in a file group) and "other" (the rest). A start is drawn with weight share[g] / count[g]. rewards.anchor.command_scale {lateral 0.2, other 1.0, vy_min 0.2} (c) Per-step multiplier of the anchor weight: `lateral` when |cmd vy| >= vy_min, else `other`. rewards.gait_terms {swing_peak {weight, target_m 0.08, dt_scale true}, foot_drag {weight, dt_scale true}, lateral_shortfall {weight, vy_min 0.2, dt_scale true}} (e) Extra reward terms from the NRD-predicted state s1 (FK feet, go2nrd.policy.fk.Go2LegFK; foot-bottom height h = foot-sphere centre z - radius (0.022 rigid, 0.025 CRM), z above the nominal surface): swing_peak: per foot, the peak h during each gait-clock swing window (phase(k1) >= 0.56, the foot_gait clock, k1 = phase counter of s1) is scored when the window ends: sum over ending feet of clamp(1 - peak / target_m, 0, 1.5); only windows that started inside the branch; moving commands only. foot_drag: sum over feet of relu(-h) |v_foot,xy| (FK foot velocity of s1); moving commands only. lateral_shortfall: clamp(1 - v_y,heading sign(cmd vy) / |cmd vy|, 0, 2) when |cmd vy| >= vy_min (v of s1, rotated into the heading frame of s1). reward += weight (x 0.02 if dt_scale) x term; logged as terms swing_peak / foot_drag / lateral_shortfall.Logs (grounds[g]["v3"]): per command category (orig / lateral / diagonal) the settled-step lateral ratio, drag share(h < -5 mm and foot speed > 0.1 m/s), mean sinkage, swing peak at window end, anchor deviation, OOD active share,and the start-group shares.
V3 options (lateral_stuck_20261108 track P "ppo_v3fix"; all default off, a config without them runs as above, bit forbit, with the same random draws): env.commands.lateral_mix.sign_follow_prob p (default 1.0 = the rule above) (2) A lateral / diagonal draw follows the start's recorded vy sign (when |vy_rec| >= sign_min_vy) only with probability p; otherwise its sign is +-1 at random. p < 1 draws one extra uniform per env after the command draws. With p = 0.5 at least half of all lateral draws have a sign independent of the start state. env.start.groups.extra [{dir, file, splits [0], families null, min_steps_left null, min_k null}] (1) Extra start sources for the ground block(s) of start.groups (CRM): a StartBank over the rows of `file` (npz names / row / lo / hi / group, the same interval format) in data dir `dir`; only starts inside a file interval (and with phase_k >= the env's min_phase_k of the ground) can be drawn. Group names of the extra files join the share table; a group's count is summed over all its sources, so a start is drawn with weight share[g] / count[g] whatever its source. Extra starts always get a lateral-mix command (category lateral; their recorded command stream is not in the env's banks, so the env's recorded-stream index is set to 0 for them); requires lateral_mix.lateral > 0. Sealed test rows (split 2) are refused by StartBank. rewards.gait_terms.wrong_way {weight, vy_min 0.2, cap 2.0, dt_scale true} (3) clamp(-v_y,heading sign(cmd vy) / |cmd vy|, 0, cap) when |cmd vy| >= vy_min: the explicit penalty of lateral motion against the command (lateral_shortfall saturates at 2 and does not separate "stalled" from "wrong way"). rewards.gait_terms.joint_speed {weight, free_rad_s 4.0, dt_scale true} (4) sum over joints of relu(|qd_j(s1)| - free_rad_s)^2 (step-average joint rates of the NRD state s1), all commands. With the existing action_rate_l2 / power terms (rewards.terms weights) it is the V3r smoothness / energy option. Extra logs only when one of these options is on (grounds[g]["v3"][cat]): lat_ratio_pos / lat_ratio_neg (settled lateral ratio by command sign), wrong_way_share (settled lateral steps with v_y,heading sign(cmd vy) < -0.05 m/s), wrong_way / joint_speed raw terms; all["v3_start_groups"] adds the extra-source share and the reversed-sign share of the lateral draws."""from __future__ import annotations
import math
import numpy as npimport torch
from go2nrd.collect.common import contract as Cfrom go2nrd.policy.fk import Go2LegFK
CATS = ("orig", "lateral", "diagonal")GAIT_PERIOD_S, GAIT_STANCE = 0.6, 0.56GAIT_OFFSETS = (0.0, 0.5, 0.5, 0.0) # FL FR RL RR (rewards.GAIT_OFFSETS_FL_FR_RL_RR)FOOT_R = {0: 0.022, 1: 0.025} # ground id -> foot radius (rigid mjlab, CRM)LOG_KEYS = ("steps", "lat_steps", "ratio_sum", "drag", "sink", "peak_sum", "peak_n", "anchor_dev", "ood_active", "swing_peak", "foot_drag", "lateral_shortfall", "vy_err")GAIT_TERMS = ("swing_peak", "foot_drag", "lateral_shortfall")FIX_TERMS = ("wrong_way", "joint_speed") # V3 options (track P)FIX_LOG_KEYS = ("lat_pos", "ratio_pos", "lat_neg", "ratio_neg", "wrong", "wrong_way", "joint_speed")WRONG_WAY_V = 0.05 # m/s against the command = a wrong-way step (logs)
def enabled(cfg): ec, rc = cfg.get("env", {}), cfg.get("rewards", {}) return bool(ec.get("commands", {}).get("lateral_mix") or ec.get("branch_s_lateral") or ec.get("start", {}).get("groups") or (rc.get("anchor") or {}).get("command_scale") or rc.get("gait_terms"))
def heading_velocity(s): """[n, 37] -> [n, 2] base-link velocity (state 19:21, world) in the heading (yaw) frame of the same state.""" q = s[:, 3:7] w, x, y, z = q.unbind(-1) yaw = torch.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)) c, sn = torch.cos(yaw), torch.sin(yaw) vx, vy = s[:, 19], s[:, 20] return torch.stack((c * vx + sn * vy, -sn * vx + c * vy), -1)
class LateralV3: def __init__(self, cfg, env): ec, rc = cfg["env"], cfg["rewards"] self.env = env dev = env.device n = env.num_envs self.n = n ground = torch.zeros(n, dtype=torch.long, device=dev) for g, b, pool, s in env.blocks: ground[s] = g self.ground = ground self.foot_r = torch.where(ground == C.GROUND_IDS["crm"], FOOT_R[1], FOOT_R[0]).to(torch.float64) # (a) commands lm = ec.get("commands", {}).get("lateral_mix") or {} self.p_lat, self.p_diag = float(lm.get("lateral", 0.0)), float(lm.get("diagonal", 0.0)) if self.p_lat < 0 or self.p_diag < 0 or self.p_lat + self.p_diag > 1: raise ValueError("lateral_mix: 0 <= lateral, diagonal and lateral + diagonal <= 1") self.vy = tuple(float(v) for v in lm.get("vy", (0.2, 0.5))) self.lat_vx, self.wz = float(lm.get("lateral_vx", 0.1)), float(lm.get("wz", 0.15)) self.diag_vx = tuple(float(v) for v in lm.get("diag_vx", (0.2, 0.5))) self.diag_fwd = float(lm.get("diag_forward_fraction", 0.6)) self.sign_from_start = bool(lm.get("sign_from_start", True)) self.sign_min = float(lm.get("sign_min_vy", 0.15)) self.follow_p = float(lm.get("sign_follow_prob", 1.0)) # (2) V3 option; 1.0 = no extra draw if not 0.0 <= self.follow_p <= 1.0: raise ValueError("lateral_mix.sign_follow_prob must be in [0, 1]") gl = lm.get("grounds") self.mix_mask = torch.ones(n, dtype=torch.bool, device=dev) if gl is None else torch.isin( ground, torch.tensor([C.GROUND_IDS[x] if isinstance(x, str) else int(x) for x in gl], device=dev)) self.mix_on = (self.p_lat + self.p_diag) > 0 # (f) lateral branch length bl = ec.get("branch_s_lateral") self.lat_steps = int(round(float(bl) / env.dt)) if bl else env.branch_steps self.cat = torch.zeros(n, dtype=torch.long, device=dev) # (b) start groups self.group_sampling = {} self.group_names = [] self.extra_banks = [] # (1) V3 option: extra start sources self.drawn_src = torch.zeros(n, dtype=torch.long, device=dev) # source of the last draw: 0 env bank, i + 1 extra i self.env_src = torch.zeros(n, dtype=torch.long, device=dev) # source of each env's current start self.reversed = torch.zeros(n, dtype=torch.bool, device=dev) self.lat_draws = torch.zeros(3, dtype=torch.float64, device=dev) # lateral / diagonal draws, reversed, followed gc = ec.get("start", {}).get("groups") if gc: if getattr(env, "bin_sampling", None): raise ValueError("env.start.groups and env.start.crm_bin_share are exclusive") self._build_groups(gc) G = len(env.ground_ids) self.group_starts = torch.zeros(max(len(self.group_names), 1), dtype=torch.float64, device=dev) # (c) anchor command scale cs = (rc.get("anchor") or {}).get("command_scale") self.anchor_scale = None if not cs else dict(lateral=float(cs.get("lateral", 1.0)), other=float(cs.get("other", 1.0)), vy_min=float(cs.get("vy_min", 0.2))) # (e) gait terms gt = rc.get("gait_terms") or {} sbd = bool(rc.get("scale_by_dt", True)) self.scales = {} self.params = {} for name in GAIT_TERMS + FIX_TERMS: tc = gt.get(name) if tc is None: continue tc = {"weight": tc} if isinstance(tc, (int, float)) else tc w = float(tc["weight"]) self.scales[name] = w * (C.CONTROL_STEP_S if (bool(tc.get("dt_scale", True)) and sbd) else 1.0) self.params[name] = tc unknown = set(gt) - set(GAIT_TERMS + FIX_TERMS) - {k for k in gt if k.startswith("_")} if unknown: raise ValueError(f"rewards.gait_terms: unknown {sorted(unknown)}") self.target = float(self.params.get("swing_peak", {}).get("target_m", 0.08)) self.lat_vy_min = float(self.params.get("lateral_shortfall", {}).get("vy_min", 0.2)) ww = self.params.get("wrong_way", {}) self.ww_vy_min, self.ww_cap = float(ww.get("vy_min", 0.2)), float(ww.get("cap", 2.0)) self.js_free = float(self.params.get("joint_speed", {}).get("free_rad_s", 4.0)) self.fix_on = bool(self.follow_p < 1.0 or self.extra_banks or any(t in self.params for t in FIX_TERMS)) if self.extra_banks and not (self.mix_on and self.p_lat > 0): raise ValueError("start.groups.extra needs commands.lateral_mix.lateral > 0 (extra starts take lateral " "commands)") self.fk = Go2LegFK(device=dev) self.offsets = torch.tensor(GAIT_OFFSETS, dtype=torch.float64, device=dev) self.peak = torch.zeros(n, 4, dtype=torch.float64, device=dev) self.valid = torch.zeros(n, 4, dtype=torch.bool, device=dev) self.swing_prev = torch.zeros(n, 4, dtype=torch.bool, device=dev) self.log_sums = torch.zeros(G * len(CATS), len(LOG_KEYS), dtype=torch.float64, device=dev) self.fix_sums = torch.zeros(G * len(CATS), len(FIX_LOG_KEYS), dtype=torch.float64, device=dev) \ if self.fix_on else None
# ------------------------------------------------------------------------------------------------ (b) def _build_groups(self, gc): env, dev = self.env, self.env.device names_file, iv = [], None if gc.get("file"): z = np.load(gc["file"], allow_pickle=False) names_file = [str(x) for x in z["names"]] iv = [torch.as_tensor(np.asarray(z[k]), device=dev).long() for k in ("row", "lo", "hi", "group")] extras = [self._load_extra(x, i) for i, x in enumerate(gc.get("extra") or [])] # (1) V3 option names_x = [nm for x in extras for nm in x["names"] if nm not in names_file] names_x = list(dict.fromkeys(names_x)) names = names_file + names_x + [x for x in ("soft", "other") if x not in names_file + names_x] share = gc.get("share", {}) extra = set(share) - set(names) if extra: raise ValueError(f"start.groups.share: unknown groups {sorted(extra)} (have {names})") sh = torch.tensor([float(share.get(x, 0.0)) for x in names], dtype=torch.float64, device=dev) if (sh < 0).any() or sh.sum() <= 0: raise ValueError("start.groups.share: non-negative, sum > 0") gl = gc.get("grounds", ["crm"]) ids = [C.GROUND_IDS[x] if isinstance(x, str) else int(x) for x in gl] from go2nrd.rl.env import soil_bin_index self.group_names = names self.group_info = {} for bi, (g, b, pool, s) in enumerate(env.blocks): if g not in ids: continue bank = env.banks[b] e, k = bank.start_e[pool], bank.start_k[pool] row = torch.as_tensor(np.asarray(bank.rows), device=dev).long()[e] r0 = 2 * k grp = torch.full((len(pool),), -1, dtype=torch.long, device=dev) if iv is not None: for j in range(len(names_file)): sel = iv[3] == j m = torch.zeros(len(pool), dtype=torch.bool, device=dev) for rr, lo, hi in zip(iv[0][sel].tolist(), iv[1][sel].tolist(), iv[2][sel].tolist()): m |= (row == rr) & (r0 >= lo) & (r0 < hi) grp = torch.where((grp < 0) & m, torch.full_like(grp, j), grp) soft = soil_bin_index(bank.ground_features[e]) == 0 grp = torch.where((grp < 0) & soft, torch.full_like(grp, names.index("soft")), grp) grp = torch.where(grp < 0, torch.full_like(grp, names.index("other")), grp) cnt = torch.bincount(grp, minlength=len(names)).to(torch.float64) if not extras: # Track B path (unchanged numbers) empty = [names[i] for i in range(len(names)) if cnt[i] == 0 and sh[i] > 0] if empty: raise ValueError(f"start.groups: no starts in group(s) {empty} of ground {g}") w = torch.where(cnt[grp] > 0, sh[grp] / cnt[grp].clamp_min(1.0), torch.zeros_like(sh[grp])) self.group_sampling[bi] = (w, grp) self.group_info[str(g)] = dict(counts={nm: int(c) for nm, c in zip(names, cnt.tolist())}, share={nm: float(v) for nm, v in zip(names, (sh / sh.sum()).tolist())}, pool=int(len(pool))) continue # extra sources of this ground: group index per extra start (-1 = not drawable) xg, srcs = [], [] min_pk = int(env.cfg["env"].get("start", {}).get("min_phase_k", {}).get( {v: k for k, v in C.GROUND_IDS.items()}.get(g, str(g)), 0)) for x in extras: xb = x["bank"] ok = (xb.ground[xb.start_e] == g) & (xb.phase_k[xb.start_e, 2 * xb.start_k] >= min_pk) gx = torch.where(ok & (x["grp"] >= 0), torch.tensor([names.index(nm) for nm in x["names"]], device=dev)[x["grp"].clamp_min(0)], torch.full_like(x["grp"], -1)) xg.append(gx) srcs.append(dict(name=x["name"], dir=x["dir"], starts=int(xb.n), drawable=int((gx >= 0).sum()))) cnt_all = cnt.clone() for gx in xg: cnt_all += torch.bincount(gx[gx >= 0], minlength=len(names)).to(torch.float64) empty = [names[i] for i in range(len(names)) if cnt_all[i] == 0 and sh[i] > 0] if empty: raise ValueError(f"start.groups: no starts in group(s) {empty} of ground {g}") wt = lambda gg: torch.where(gg >= 0, sh[gg.clamp_min(0)] / cnt_all[gg.clamp_min(0)].clamp_min(1.0), torch.zeros_like(sh[gg.clamp_min(0)])) w_all = torch.cat([wt(grp)] + [wt(gx) for gx in xg]) g_all = torch.cat([grp] + [gx.clamp_min(0) for gx in xg]) offs, o = [], len(pool) for x, gx in zip(extras, xg): offs.append((x["bank"], o, len(gx))) o += len(gx) self.group_sampling[bi] = (w_all, g_all, offs, s) per_src = {"env_bank": {nm: int(c) for nm, c in zip(names, cnt.tolist())}} for x, gx in zip(extras, xg): per_src[x["name"]] = {nm: int((gx == i).sum()) for i, nm in enumerate(names) if int((gx == i).sum())} self.group_info[str(g)] = dict(counts={nm: int(c) for nm, c in zip(names, cnt_all.tolist())}, counts_by_source=per_src, share={nm: float(v) for nm, v in zip(names, (sh / sh.sum()).tolist())}, pool=int(len(pool)), extra_sources=srcs) self.extra_banks = [x["bank"] for x in extras]
def _load_extra(self, xc, i): """(1) One extra start source: StartBank over the interval rows of xc["file"] in xc["dir"] -> dict(bank, grp (group index into the file's names per bank start, -1 = outside every interval), names, name, dir).""" from go2nrd.sim.bank import StartBank env, dev = self.env, self.env.device sc = env.cfg["env"].get("start", {}) z = np.load(xc["file"], allow_pickle=False) names = [str(x) for x in z["names"]] row, lo, hi, gi = (np.asarray(z[k]).astype(np.int64) for k in ("row", "lo", "hi", "group")) rows = np.unique(row) if xc.get("rows") is not None: if not np.isin(rows, np.asarray(xc["rows"])).all(): raise ValueError(f"start.groups.extra[{i}]: interval rows outside the given rows") K = int(getattr(env.sim, "k", 4)) bank = StartBank(xc["dir"], splits=tuple(xc.get("splits", (0,))), families=xc.get("families", sc.get("families")), min_steps_left=int(xc.get("min_steps_left", sc.get("min_steps_left", 1))), min_k=max(int(xc.get("min_k", sc.get("min_k", K - 1))), K - 1), device=dev, history=K, rows=rows.tolist()) e, k = bank.start_e, bank.start_k brow = torch.as_tensor(np.asarray(bank.rows), device=dev).long()[e] r0 = 2 * k grp = torch.full((bank.n,), -1, dtype=torch.long, device=dev) for rr, a, b, gg in zip(row.tolist(), lo.tolist(), hi.tolist(), gi.tolist()): m = (brow == rr) & (r0 >= a) & (r0 < b) & (grp < 0) grp = torch.where(m, torch.full_like(grp, gg), grp) return dict(bank=bank, grp=grp, names=names, name=str(xc.get("name", f"extra{i}")), dir=str(xc["dir"]))
def draw_block(self, bi, b, pool, m, gen): """m starts of block bi (start-group weights) -> bank.draw dict.""" gs = self.group_sampling[bi] w, grp = gs[0], gs[1] j = torch.multinomial(w, m, replacement=True, generator=gen) self.group_starts.index_add_(0, grp[j], torch.ones(m, dtype=torch.float64, device=w.device)) if len(gs) == 2: # Track B path return self.env.banks[b].draw(pool[j]) offs, s = gs[2], gs[3] main = j < len(pool) st = self.env.banks[b].draw(pool[torch.where(main, j, torch.zeros_like(j))]) src = torch.zeros(m, dtype=torch.long, device=w.device) for xi, (xb, off, cnt) in enumerate(offs): sel = (j >= off) & (j < off + cnt) if not bool(sel.any()): continue sx = xb.draw(torch.where(sel, j - off, torch.zeros_like(j))) for key, v in st.items(): st[key] = torch.where(sel.view(-1, *([1] * (v.dim() - 1))), sx[key].to(v.dtype), v) src = torch.where(sel, torch.full_like(src, xi + 1), src) self.drawn_src[s] = src return st
# ------------------------------------------------------------------------------------------------ (a), (f) def on_reset(self, mask, start): env, n, dev, gen = self.env, self.n, self.env.device, self.env.gen m = mask if self.mix_on: u = torch.rand(n, device=dev, generator=gen) cat = torch.where(u < self.p_lat, 1, torch.where(u < self.p_lat + self.p_diag, 2, 0)).to(torch.long) cat = torch.where(self.mix_mask, cat, torch.zeros_like(cat)) r = torch.rand(n, 6, device=dev, generator=gen) if self.extra_banks: # (1) extra starts: always a lateral command cat = torch.where(self.drawn_src > 0, torch.ones_like(cat), cat) mag = self.vy[0] + (self.vy[1] - self.vy[0]) * r[:, 0] rnd_sign = torch.where(r[:, 1] < 0.5, -1.0, 1.0) rec_vy = start["command"][:, 1].float() follow = (rec_vy.abs() >= self.sign_min) & torch.tensor(self.sign_from_start, device=dev) if self.follow_p < 1.0: # (2) V3 option: one extra draw per env follow = follow & (torch.rand(n, device=dev, generator=gen) < self.follow_p) sign = torch.where(follow, torch.sign(rec_vy), rnd_sign) if self.fix_on: rev = (rec_vy.abs() >= self.sign_min) & (sign != torch.sign(rec_vy)) & (cat > 0) self.reversed = torch.where(m, rev, self.reversed) self.lat_draws += torch.stack(((m & (cat > 0)).sum(), (m & rev).sum(), (m & (cat > 0) & follow).sum())).to(torch.float64) vy = sign * mag wz = self.wz * (2 * r[:, 2] - 1) vx_lat = self.lat_vx * (2 * r[:, 3] - 1) dmag = self.diag_vx[0] + (self.diag_vx[1] - self.diag_vx[0]) * r[:, 4] vx_diag = torch.where(r[:, 5] < self.diag_fwd, dmag, -dmag) vx = torch.where(cat == 1, vx_lat, vx_diag) new_cmd = torch.stack((vx, vy, wz), -1) take = m & (cat > 0) self.cat = torch.where(m, cat, self.cat) env.cmd_mode = torch.where(take, torch.zeros_like(env.cmd_mode), env.cmd_mode) env.env_cmd = torch.where(take[:, None], new_cmd, env.env_cmd) env.resample_at = torch.where(take, torch.full_like(env.resample_at, -1), env.resample_at) env.loop.command = torch.where(take[:, None], new_cmd, env.loop.command) env.cmd_prev = torch.where(take[:, None], new_cmd, env.cmd_prev) if self.extra_banks: # recorded-stream index of extra starts: unused xm = m & (self.drawn_src > 0) # (cmd_mode False), must index the env bank self.env_src = torch.where(m, self.drawn_src, self.env_src) env.rec_e = torch.where(xm, torch.zeros_like(env.rec_e), env.rec_e) env.rec_k0 = torch.where(xm, torch.zeros_like(env.rec_k0), env.rec_k0) if self.lat_steps != env.branch_steps: lat = m & (self.cat == 1) env.limit = torch.where(lat, torch.full_like(env.limit, self.lat_steps), env.limit) # gait-clock trackers: a window is scored only if its start is seen inside the branch self.valid = torch.where(m[:, None], torch.zeros_like(self.valid), self.valid) self.swing_prev = torch.where(m[:, None], self.clock_swing(env.loop.k), self.swing_prev)
def after_stagger(self): env = self.env if self.lat_steps != env.branch_steps: lat = self.cat == 1 stretched = torch.ceil(env.limit.to(torch.float64) * self.lat_steps / env.branch_steps).long() env.limit = torch.where(lat, stretched.clamp(1, self.lat_steps), env.limit)
def set_category(self, cat): """Evaluation: explicit command category of each env (logs only).""" self.cat = torch.as_tensor(cat, device=self.env.device).long().clone()
# ------------------------------------------------------------------------------------------------ (c) def anchor_factor(self, cmd): a = self.anchor_scale lat = cmd[:, 1].abs() >= a["vy_min"] return torch.where(lat, torch.full_like(cmd[:, 1], a["lateral"]), torch.full_like(cmd[:, 1], a["other"]))
# ------------------------------------------------------------------------------------------------ (e) def clock_swing(self, k): ph = (k.to(torch.long).to(torch.float64) * C.CONTROL_STEP_S / GAIT_PERIOD_S)[:, None] + self.offsets return (ph % 1.0) >= GAIT_STANCE
def gait(self, s1, k0, cmd): """Raw gait terms [n] (float32) and per-step foot diagnostics; updates the swing trackers.""" f64 = torch.float64 pos = self.fk.foot_positions(s1) vel = self.fk.foot_velocities(s1) h = pos[..., 2] - self.foot_r[:, None] speed = torch.linalg.norm(vel[..., :2], dim=-1) moving = (torch.linalg.norm(cmd[:, :2], dim=-1) + cmd[:, 2].abs() > 0.1).to(f64) swing = self.clock_swing(k0 + 1) starting = swing & ~self.swing_prev cont = swing & self.swing_prev ending = ~swing & self.swing_prev & self.valid self.peak = torch.where(starting, h, torch.where(cont, torch.maximum(self.peak, h), self.peak)) self.valid = torch.where(starting, torch.ones_like(self.valid), self.valid) short = (1.0 - self.peak / self.target).clamp(0.0, 1.5) t = {} t["swing_peak"] = (short * ending.to(f64)).sum(-1) * moving t["foot_drag"] = ((-h).clamp_min(0.0) * speed).sum(-1) * moving vh = heading_velocity(s1) vy_c = cmd[:, 1].to(f64) lat = vy_c.abs() >= self.lat_vy_min along = vh[:, 1] * torch.sign(vy_c) t["lateral_shortfall"] = torch.where(lat, (1.0 - along / vy_c.abs().clamp_min(1e-6)).clamp(0.0, 2.0), torch.zeros_like(along)) if "wrong_way" in self.params: # (3) V3 option ww = vy_c.abs() >= self.ww_vy_min t["wrong_way"] = torch.where(ww, (-along / vy_c.abs().clamp_min(1e-6)).clamp(0.0, self.ww_cap), torch.zeros_like(along)) if "joint_speed" in self.params: # (4) V3 option t["joint_speed"] = (s1[:, 25:37].abs() - self.js_free).clamp_min(0.0).square().sum(-1) diag = dict(h=h, speed=speed, ending=ending, peak=self.peak.clone(), along=along, lat=lat, vh=vh) self.valid = torch.where(ending, torch.zeros_like(self.valid), self.valid) self.swing_prev = swing return {k: v.to(torch.float32) for k, v in t.items()}, diag
def apply(self, s1, k0, cmd, rew, terms): t, diag = self.gait(s1, k0, cmd) terms = dict(terms) for name, sc in self.scales.items(): rew = rew + sc * t[name] for name in t: terms[name] = t[name] self.last_diag = diag return rew, terms
# ------------------------------------------------------------------------------------------------ logs def accumulate(self, terms, cmd, ood, settled): env = self.env f = torch.float64 d = getattr(self, "last_diag", None) if d is None: return trk = settled.to(f) lat = d["lat"].to(f) * trk vy = cmd[:, 1].to(f) ratio = torch.where(d["lat"], d["along"] / vy.abs().clamp_min(1e-6), torch.zeros_like(vy)) drag = ((d["h"] < -0.005) & (d["speed"] > 0.1)).to(f).mean(-1) sink = (-d["h"]).clamp_min(0.0).mean(-1) end = d["ending"].to(f) zero = torch.zeros_like(trk) cols = [trk, lat, ratio * lat, drag * trk, sink * trk, (d["peak"] * end).sum(-1) * trk, end.sum(-1) * trk, terms.get("anchor_dev", zero).to(f) * trk, (ood > 0).to(f) * trk, terms["swing_peak"].to(f) * trk, terms["foot_drag"].to(f) * trk, terms["lateral_shortfall"].to(f) * trk, (d["vh"][:, 1] - vy).abs() * lat] idx = env.ground_idx * len(CATS) + self.cat self.log_sums.index_add_(0, idx, torch.stack(cols, -1)) if self.fix_sums is not None: # V3 option logs pos, neg = lat * (vy > 0).to(f), lat * (vy < 0).to(f) fx = [pos, ratio * pos, neg, ratio * neg, lat * (d["along"] < -WRONG_WAY_V).to(f), terms.get("wrong_way", zero).to(f) * trk, terms.get("joint_speed", zero).to(f) * trk] self.fix_sums.index_add_(0, idx, torch.stack(fx, -1))
def pop(self): sums = self.log_sums.cpu().numpy() self.log_sums.zero_() gs = self.group_starts.cpu().numpy() self.group_starts.zero_() K = {k: i for i, k in enumerate(LOG_KEYS)} fsum = None if self.fix_sums is not None: fsum = self.fix_sums.cpu().numpy() self.fix_sums.zero_() FK = {k: i for i, k in enumerate(FIX_LOG_KEYS)} out = {} for gi, name in enumerate(self.env.ground_names): o = {} for ci, c in enumerate(CATS): r = sums[gi * len(CATS) + ci] st, ls, pn = r[K["steps"]], r[K["lat_steps"]], r[K["peak_n"]] if st <= 0: continue o[c] = dict(steps=float(st), lat_steps=float(ls), lat_ratio=float(r[K["ratio_sum"]] / ls) if ls > 0 else None, vy_abs_err=float(r[K["vy_err"]] / ls) if ls > 0 else None, drag_frac=float(r[K["drag"]] / st), sink_mean_m=float(r[K["sink"]] / st), swing_peak_m=float(r[K["peak_sum"]] / pn) if pn > 0 else None, anchor_dev=float(r[K["anchor_dev"]] / st), ood_active=float(r[K["ood_active"]] / st), swing_peak=float(r[K["swing_peak"]] / st), foot_drag=float(r[K["foot_drag"]] / st), lateral_shortfall=float(r[K["lateral_shortfall"]] / st)) if fsum is not None: q = fsum[gi * len(CATS) + ci] rt = lambda a, b: float(q[FK[a]] / q[FK[b]]) if q[FK[b]] > 0 else None o[c].update(lat_ratio_pos=rt("ratio_pos", "lat_pos"), lat_ratio_neg=rt("ratio_neg", "lat_neg"), wrong_way_share=float(q[FK["wrong"]] / ls) if ls > 0 else None, wrong_way=float(q[FK["wrong_way"]] / st), joint_speed=float(q[FK["joint_speed"]] / st)) out[name] = o if self.group_names: tot = max(float(gs.sum()), 1.0) out["start_groups"] = {nm: float(gs[i] / tot) for i, nm in enumerate(self.group_names)} if self.fix_on: ld = self.lat_draws.cpu().numpy() self.lat_draws.zero_() sg = out.setdefault("start_groups", {}) sg["_reversed_share_of_lateral_draws"] = float(ld[1] / ld[0]) if ld[0] > 0 else None sg["_sign_follows_start_share_of_lateral_draws"] = float(ld[2] / ld[0]) if ld[0] > 0 else None return out
def describe(self): return dict(lateral_mix=dict(lateral=self.p_lat, diagonal=self.p_diag, vy=list(self.vy), lateral_vx=self.lat_vx, wz=self.wz, diag_vx=list(self.diag_vx), diag_forward_fraction=self.diag_fwd, sign_from_start=self.sign_from_start, sign_min_vy=self.sign_min, sign_follow_prob=self.follow_p), lateral_branch_steps=self.lat_steps, branch_steps=self.env.branch_steps, start_groups=getattr(self, "group_info", None), anchor_command_scale=self.anchor_scale, gait_terms={k: dict(self.params[k], per_step_scale=v) for k, v in self.scales.items()}, swing_target_m=self.target, v3fix_options_on=self.fix_on, wrong_way=dict(vy_min=self.ww_vy_min, cap=self.ww_cap) if "wrong_way" in self.params else None, joint_speed_free_rad_s=self.js_free if "joint_speed" in self.params else None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""FineTunePPO: rsl_rl 5.0.1 PPO (rsl_rl/algorithms/ppo.py) with the fine-tune changes:
- one Adam with three parameter groups: actor MLP (lr actor_lr), action std (std_lr), critic (critic_lr); fixed learning rates (no adaptive schedule; KL is still measured and logged);- critic warm-up: while actor_frozen, the loss is the value loss only and the actor / std groups have lr 0 (their Adam moments are not touched, so the actor starts clean after the warm-up);- std bounds: after each optimiser step the scalar std is clamped to [std_min, std_max];- time-out bootstrap from the FINAL observation: reward += gamma V(final_obs) on time-outs (extras["final_obs"]), instead of rsl_rl's V(obs before the step) (time_out_bootstrap "final"; "before" = rsl_rl's rule; "none");- extra loss statistics: KL, clip fraction, explained variance of the value targets.Symmetry, RND and multi-GPU are not supported here (not used)."""from __future__ import annotations
import torchimport torch.nn as nn
from rsl_rl.algorithms import PPO
class FineTunePPO(PPO): def __init__(self, actor, critic, storage, actor_lr=1e-4, critic_lr=1e-3, std_lr=None, std_min=0.05, std_max=0.15, time_out_bootstrap="final", **kw): kw.setdefault("schedule", "fixed") super().__init__(actor, critic, storage, learning_rate=actor_lr, **kw) if self.rnd or self.symmetry or self.is_multi_gpu: raise ValueError("FineTunePPO: RND / symmetry / multi-GPU are not supported") std_params = [p for n, p in self.actor.named_parameters() if n.startswith("distribution.")] mlp_params = [p for n, p in self.actor.named_parameters() if not n.startswith("distribution.")] self.lrs = dict(actor=float(actor_lr), std=float(actor_lr if std_lr is None else std_lr), critic=float(critic_lr)) self.optimizer = torch.optim.Adam([dict(params=mlp_params, lr=self.lrs["actor"], name="actor"), dict(params=std_params, lr=self.lrs["std"], name="std"), dict(params=list(self.critic.parameters()), lr=self.lrs["critic"], name="critic")]) self.std_min, self.std_max = std_min, std_max if time_out_bootstrap not in ("final", "before", "none"): raise ValueError(f"time_out_bootstrap {time_out_bootstrap!r}") self.time_out_bootstrap = time_out_bootstrap self.actor_frozen = False self.clamp_std()
# ------------------------------------------------------------------------------------------------ helpers def set_actor_frozen(self, frozen: bool): self.actor_frozen = bool(frozen) for g in self.optimizer.param_groups: if g["name"] in ("actor", "std"): g["lr"] = 0.0 if frozen else self.lrs[g["name"]] self.learning_rate = 0.0 if frozen else self.lrs["actor"]
@torch.no_grad() def clamp_std(self): d = self.actor.distribution if hasattr(d, "std_param") and (self.std_min is not None or self.std_max is not None): d.std_param.clamp_(min=self.std_min, max=self.std_max)
# ------------------------------------------------------------------------------------------------ rollout def process_env_step(self, obs, rewards, dones, extras): self.actor.update_normalization(obs) # no-op when the normalisers are frozen self.critic.update_normalization(obs) self.transition.rewards = rewards.clone() self.transition.dones = dones if "time_outs" in extras and self.time_out_bootstrap != "none": to = extras["time_outs"].to(self.device).float() if self.time_out_bootstrap == "final" and "final_obs" in extras: v = self.critic(extras["final_obs"].to(self.device)).detach() else: v = self.transition.values self.transition.rewards += self.gamma * (v.squeeze(-1) * to) self.storage.add_transition(self.transition) self.transition.clear() self.actor.reset(dones) self.critic.reset(dones)
# ------------------------------------------------------------------------------------------------ update def update(self): stats = dict(value=0.0, surrogate=0.0, entropy=0.0, kl=0.0, clip_frac=0.0) generator = self.storage.mini_batch_generator(self.num_mini_batches, self.num_learning_epochs) ret = self.storage.returns.flatten() val = self.storage.values.flatten() ev = float(1.0 - (ret - val).var() / ret.var().clamp_min(1e-12)) n_up = 0 for batch in generator: if self.normalize_advantage_per_mini_batch: with torch.no_grad(): batch.advantages = (batch.advantages - batch.advantages.mean()) / (batch.advantages.std() + 1e-8) self.actor(batch.observations, masks=batch.masks, hidden_state=batch.hidden_states[0], stochastic_output=True) logp = self.actor.get_output_log_prob(batch.actions) values = self.critic(batch.observations, masks=batch.masks, hidden_state=batch.hidden_states[1]) params = self.actor.output_distribution_params entropy = self.actor.output_entropy with torch.inference_mode(): kl = self.actor.get_kl_divergence(batch.old_distribution_params, params).mean() ratio = torch.exp(logp - torch.squeeze(batch.old_actions_log_prob)) adv = torch.squeeze(batch.advantages) surrogate = torch.max(-adv * ratio, -adv * torch.clamp(ratio, 1.0 - self.clip_param, 1.0 + self.clip_param)).mean() if self.use_clipped_value_loss: vc = batch.values + (values - batch.values).clamp(-self.clip_param, self.clip_param) value_loss = torch.max((values - batch.returns).pow(2), (vc - batch.returns).pow(2)).mean() else: value_loss = (batch.returns - values).pow(2).mean() if self.actor_frozen: loss = self.value_loss_coef * value_loss else: loss = surrogate + self.value_loss_coef * value_loss - self.entropy_coef * entropy.mean() self.optimizer.zero_grad(set_to_none=True) loss.backward() if not self.actor_frozen: nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_grad_norm) nn.utils.clip_grad_norm_(self.critic.parameters(), self.max_grad_norm) self.optimizer.step() self.clamp_std() with torch.no_grad(): cf = ((ratio - 1.0).abs() > self.clip_param).float().mean() for k, v in (("value", value_loss), ("surrogate", surrogate), ("entropy", entropy.mean()), ("kl", kl), ("clip_frac", cf)): stats[k] += float(v) n_up += 1 self.storage.clear() out = {k: v / max(n_up, 1) for k, v in stats.items()} out["explained_variance"] = ev return out
def save(self): d = super().save() d["finetune_ppo"] = dict(lrs=self.lrs, std_min=self.std_min, std_max=self.std_max, actor_frozen=self.actor_frozen, time_out_bootstrap=self.time_out_bootstrap) return d123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286"""FineTuneRunner: PPO fine-tune of model_10000.pt inside the Go2 NRD (rsl-rl-lib 5.0.1 models, storage and PPO core).
- Models: rsl_rl MLPModel actor 47-512-256-128-12 ELU (obs normalisation, Gaussian scalar std) and critic 74-512-256-128-1, exactly the layout of the mjlab run (agent.yaml), loaded from the checkpoint with strict=True (actor, critic, both normalisers; not the optimiser). Normalisers frozen (until = 1; their count is 9.8e8).- Action std = min(checkpoint std, ppo.std_max); learnable, clamped to [ppo.std_min, ppo.std_max] after every step.- Critic warm-up: runner.warmup_iterations with the actor frozen (value loss only, actor lr 0); then actor lr ppo.actor_lr (1e-4), critic lr ppo.critic_lr (1e-3) throughout.- Guard (Study 4 rule, rl_cfg.py / hooks.py RegressionGuard): over a window of `window` post-warm-up iterations, stop when more than `spike_fraction` of them had a mean OOD cost above `ood_spike` AND the window-mean reward fell more than `reward_drop` (relative) below its best window mean. healthy.pt = the newest checkpoint written while the guard was healthy.- Checkpoints (rsl_rl layout + "infos"): model_0.pt (the start policy, std capped, before any update), model_<it>.pt every save_interval, last.pt every checkpoint_interval and at the end; re-running the same command resumes from last.pt; complete.json marks the end (max iterations or guard). SIGTERM / SIGUSR1 / SIGINT: save last.pt after the current iteration and exit 0 (the AMD sbatch resubmits).- Action anchor (rewards.anchor, go2nrd.rl.env): before each env step the runner hands the policy mean of the step to the env (env.action_mean); the env's frozen reference actor is built from the init checkpoint (or rewards.anchor.reference), so a resume keeps the same reference.- Logging: metrics.jsonl (one row per iteration: losses, lr, std, timing, throughput, per-ground tracking errors, power, torque saturation, OOD, falls, per-term rewards), stdout every log_interval."""from __future__ import annotations
import jsonimport mathimport osimport signalimport timefrom collections import dequefrom pathlib import Path
import torch
from rsl_rl.models import MLPModelfrom rsl_rl.modules.distribution import GaussianDistributionfrom rsl_rl.storage import RolloutStorage
from go2nrd.rl.config import strip_commentsfrom go2nrd.rl.env import Go2NrdVecEnvfrom go2nrd.rl.ppo import FineTunePPO
OBS_GROUPS = {"actor": ["actor"], "critic": ["critic"]}
class Guard: def __init__(self, window=50, ood_spike=0.005, spike_fraction=0.6, reward_drop=0.25, enabled=True): self.window, self.ood_spike = int(window), float(ood_spike) self.spike_fraction, self.reward_drop, self.enabled = float(spike_fraction), float(reward_drop), bool(enabled) self.spikes, self.rewards = deque(maxlen=self.window), deque(maxlen=self.window) self.best = None self.last = dict(spike_frac=0.0, drop=0.0, healthy=True, tripped=False)
def update(self, ood_mean, reward_mean): self.spikes.append(float(ood_mean) > self.ood_spike) self.rewards.append(float(reward_mean)) wmean = sum(self.rewards) / len(self.rewards) full = len(self.rewards) == self.window if full: self.best = wmean if self.best is None else max(self.best, wmean) frac = sum(self.spikes) / len(self.spikes) drop = (self.best - wmean) / max(abs(self.best), 1e-9) if self.best is not None else 0.0 tripped = self.enabled and full and frac > self.spike_fraction and drop > self.reward_drop self.last = dict(spike_frac=frac, drop=drop, window_reward=wmean, best_window_reward=self.best, healthy=not (frac > self.spike_fraction or drop > self.reward_drop), tripped=tripped) return tripped
def state(self): return dict(spikes=list(self.spikes), rewards=list(self.rewards), best=self.best, last=self.last)
def load(self, st): self.spikes.extend(st.get("spikes", [])) self.rewards.extend(st.get("rewards", [])) self.best = st.get("best") self.last = st.get("last", self.last)
class FineTuneRunner: def __init__(self, cfg: dict, out_dir, device="cuda"): self.cfg = cfg self.out = Path(out_dir) self.out.mkdir(parents=True, exist_ok=True) self.device = torch.device(device) seed = int(cfg.get("seed", 1)) torch.manual_seed(seed) if cfg.get("nrd", {}).get("tf32", False): torch.backends.cuda.matmul.allow_tf32 = True t0 = time.time() self.env = Go2NrdVecEnv(cfg, self.device, train=True) self.build_s = time.time() - t0 pc, rc = cfg["ppo"], cfg["runner"] self.num_steps = int(rc.get("num_steps_per_env", 24)) obs = self.env.get_observations() hid = tuple(pc.get("hidden_dims", (512, 256, 128))) self.actor = MLPModel(obs, OBS_GROUPS, "actor", self.env.num_actions, hidden_dims=hid, activation="elu", obs_normalization=True, distribution_cfg=dict(class_name=GaussianDistribution, init_std=1.0, std_type="scalar")).to(self.device) self.critic = MLPModel(obs, OBS_GROUPS, "critic", 1, hidden_dims=hid, activation="elu", obs_normalization=True).to(self.device) # initial weights from the mjlab checkpoint ck = torch.load(cfg["init_checkpoint"], map_location=self.device, weights_only=False) self.actor.load_state_dict(ck["actor_state_dict"], strict=True) self.critic.load_state_dict(ck["critic_state_dict"], strict=True) self.checkpoint_std = ck["actor_state_dict"]["distribution.std_param"].tolist() self.checkpoint_iter = int(ck.get("iter", -1)) for m in (self.actor, self.critic): if cfg["runner"].get("freeze_normalizers", True): m.obs_normalizer.until = 1 # count 9.8e8 >= 1: update() returns at once storage = RolloutStorage("rl", self.env.num_envs, self.num_steps, obs, [self.env.num_actions], self.device) self.alg = FineTunePPO( self.actor, self.critic, storage, actor_lr=pc.get("actor_lr", 1e-4), critic_lr=pc.get("critic_lr", 1e-3), std_lr=pc.get("std_lr"), std_min=pc.get("std_min", 0.05), std_max=pc.get("std_max", 0.15), time_out_bootstrap=pc.get("time_out_bootstrap", "final"), num_learning_epochs=int(pc.get("num_learning_epochs", 5)), num_mini_batches=int(pc.get("num_mini_batches", 4)), clip_param=float(pc.get("clip_param", 0.2)), gamma=float(pc.get("gamma", 0.99)), lam=float(pc.get("lam", 0.95)), value_loss_coef=float(pc.get("value_loss_coef", 1.0)), entropy_coef=float(pc.get("entropy_coef", 0.0)), max_grad_norm=float(pc.get("max_grad_norm", 1.0)), use_clipped_value_loss=bool(pc.get("use_clipped_value_loss", False)), desired_kl=None, normalize_advantage_per_mini_batch=bool(pc.get("normalize_advantage_per_mini_batch", False)), device=str(self.device)) self.guard = Guard(**{k: v for k, v in cfg.get("guard", {}).items() if not k.startswith("_")}) self.it = 0 # next iteration to run self.healthy = None self._stop = False self.resumed = self._resume()
# ------------------------------------------------------------------------------------------------ io def _infos(self): return dict(guard=self.guard.state(), healthy=self.healthy, checkpoint_std=self.checkpoint_std, init_checkpoint=self.cfg["init_checkpoint"], ood=self.env.ood_summary(), rewards=self.env.rewards.describe(), grounds=self.env.ground_names)
def save(self, name, it): d = self.alg.save() d["iter"] = int(it) d["infos"] = self._infos() tmp = self.out / (name + ".tmp") torch.save(d, tmp) os.replace(tmp, self.out / name)
def _resume(self): p = self.out / "last.pt" if not p.is_file(): return False d = torch.load(p, map_location=self.device, weights_only=False) self.alg.load(d, dict(actor=True, critic=True, optimizer=True), strict=True) for m in (self.actor, self.critic): if self.cfg["runner"].get("freeze_normalizers", True): m.obs_normalizer.until = 1 self.it = int(d["iter"]) + 1 inf = d.get("infos") or {} self.guard.load(inf.get("guard", {})) self.healthy = inf.get("healthy") print(f"[resume] {p} iteration {d['iter']} -> continue at {self.it}", flush=True) return True
def _signal(self, signum, frame): print(f"[signal] {signal.Signals(signum).name}: stop after this iteration", flush=True) self._stop = True
# ------------------------------------------------------------------------------------------------ run def learn(self, max_iterations=None): rc = self.cfg["runner"] max_it = int(max_iterations if max_iterations is not None else rc.get("max_iterations", 1000)) warm = int(rc.get("warmup_iterations", 50)) save_every, ck_every = int(rc.get("save_interval", 50)), int(rc.get("checkpoint_interval", 10)) log_every = int(rc.get("log_interval", 1)) for s in (signal.SIGTERM, signal.SIGUSR1, signal.SIGINT): signal.signal(s, self._signal) if not self.resumed: self.alg.clamp_std() self.save("model_0.pt", -1) (self.out / "start.json").write_text(json.dumps(dict( checkpoint_std=self.checkpoint_std, std_after_cap=self.actor.distribution.std_param.tolist(), checkpoint_iter=self.checkpoint_iter, env_build_s=self.build_s, ood=self.env.ood_summary(), rewards=self.env.rewards.describe(), grounds=self.env.ground_names, blocks=[dict(ground=g, envs=s.stop - s.start, pool=int(len(p))) for g, b, p, s in self.env.blocks], members=self.env.sim.paths, ground_arg=self.env.ground_arg), indent=1)) metrics = open(self.out / "metrics.jsonl", "a") obs = self.env.get_observations().to(self.device) self.alg.train_mode() reason = "max_iterations" while self.it < max_it: it = self.it frozen = it < warm self.alg.set_actor_frozen(frozen) if self.device.type == "cuda": torch.cuda.synchronize() t0 = time.time() bad = torch.zeros((), dtype=torch.bool, device=self.device) with torch.inference_mode(): anchored = self.env.anchor is not None for _ in range(self.num_steps): actions = self.alg.act(obs) if anchored: # the policy mean of this step (centered anchor) self.env.action_mean = self.alg.transition.distribution_params[0] obs, rew, dones, extras = self.env.step(actions) bad = bad | ~torch.isfinite(rew).all() | ~torch.isfinite(obs["actor"]).all() | \ ~torch.isfinite(obs["critic"]).all() self.alg.process_env_step(obs, rew, dones, extras) self.alg.compute_returns(obs) if bool(bad): raise FloatingPointError(f"iteration {it}: non-finite reward or observation from the env") t1 = time.time() loss = self.alg.update() if self.device.type == "cuda": torch.cuda.synchronize() t2 = time.time() log = self.env.pop_log() allg = log["all"] tripped = False if not frozen: tripped = self.guard.update(allg["ood_cost"], allg["reward_per_step"]) samples = self.env.num_envs * self.num_steps row = dict(iteration=it, warmup=frozen, time=time.time(), collect_s=t1 - t0, learn_s=t2 - t1, env_steps_per_s=samples / max(t2 - t0, 1e-9), collect_steps_per_s=samples / max(t1 - t0, 1e-9), loss=loss, lr={g["name"]: g["lr"] for g in self.alg.optimizer.param_groups}, std=self.actor.distribution.std_param.tolist(), guard=self.guard.last, grounds=log, gpu_peak_alloc_gb=(torch.cuda.max_memory_allocated(self.device) / 1e9 if self.device.type == "cuda" else None)) metrics.write(json.dumps(row) + "\n") metrics.flush() if it % log_every == 0 or it == max_it - 1: te = allg["track_err"] print(f"it {it:5d}{' W' if frozen else ' '} rew/step {allg['reward_per_step']:+.4f} " f"vloss {loss['value']:.4g} ev {loss['explained_variance']:+.3f} kl {loss['kl']:.2e} " f"trk {te[0]:.3f}/{te[1]:.3f}/{te[2]:.3f} P {allg['power_w']:.1f}W " f"sat {allg['tau_sat_frac']:.1e} ood {allg['ood_cost']:.2e} ({allg['ood_active_frac']:.3f}) " f"falls {allg['falls']:.0f} |roll| {allg['roll_abs']:.3f} lat {allg['roll_abs_lat']:.3f} " f"std {sum(row['std']) / 12:.3f} " f"{row['env_steps_per_s']:.0f} st/s", flush=True) if tripped: reason = "guard" self.save("last.pt", it) (self.out / "guard.json").write_text(json.dumps(dict(iteration=it, guard=self.guard.last, healthy=self.healthy), indent=1)) print(f"[guard] tripped at iteration {it}: {self.guard.last}; last healthy {self.healthy}", flush=True) self.it = it + 1 break if save_every and it % save_every == 0 and it > 0: self.save(f"model_{it}.pt", it) if self.guard.last.get("healthy", True): self.save("healthy.pt", it) self.healthy = it if (ck_every and it % ck_every == 0) or self._stop: self.save("last.pt", it) self.it = it + 1 if self._stop: metrics.close() print(f"[stop] saved last.pt at iteration {it}", flush=True) return "signal" metrics.close() self.save("last.pt", self.it - 1) self.save(f"model_{self.it - 1}.pt", self.it - 1) (self.out / "complete.json").write_text(json.dumps(dict( reason=reason, iterations=self.it, last=f"model_{self.it - 1}.pt", healthy=self.healthy, guard=self.guard.last), indent=1)) self.export_onnx() return reason
def export_onnx(self): try: export_actor_onnx(self.actor.state_dict(), self.out / "policy.onnx") print(f"[export] {self.out / 'policy.onnx'}", flush=True) except Exception as ex: # optional (needs onnx) print(f"[export] ONNX export skipped: {type(ex).__name__}: {ex}", flush=True)
def export_actor_onnx(actor_state_dict, path, opset=17): """Actor mean with the normaliser inside, one self-contained ONNX file [batch, 47] 'obs' -> [batch, 12] 'actions' (the deploy contract of mjlab's policy.onnx; metadata not copied). TorchScript exporter (dynamo=False), so the weights stay inside the file.""" from go2nrd.policy.mjlab_policy import MjlabActor a = MjlabActor() a.load_state_dict({k: v.detach().cpu() for k, v in actor_state_dict.items()}, strict=True) a.eval() torch.onnx.export(a, torch.zeros(1, 47), str(path), input_names=["obs"], output_names=["actions"], opset_version=opset, dynamic_axes={"obs": {0: "batch"}, "actions": {0: "batch"}}, dynamo=False) return path
def write_config(cfg, out): p = Path(out) / "config.json" p.write_text(json.dumps(strip_comments(cfg), indent=1)) return p123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Parity of an exported deploy folder: ONNX vs the torch actor, vs the reference ONNX, and through legged_sim_eval'sDeployPolicy (the deploy's observation assembly + onnxruntime) on observations recorded in mjlab.
New code (judges worker, 2026-10-30). Env ``go2eval`` (torch, onnxruntime, legged_sim_eval)::
PYTHONPATH=/home/harry/go2_sand/nrd/src:/home/harry/go2_sand/legged_rl_deploy/sim_eval \\ python -B -m go2nrd.eval.parity --folder /home/harry/go2_sand/nrd_data/eval/policies/<name> [--rows 4000]
Recorded rows: the policy steps (even records with a finite observation and a command inside the deploy config'sclip box, since the collector commands up to vx 1.25 / vy 1 / wz 1.5) of the mjlab raw shard rigid_test_s0000(the collector's states with instantaneous rates, the command, phase counter k and the observation the mjlab policysaw, and its raw action). For each row a ``RobotState`` is rebuilt the way the DDS bridge publishes it (IMU quaternionw >= 0, gyro = R^T w_world, q / dq in motor order through ``joint_ids_map``, float32), the sticks are set bylegged_sim_eval's ``DirectCommand`` for the command, ``policy_steps`` = k and ``last_action`` = the observation'sprevious action; ``DeployPolicy.update`` then packs the observation and runs the folder's ONNX (``OrtRunner``, thedeploy runtime). Reported (max abs): rebuilt deploy observation vs the recorded one (per term), DeployPolicy action vsthe torch actor of the checkpoint on the recorded observation, vs the folder's ONNX called directly, vs the referenceONNX (mjlab's own export of model_10000) and vs the recorded raw action (equal only for model_10000).Written to ``<folder>/parity.json``."""from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
import numpy as np
from go2nrd.eval.export_onnx import REFERENCE_ONNX, load_actor, onnx_runnerfrom go2nrd.eval.smooth import JMAP, quat_to_rot
SHARD = Path("/home/harry/go2_sand/nrd_data/raw/rigid_test/rigid_test_s0000.npz")CLIP_LO, CLIP_HI = np.array([-0.5, -0.5, -1.0]), np.array([1.0, 0.5, 1.0]) # config.yaml commands.base_velocityTERMS = dict(base_ang_vel=slice(0, 3), projected_gravity=slice(3, 6), command=slice(6, 9), phase=slice(9, 11), joint_pos=slice(11, 23), joint_vel=slice(23, 35), last_action=slice(35, 47))
def recorded_rows(shard: Path, n: int, seed: int = 0) -> dict: from go2nrd.collect.common.contract import load_raw_shard
eps, _ = load_raw_shard(shard) cols = dict(state=[], command=[], k=[], obs=[], raw=[], family=[]) for e in eps: ok = np.isfinite(e.obs).all(1) & np.isfinite(e.raw_action).all(1) ok &= ((e.command >= CLIP_LO) & (e.command <= CLIP_HI)).all(1) # the deploy config clips commands idx = np.flatnonzero(ok) cols["state"].append(e.state[idx]) cols["command"].append(e.command[idx]) cols["k"].append(e.phase_k[idx]) cols["obs"].append(e.obs[idx]) cols["raw"].append(e.raw_action[idx]) cols["family"] += [e.family] * len(idx) out = {k: (np.concatenate(v) if k != "family" else np.array(v)) for k, v in cols.items()} pick = np.sort(np.random.default_rng(seed).choice(len(out["obs"]), min(n, len(out["obs"])), replace=False)) return {k: v[pick] for k, v in out.items()}
def deploy_actions(config: Path, rows: dict) -> tuple[np.ndarray, np.ndarray]: """(packed observations [n, 47], raw actions [n, 12]) of legged_sim_eval's DeployPolicy on the rebuilt states.""" from legged_sim_eval.config import load_deploy_config from legged_sim_eval.lowlevel import DirectCommand from legged_sim_eval.policy import DeployPolicy from legged_sim_eval.robot import RobotState
cfg = load_deploy_config(str(config)) pol = DeployPolicy(cfg) src = DirectCommand(pol) jm = np.asarray(cfg.policy["joint_ids_map"], np.intp) if not np.array_equal(jm, JMAP): raise ValueError(f"joint_ids_map {jm} differs from {JMAP}") obs_out, act_out = [], [] for s, c, k, o in zip(rows["state"], rows["command"], rows["k"], rows["obs"]): quat = s[3:7] / np.linalg.norm(s[3:7]) R = quat_to_rot(quat) gyro = R.T @ s[22:25] q = np.zeros(12) dq = np.zeros(12) q[JMAP] = s[7:19] dq[JMAP] = s[25:37] st = RobotState.from_sensors(quat, gyro, q, dq, np.zeros(12), base_rot=R) pad = src.update(c) pol.policy_steps = int(k) pol.last_action = np.asarray(o[35:47], np.float32).copy() if not pol.update(st, pad, 0): raise RuntimeError("policy did not run at loop_cnt 0") obs_out.append(pol.last_input.copy()) act_out.append(pol.last_raw.copy()) return np.asarray(obs_out, np.float64), np.asarray(act_out, np.float64)
def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--folder", required=True, help="deploy folder (policy.onnx, config.yaml, policy_export.json)") ap.add_argument("--checkpoint", default=None, help="default: policy_export.json checkpoint.file") ap.add_argument("--rows", type=int, default=4000) ap.add_argument("--shard", default=str(SHARD)) ap.add_argument("--atol", type=float, default=1e-4) args = ap.parse_args(argv) import torch
folder = Path(args.folder) ckpt = args.checkpoint or json.loads((folder / "policy_export.json").read_text())["checkpoint"]["file"] actor, ck = load_actor(Path(ckpt)) rows = recorded_rows(Path(args.shard), args.rows) obs = rows["obs"].astype(np.float32) with torch.no_grad(): y_torch = actor(torch.from_numpy(obs)).numpy().astype(np.float64) run_new, ev = onnx_runner(folder / "policy.onnx") run_ref, _ = onnx_runner(REFERENCE_ONNX) y_onnx = run_new(obs).astype(np.float64) y_ref = run_ref(obs).astype(np.float64) obs_dep, y_dep = deploy_actions(folder / "config.yaml", rows) d_obs = np.abs(obs_dep - rows["obs"]) res = dict(folder=str(folder), checkpoint=ck, shard=str(args.shard), rows=int(len(obs)), evaluator=ev, families={f: int((rows["family"] == f).sum()) for f in np.unique(rows["family"])}, obs_rebuilt_vs_recorded={t: float(d_obs[:, s].max()) for t, s in TERMS.items()}, max_abs=dict(onnx_vs_torch=float(np.abs(y_onnx - y_torch).max()), deploy_vs_torch_on_recorded_obs=float(np.abs(y_dep - y_torch).max()), deploy_vs_onnx_on_recorded_obs=float(np.abs(y_dep - y_onnx).max()), onnx_vs_reference_onnx=float(np.abs(y_onnx - y_ref).max()), deploy_vs_recorded_raw=float(np.abs(y_dep - rows["raw"]).max()), torch_vs_recorded_raw=float(np.abs(y_torch - rows["raw"]).max())), action_abs_max=float(np.abs(y_dep).max())) obs_ok = max(v for k, v in res["obs_rebuilt_vs_recorded"].items()) < 1e-4 res["ok"] = bool(obs_ok and res["max_abs"]["onnx_vs_torch"] < args.atol and res["max_abs"]["deploy_vs_torch_on_recorded_obs"] < args.atol) (folder / "parity.json").write_text(json.dumps(res, indent=1) + "\n") print(json.dumps(res, indent=1)) return 0 if res["ok"] else 1
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Loader-compatible export of an nrd_v3 endpoint (weights unchanged).
The nrd_v3 driver wrote its own lineage as the packet 'runtime'. contact_nrd.model.load_model (Go2NrdSim / PPO)also needs, for the fused-heading frame, runtime['state_frame'] (yaw_frame.metadata()) andruntime['frame_source_sha256'] (sha256 of yaw_frame.py / yaw_frame_adapter.py). This script copies the endpoint,adds exactly those two fields (from the FROZEN reference source, digest 924630...) plus the train_three-style'config' alias of the recipe, and checks: 1. model_state_dict / model_config / system / masks / update bitwise equal to the input endpoint; 2. the export loads with the working-tree load_model and Go2NrdSim; 3. one Go2NrdSim-equivalent model step on VAL histories equals the frozen-source model step bitwise. python export_loader.py --src LAST.pt --out EXPORT.pt --frozen-src SRC --manifest M --data-root D"""from __future__ import annotations
import argparseimport copyimport hashlibimport jsonimport subprocessimport sysfrom pathlib import Path
import torch
HERE = Path(__file__).resolve().parentW = Path("/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102")
def sha(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()
CHECK = r'''import json, sys, torch, numpy as npsys.path.insert(0, sys.argv[1]) # working-tree src (the PPO / Go2NrdSim code path)from go2nrd.contact_nrd.model import load_modelfrom go2nrd.sim.nrd_sim import Go2NrdSimm, pk = load_model(sys.argv[2], "cpu")sim = Go2NrdSim(sys.argv[2], device="cpu")b = torch.load(sys.argv[3], weights_only=False)with torch.no_grad(): out, _ = m.world_step(b["hist"], b["ok"], b["act"], ground=b["ground"])torch.save(out, sys.argv[4])print(json.dumps({"load_model": True, "go2nrdsim_members": sim.n_members, "state_frame": m.state_frame, "n_ground_features": int(m.n_ground_features)}))'''
def main(): p = argparse.ArgumentParser() p.add_argument("--src", type=Path, required=True) p.add_argument("--out", type=Path, required=True) p.add_argument("--frozen-src", type=Path, required=True) p.add_argument("--manifest", type=Path, required=True) p.add_argument("--data-root", type=Path, required=True) a = p.parse_args() sys.path.insert(0, str(HERE)) from nrd_v3_train import load_frozen, digest helper, trainer, data, frame, _ = load_frozen(a.frozen_src, json.loads((HERE / "reference/pins.json").read_text())["source_sha256"]) pk = torch.load(a.src, map_location="cpu", weights_only=False) ex = copy.deepcopy(pk) rt = dict(ex["runtime"]) rt["state_frame"] = frame.metadata() rt["frame_source_sha256"] = {n: sha(a.frozen_src / "go2nrd/fixed_base" / n) for n in ("yaw_frame.py", "yaw_frame_adapter.py")} rt["config"] = rt["recipe"] rt["export"] = dict(schema="lateral_stuck_20261108_nrd_v3_loader_export_v1", source_endpoint=str(a.src), source_endpoint_sha256=sha(a.src), added=["state_frame", "frame_source_sha256", "config", "export"], weights_changed=False) ex["runtime"] = rt a.out.parent.mkdir(parents=True, exist_ok=True) torch.save(ex, a.out) same = {k: digest(pk[k]) == digest(ex[k]) for k in ("model_state_dict", "model_config", "system", "masks", "update")} # fixed VAL histories (lat_v2 VAL, frozen sampler, seed 8671) cfg = json.loads((HERE / "reference/full_config.json").read_text()) smp = helper.WindowSampler(data.load_arm(a.manifest, "lat_v2", "matched", "val", a.data_root), cfg["history"], "cpu", 0) import numpy as np smp.rng = np.random.default_rng(8671) b = smp.sample(64, 1) batch = dict(hist=b["hist"], ok=b["ok"], act=b["actions"][:, 0], ground=b["ground"]) tmp = a.out.with_suffix(".check_batch.pt") torch.save(batch, tmp) model = helper.build_model(pk["system"], cfg) model.load_state_dict(pk["model_state_dict"]) model.eval() with torch.no_grad(): ref_out, _ = model.world_step(batch["hist"], batch["ok"], batch["act"], ground=batch["ground"]) out_pt = a.out.with_suffix(".check_out.pt") r = subprocess.run([sys.executable, "-B", "-c", CHECK, str(W / "src"), str(a.out), str(tmp), str(out_pt)], capture_output=True, text=True, env={"PATH": "/usr/bin:/bin", "OMP_NUM_THREADS": "1"}) if r.returncode: raise SystemExit(r.stderr[-3000:]) info = json.loads(r.stdout.strip().splitlines()[-1]) wt = torch.load(out_pt, weights_only=False) info.update(packet_fields_equal=same, step_bitwise_equal_frozen=bool(torch.equal(wt, ref_out)), export=str(a.out), export_sha256=sha(a.out), source_sha256=sha(a.src)) tmp.unlink() out_pt.unlink() print(json.dumps(info))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169"""Train-only kNN OOD reference of the CRM ground for PPO in the retrained NRD nrd_v3 FRESH-b (track P2, ppo_nrdv3).
Why: the OOD price / guard of the PPO env compares (state, applied target) features with a reference corpus. Forthe seed61 NRD the env drew that corpus from the PPO start pool (crm_prod: the 141 PPO71 training rows), which isinside the seed61 training data. FRESH-b was trained on crm_prod TRAIN + the lateral v2 TRAIN exports (HIP + CUDAbuilds; arm mixed_plus_lat_v2, matched; draw shares in the CRM half: crm_prod 50 %, lateral 50 %). The features arephysical (no NRD normalisation), so only the corpus changes. Same procedure as before:
old (env, seed61 runs): pool = CRM starts of the PPO start pool (split 0, families nominal + difficult, k >= 4, >= 100 steps left, phase_k >= 50); draw = first min(|pool|, 16000) of torch.randperm(|pool|, cuda generator seed 0); CorpusReference(seed 0, 4000 points, k 8): whitening by the draw, stock threshold = p99 of each reference point's k-th neighbour distance; recipe V2s/V3: nominal-family p99 of the leave-one-out kNN mean. new (this file, FRESH-b runs): the same 16000-row draw size and the same code, but the rows are 8000 = the first 8000 of the SAME crm_prod permutation (a subset of the old draw) and 8000 = the first 8000 of torch.randperm over the union of lateral v2 TRAIN starts (HIP + CUDA, the same start filter; cuda generator seed 0), i.e. the FRESH-b CRM training mixture 50 / 50; HIP / CUDA by start count (FRESH-b shared the lateral draws by window count). Rigid: unchanged (FRESH-b rigid TRAIN = rigid_prod_v2 TRAIN, the old reference is already its train-only pool). No validation or test row is read (asserted: all rows split 0 and in the FRESH-b train lists).
Checks: (1) the replicated old draw gives the env's old CRM reference bit for bit (reference points, mean, scale,thresholds); (2) the written file loaded by the env (ood.reference_file) gives the same CorpusReference as built here.
PYTHONPATH=<wt>/src python build_ood_reference.py --out assets/ood_ref_crm_freshb_v1.npz"""from __future__ import annotations
import argparseimport hashlibimport jsonimport sysfrom pathlib import Path
import numpy as npimport torch
HERE = Path(__file__).resolve().parentS = HERE.parentWT = S.parents[1]EXPORT = Path("/home/harry/go2_sand/nrd_data/export")LAT = {"crm_lat_v2_hip": EXPORT / "lateral_stuck_20261108_crm_v2_hip", "crm_lat_v2_cuda": EXPORT / "lateral_stuck_20261108_crm_v2_cuda"}
def sha(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 pool_of(bank, min_pk=50): pk = bank.phase_k[bank.start_e, 2 * bank.start_k] return torch.nonzero((bank.ground[bank.start_e] == 1) & (pk >= min_pk)).flatten()
def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", type=Path, required=True) ap.add_argument("--device", default="cuda") a = ap.parse_args() dev = torch.device(a.device) sys.path.insert(0, str(WT / "src")) from go2nrd.fixed_base.ppo_lateral_v3 import build_config from go2nrd.rl.env import Go2NrdVecEnv from go2nrd.rl.ood import CorpusReference, ood_features from go2nrd.sim.bank import StartBank
base = json.loads((HERE / "recipes/base_ppo71_config.json").read_text()) recipe = json.loads((HERE / "recipes/v3.json").read_text()) paths = json.loads((HERE / "recipes/paths_local_seed61.json").read_text()) cfg = build_config(base, recipe, paths, 91) cfg["env"]["num_envs"] = 64 sc = cfg["env"]["start"] oc = cfg["ood"] m = int(oc.get("max_points", 4000)) # ---- (1) old env reference (seed61 runs) and its replication env = Go2NrdVecEnv(cfg, a.device, train=True) gi = env.ground_names.index("crm") g, b, pool, s_ = env.blocks[gi] bank = env.banks[b] gen = torch.Generator(device=dev).manual_seed(int(oc.get("seed", 0))) perm = torch.randperm(len(pool), device=dev, generator=gen) take = min(len(pool), 4 * m) st_old = bank.draw(pool[perm[:take]]) feat_old = ood_features(st_old["hist"][:, -1], st_old["action"]) ref_old = CorpusReference(feat_old, seed=int(oc.get("seed", 0)), max_points=m, k=int(oc["k"]), quantile=float(oc["quantile"]), device=a.device) rec_old = env._family_threshold(ref_old, feat_old, st_old["family"], bank, oc["threshold"]) env_ref = env.ood.refs[gi] same = (torch.equal(env_ref.ref, ref_old.ref) and torch.equal(env_ref._mu, ref_old._mu) and torch.equal(env_ref._sd, ref_old._sd) and env_ref.thresh == ref_old.thresh) if not same: raise AssertionError("replicated old CRM draw differs from the env reference") old_rigid = env.ood_summary()["rigid"] old_crm = env.ood_summary()["crm"] # ---- (2) new rows half = take // 2 st_c = bank.draw(pool[perm[:half]]) sp = json.loads((S / "collect/splits_lateral_v2.json").read_text()) tr = sp["arms"]["matched"]["mixed_plus_lat_v2"]["train"] if not set(np.asarray(bank.rows).tolist()) <= set(tr["crm"]): raise AssertionError("crm_prod pool rows not inside the FRESH-b train list") lat_banks, lat_pools, src_info = [], [], {} K = int(env.sim.k) for key, d in LAT.items(): lb = StartBank(d, splits=tuple(sc.get("splits", (0,))), families=sc.get("families"), min_steps_left=int(sc.get("min_steps_left", 1)), min_k=max(int(sc.get("min_k", K - 1)), K - 1), device=a.device, history=K, rows=tr[key]) if not set(np.asarray(lb.rows).tolist()) <= set(tr[key]): raise AssertionError(f"{key}: rows outside the FRESH-b train list") lp = pool_of(lb, int(sc.get("min_phase_k", {}).get("crm", 0))) lat_banks.append(lb); lat_pools.append(lp) src_info[key] = dict(dir=str(d), unified_sha256=sha(d / "unified_data.npz"), episodes=int(len(lb.rows)), starts=int(len(lp))) nl = [len(p) for p in lat_pools] gen2 = torch.Generator(device=dev).manual_seed(int(oc.get("seed", 0))) lperm = torch.randperm(sum(nl), device=dev, generator=gen2)[:take - half] feats, fams = [ood_features(st_c["hist"][:, -1], st_c["action"])], [st_c["family"]] off = 0 for lb, lp, n in zip(lat_banks, lat_pools, nl): sel = lperm[(lperm >= off) & (lperm < off + n)] - off if len(sel): st = lb.draw(lp[sel]) feats.append(ood_features(st["hist"][:, -1], st["action"])); fams.append(st["family"]) src_info[list(LAT)[lat_banks.index(lb)]]["drawn"] = int(len(sel)) off += n # keep the draw order (crm_prod rows first, then lateral rows in permutation order per source) feat = torch.cat(feats) family = torch.cat(fams) names = [f["name"] for f in bank.system["families"]] for lb in lat_banks: if [f["name"] for f in lb.system["families"]] != names: raise AssertionError("family names differ between crm_prod and lateral v2") ref_new = CorpusReference(feat, seed=int(oc.get("seed", 0)), max_points=m, k=int(oc["k"]), quantile=float(oc["quantile"]), device=a.device) stock_new = ref_new.thresh rec_new = env._family_threshold(ref_new, feat, family, bank, oc["threshold"]) prov = dict(schema="ppo_nrdv3_ood_reference_v1", ground="crm", nrd="nrd_v3 FRESH-b loader 501c9b8d", splits_manifest_sha256=sha(S / "collect/splits_lateral_v2.json"), arm="mixed_plus_lat_v2 matched train", rows_total=int(len(feat)), crm_prod=dict(pool_starts=int(len(pool)), drawn=int(half), rule="first half of the old env permutation (seed 0)", unified_sha256=sha(Path(cfg["data"][0]["dir"]) / "unified_data.npz")), lateral_v2=src_info, start_filter=dict(splits=sc.get("splits"), families=sc.get("families"), min_steps_left=sc.get("min_steps_left"), min_k=4, min_phase_k_crm=50), family_counts={nm: int((family == i).sum()) for i, nm in enumerate(names)}, old=dict(stock=rec_old["stock"], nominal_p99=rec_old["thresh"], rows=old_crm["rows"], env_crm_family_threshold=old_crm.get("family_threshold"), rigid_stock=old_rigid["family_threshold"]["stock"], rigid_nominal_p99=old_rigid["family_threshold"]["thresh"]), new=dict(stock=stock_new, nominal_p99=rec_new["thresh"], nominal_rows=rec_new["rows"], loo_knn_mean=rec_new["loo_knn_mean"])) a.out.parent.mkdir(parents=True, exist_ok=True) np.savez(a.out, feat=feat.double().cpu().numpy(), family=family.long().cpu().numpy(), family_names=np.asarray(names), provenance=np.asarray(json.dumps(prov))) # ---- (3) the env path reads the file to the same reference f2, fam2 = env._reference_rows(a.out, bank, "crm") r2 = CorpusReference(f2, seed=int(oc.get("seed", 0)), max_points=m, k=int(oc["k"]), quantile=float(oc["quantile"]), device=a.device) if not (torch.equal(r2.ref, ref_new.ref) and r2.thresh == stock_new): raise AssertionError("file round trip changed the reference") prov["file_sha256"] = sha(a.out) prov["checks"] = dict(old_replication_bitwise=True, file_roundtrip_bitwise=True) a.out.with_suffix(".json").write_text(json.dumps(prov, indent=1) + "\n") print(json.dumps(prov, indent=1))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142"""Track P2 (ppo_nrdv3) copy of ppo_v3fix/export_v3fix.py (paths changed: exports under runs/.../ppo_nrdv3/; the NRD check isthe FRESH-b loader 501c9b8d and the OOD overlay; nothing else changed). Track P docstring: Export PPO v3 candidates to deploy ONNX exactly like the prior study (export_horizon_PPO_v1.py), CPU only.
Per candidate (RUN = a finished local copy of a run; endpoint model_299.pt): 1. checks: complete.json reason max_iterations, frozen_audit unchanged NRD + unchanged actor normaliser, NRD sha. 2. python -m go2nrd.eval.export_onnx --checkpoint RUN/model_299.pt --out EXPORTS/<name>_i299 --reference legged_rl_deploy/.../velocity/policy.onnx --template .../velocity/config.yaml (unchanged exporter, sha256 5e418e4c...: opset 18, static [1, 47], metadata copied, run_path = the run name; its verification includes 2048 recorded mjlab observations). 3. python -m go2nrd.eval.parity --folder EXPORTS/<name>_i299 --rows 4000 (legged_sim_eval DeployPolicy path on recorded mjlab rows: deploy observation assembly + onnxruntime vs the torch actor of the .pt). 4. extra parity on 4000 recorded Chrono CRM observations (VAL split states of crm_prod with their recorded command / phase / previous action through go2nrd.policy.obs.ObsBuilder): onnxruntime vs the .pt actor. 5. portable copy EXPORTS_EULER/<name>_i299 (identical policy.onnx; config.yaml model_path = the Euler path).Writes EXPORTS/<name>_i299/v3_export_record.json and prints a summary.
python export_v3.py NAME=RUN_DIR [NAME=RUN_DIR ...]"""from __future__ import annotations
import hashlibimport jsonimport osimport subprocessimport sysfrom pathlib import Path
import numpy as np
WT = Path("/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102")EXPORTS = WT / "runs/lateral_stuck_20261108/ppo_nrdv3/exports"EXPORTS_EULER = WT / "runs/lateral_stuck_20261108/ppo_nrdv3/exports_portable_euler"EXPORTS_AMD = WT / "runs/lateral_stuck_20261108/ppo_nrdv3/exports_portable_amd"AMD_EXPORTS = "/work1/dannegrut/harry/lateral_stuck_20261108/ppo_nrdv3/exports"EULER_EXPORTS = "/srv/home/hzhang699/go2nrd/studies/lateral_stuck_20261108/ppo_nrdv3/exports"ORIGINAL = Path("/home/harry/go2_sand/legged_rl_deploy/policies/go2/unitree_rl_mjlab/velocity")NRD_SHA = "501c9b8da022caf9594ad9cd7c50a7eda1e00424e5d4c9c7c8add65ee788848c" # nrd_v3 FRESH-b loaderOVERLAY_SHA = "17d563ae2b18a0a14a6c843d399ef91da22efb16e7f2ab3e5e1d6294318e5a9f" # recipes/overlay_nrdv3_ood.jsonEXPORTER_SHA = "5e418e4c0efa9dd36f1514cde9429e04050a1edb5686a9443f99d98f7d85ee83"
def sha(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def crm_obs(n=4000, seed=0): import torch from go2nrd.policy.obs import ObsBuilder from go2nrd.sim.bank import StartBank bank = StartBank("/home/harry/go2_sand/nrd_data/export/crm_prod", splits=(1,), families=("nominal", "difficult"), min_k=4, device="cpu", history=4) g = torch.Generator().manual_seed(seed) st = bank.draw(torch.randint(bank.n, (n,), generator=g)) ob = ObsBuilder(device="cpu", force_fill="zero") # the recorded instantaneous state is what the policy saw in Chrono return ob.actor(st["state_inst"], st["command"].float(), st["phase_k"], st["last_action"]).numpy().astype(np.float32)
def main(): env = dict(os.environ, CUDA_VISIBLE_DEVICES="", OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1", PYTHONDONTWRITEBYTECODE="1", PYTHONPATH=f"{WT / 'src'}:/home/harry/go2_sand/unitree_rl_mjlab:/home/harry/go2_sand/legged_rl_deploy/sim_eval") assert sha(WT / "src/go2nrd/eval/export_onnx.py") == EXPORTER_SHA assert sha(ORIGINAL / "policy.onnx") == "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45" sys.path.insert(0, str(WT / "src")) from go2nrd.eval.export_onnx import load_actor, onnx_runner import torch obs_crm = crm_obs() out = {} for spec in sys.argv[1:]: name, run = spec.split("=", 1) run = Path(run) comp = json.loads((run / "complete.json").read_text()) audit = json.loads((run / "frozen_audit.json").read_text()) cfg = json.loads((run / "config.json").read_text()) assert comp["reason"] == "max_iterations" and comp["last"] == "model_299.pt", comp assert audit["unchanged"] and audit["teacher_actor_normalization_unchanged"], audit assert cfg["lateral_v3_lineage"]["nrd_sha256"] == NRD_SHA assert cfg["lateral_v3_lineage"].get("overlay_sha256") == OVERLAY_SHA ck = run / "model_299.pt" folder = EXPORTS / f"{name}_i299" if not (folder / "policy_export.json").exists(): folder.parent.mkdir(parents=True, exist_ok=True) with open(EXPORTS / f"{name}_i299_export.log", "w") as log: subprocess.run([sys.executable, "-B", "-m", "go2nrd.eval.export_onnx", "--checkpoint", str(ck), "--out", str(folder), "--run-name", name, "--reference", str(ORIGINAL / "policy.onnx"), "--template", str(ORIGINAL / "config.yaml")], cwd=WT, env=env, stdout=log, stderr=subprocess.STDOUT, check=True, timeout=300) if not (folder / "parity.json").exists(): with open(EXPORTS / f"{name}_i299_parity.log", "w") as log: subprocess.run([sys.executable, "-B", "-m", "go2nrd.eval.parity", "--folder", str(folder), "--rows", "4000"], cwd=WT, env=env, stdout=log, stderr=subprocess.STDOUT, check=True, timeout=600) desc = json.loads((folder / "policy_export.json").read_text()) par = json.loads((folder / "parity.json").read_text()) actor, ckd = load_actor(ck) fn, evaluator = onnx_runner(folder / "policy.onnx") with torch.no_grad(): y_t = actor(torch.from_numpy(obs_crm)).numpy() y_o = fn(obs_crm) crm_diff = float(np.abs(y_o - y_t).max()) # portable Euler copy pf = EXPORTS_EULER / f"{name}_i299" pf.mkdir(parents=True, exist_ok=True) (pf / "policy.onnx").write_bytes((folder / "policy.onnx").read_bytes()) txt = (folder / "config.yaml").read_text().splitlines() txt = [(ln.split("model_path:")[0] + f"model_path: {EULER_EXPORTS}/{name}_i299/policy.onnx") if ln.strip().startswith("model_path:") else ln for ln in txt] (pf / "config.yaml").write_text("\n".join(txt) + "\n") for f in ("policy_export.json", "parity.json"): (pf / f).write_bytes((folder / f).read_bytes()) pa = EXPORTS_AMD / f"{name}_i299" # portable AMD copy (track P) pa.mkdir(parents=True, exist_ok=True) (pa / "policy.onnx").write_bytes((folder / "policy.onnx").read_bytes()) txa = [(ln.split("model_path:")[0] + f"model_path: {AMD_EXPORTS}/{name}_i299/policy.onnx") if ln.strip().startswith("model_path:") else ln for ln in (folder / "config.yaml").read_text().splitlines()] (pa / "config.yaml").write_text("\n".join(txa) + "\n") for f in ("policy_export.json", "parity.json"): (pa / f).write_bytes((folder / f).read_bytes()) rec = dict(name=name, run=str(run), checkpoint=str(ck), checkpoint_sha256=sha(ck), iteration=ckd["iteration"], onnx=str(folder / "policy.onnx"), onnx_sha256=sha(folder / "policy.onnx"), onnx_portable_euler=f"{EULER_EXPORTS}/{name}_i299/policy.onnx", config_yaml=str(folder / "config.yaml"), config_yaml_portable_euler=f"{EULER_EXPORTS}/{name}_i299/config.yaml", onnx_portable_amd=f"{AMD_EXPORTS}/{name}_i299/policy.onnx", config_yaml_portable_amd=f"{AMD_EXPORTS}/{name}_i299/config.yaml", structure_ok=desc["structure"]["ok"], exporter_verification=desc["verification"], parity_deploy=par, parity_crm_recorded=dict(n=int(len(obs_crm)), evaluator=evaluator, max_abs_onnx_vs_pt=crm_diff, max_abs_action=float(np.abs(y_o).max())), exporter_sha256=EXPORTER_SHA, nrd_sha256=NRD_SHA, recipe=cfg["lateral_v3_lineage"]["recipe"], seed=cfg["seed"], overlay_sha256=cfg["lateral_v3_lineage"]["overlay_sha256"], ood_reference_file=cfg["ood"].get("reference_file")) (folder / "v3_export_record.json").write_text(json.dumps(rec, indent=1) + "\n") (pf / "v3_export_record.json").write_text(json.dumps(rec, indent=1) + "\n") (pa / "v3_export_record.json").write_text(json.dumps(rec, indent=1) + "\n") out[name] = rec print(name, rec["onnx_sha256"][:16], "structure", rec["structure_ok"], "exporter max", desc["verification"]["max_onnx_vs_torch"], "crm max", crm_diff, flush=True) print(json.dumps({k: dict(onnx_sha256=v["onnx_sha256"], crm=v["parity_crm_recorded"]["max_abs_onnx_vs_pt"]) for k, v in out.items()}, indent=1))
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Start-group intervals for env.start.groups (go2nrd.rl.lateral_v3): the CRM STUCK lateral intervals of phase 1.
Source: diag/crm_coverage/lateral_windows.json "stuck" (domain crm), the same list the phase-1 critic used (S6:1,579 of 29,445 PPO71 CRM starts inside STUCK, 512 inside drag-like). Groups (first match wins in the env): stuck_drag : drag-like STUCK interval (critic rule: swing clearance median < 3 cm or stance max sinkage median > 2 cm) stuck : other STUCK intervalInterval = export row piece_index, records [start_record, end_record) (cut at the row end when the window crossesa chunk edge, as critic S6). Also counts the PPO71 CRM pool starts per group (critic S6 enumeration).
python3 build_start_groups.py -> start_groups_crm_stuck_v1.npz, start_groups_crm_stuck_v1.json"""import jsonfrom pathlib import Path
import numpy as np
WT = Path("/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102")HERE = WT / "studies/lateral_stuck_20261108/ppo_v3"LW = WT / "studies/lateral_stuck_20261108/diag/crm_coverage/lateral_windows.json"PPO71 = WT / "runs/fixed_base_20261102/ppo/horizon_h50_u13500_s61_p71_diagnostic_v1"EXPORT = Path("/home/harry/go2_sand/nrd_data/export/crm_prod")
def drag_like(w): return (w.get("swing_clearance_median_m") is not None and w["swing_clearance_median_m"] < 0.03) or \ (w.get("stance_max_sinkage_median_m") is not None and w["stance_max_sinkage_median_m"] > 0.02)
def main(): import sys sys.path.insert(0, str(WT / "src")) from go2nrd.sim.bank import npz_members arr = npz_members(EXPORT / "unified_data.npz") L = np.asarray(arr["lengths"]) st = [w for w in json.loads(LW.read_text())["stuck"] if w["domain"] == "crm"] names = ["stuck_drag", "stuck"] rows, lo, hi, grp, meta = [], [], [], [], [] for w in st: e = int(w["piece_index"]) end = int(w["end_record"]) if int(w.get("piece_index_end", e)) == e else int(L[e]) g = 0 if drag_like(w) else 1 rows.append(e); lo.append(int(w["start_record"])); hi.append(end); grp.append(g) meta.append(dict(row=e, lo=int(w["start_record"]), hi=end, group=names[g], parent=w["parent"], split=w["split"], family=w["family"], vy_cmd=w["vy_cmd"], vx_cmd=w["vx_cmd"], soil_cohesion_pa=w["soil_cohesion_pa"], soil_friction=w["soil_friction"], min_window_ratio=w["min_window_ratio"])) out = HERE / "start_groups_crm_stuck_v1.npz" np.savez(out, names=np.array(names), row=np.array(rows, np.int64), lo=np.array(lo, np.int64), hi=np.array(hi, np.int64), group=np.array(grp, np.int64)) # PPO71 CRM pool enumeration (critic S6 rule) and group counts cfg = json.loads((PPO71 / "config.json").read_text()) sc = cfg["env"]["start"] entry = [d for d in cfg["data"] if Path(d["dir"]).name == "crm_prod"][0] prow = np.asarray(entry["rows"], int) spl, fam = np.asarray(arr["splits"]), np.asarray(arr["family"]) sel = prow[np.isin(spl[prow], sc["splits"]) & np.isin(fam[prow], [0, 1])] min_k, msl, min_pk = max(int(sc["min_k"]), 3), int(sc["min_steps_left"]), int(sc["min_phase_k"]["crm"]) counts = {n: 0 for n in names} total = 0 par = np.asarray(arr["parent_episode_id"]) parents = {n: set() for n in names} lat_vy = {n: [] for n in names} for e in sel: n = int(L[e]); kmax = (n - 1 - 2 * msl) // 2 if kmax < min_k: continue k = np.arange(min_k, kmax + 1) k = k[np.asarray(arr["phase_k"][e, :n])[2 * k] >= min_pk] total += len(k) r0 = 2 * k got = np.full(len(k), -1) for rr, a, b, g in zip(rows, lo, hi, grp): if rr == e: got = np.where((got < 0) & (r0 >= a) & (r0 < b), g, got) for g, nm in enumerate(names): c = int((got == g).sum()); counts[nm] += c if c: parents[nm].add(int(par[e])) lat_vy[nm] += np.asarray(arr["command"][e, :n])[r0[got == g], 1].tolist() rec = dict(file=str(out), source=str(LW), intervals=len(rows), names=names, intervals_per_group={nm: int(sum(g == i for g in grp)) for i, nm in enumerate(names)}, ppo71_crm_pool_starts=total, pool_starts_per_group=counts, pool_parents_per_group={k: sorted(v) for k, v in parents.items()}, pool_vy_abs_median={k: float(np.median(np.abs(v))) if v else None for k, v in lat_vy.items()}, pool_vy_pos_share={k: float(np.mean(np.asarray(v) > 0)) if v else None for k, v in lat_vy.items()}, intervals_detail=meta) (HERE / "start_groups_crm_stuck_v1.json").write_text(json.dumps(rec, indent=1) + "\n") print(json.dumps({k: v for k, v in rec.items() if k != "intervals_detail"}, indent=1))
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:528b37f1d97f17c4c2e655b82d371012da6944a82e0e97dafcd04e82c77127eesize 48929838123version https://git-lfs.github.com/spec/v1oid sha256:7c8e6b75bb94e834f4e237b320945c297ec3b2288c5d12b7950d785379151f66size 60475430123version https://git-lfs.github.com/spec/v1oid sha256:ca870a86a87c5c1bd853048de81e4c83182f841b01ec04a87d70efcd7f537af0size 7046472123version https://git-lfs.github.com/spec/v1oid sha256:81a3e27e7b4f8635dd583cd1bfaa71013bba6fe8805cc1a803ebe13b00954e72size 6793278123version https://git-lfs.github.com/spec/v1oid sha256:1671c771c4c55a9ad8ae9a1be84eef361134e45533ca93ad7a7e5e4399e012d8size 681098123version https://git-lfs.github.com/spec/v1oid sha256:853a24cff65412a1e9a4becc078e615b8d7d24c76f98c26268dffe2c7c662539size 673647123version https://git-lfs.github.com/spec/v1oid sha256:bfb2ee245691196798f28fc695c6fb558e851a835e26094f138e52a2a939028csize 12163621123version https://git-lfs.github.com/spec/v1oid sha256:5b533c22cb13131f7c6b9e38deccae3c97f8797ae3285ef4d80e64813a8ba02asize 1695346123version https://git-lfs.github.com/spec/v1oid sha256:e54474044a6bc37ab6b4260629c2b2d695a7368384996eaef2d90103242520ffsize 595152123version https://git-lfs.github.com/spec/v1oid sha256:5ba3b8c4330110b089f7d2639527b1f1a56b74d05367ef953bbe9e7eb6d587d4size 13016731123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268{ "schema": "go2_sand_finetune_export_names_v1", "note": "The split manifests and run configs name the exports by their ORIGINAL folder names and absolute local paths (/home/harry/go2_sand/nrd_data/export/<original_folder>). On the Hub the folders are renamed as listed here; the files inside are unchanged (same sha256). To reuse the split manifests, place or link each release folder at its original folder name, or edit 'path'.", "split_manifests": { "go2_sand_finetune/data/splits/splits_fixed_base_20261102.json": { "original_path": "/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102/studies/fixed_base_20261102/data/splits.json", "sha256": "f1d264dde8e4398607d09a3c4013c2dfe624e8fcef873596880b5ce63376b3f0" }, "go2_sand_finetune/data/splits/splits_lateral_v2.json": { "original_path": "/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102/studies/lateral_stuck_20261108/collect/splits_lateral_v2.json", "sha256": "9ba6dce9f4b7e29ad385da61d1209d71f5f7478c7863b4dba23c9519047bee4f", "used_by": "NRD FRESH-b (arm mixed_plus_lat_v2, budget matched, seed 62; lineage.json manifest_sha256)" } }, "exports": { "rigid_prod_v2": { "release_folder": "go2_sand_finetune/data/rigid_prod_v2/", "original_folder": "/home/harry/go2_sand/nrd_data/export/rigid_prod_v2", "campaign": "rigid_prod", "plan": "go2_sand_finetune/data/plans/rigid_prod.json", "master_seed": 645913208, "plan_episodes": 8700, "plan_missing_episodes_in_this_export": 0, "created_utc": "2026-10-30T06:27:55Z", "export_code": "6e5c729e28c3bd6c03bd34e715d9827a80d0cd3e", "export_code_dirty": true, "pieces": 10443, "valid_records": 3271292, "hours": 9.057913888888889, "split_counts": { "0": 9391, "1": 1052, "2": 0 }, "raw_shards": 39, "platform": "local workstation, RTX 5090, mjlab / MuJoCo Warp (raw shards 2026-10-29 22:27 CDT)", "simulation": { "simulator": "mjlab (MuJoCo Warp)", "packages": { "mjlab": "1.2.0", "mujoco": "3.5.0", "mujoco-warp": "3.5.0", "warp-lang": "1.12.1", "torch": "2.14.1" }, "task": "Unitree-Go2-Flat" }, "generating_policy": { "kind": "mjlab checkpoint (deterministic mean action)", "checkpoint": "/home/harry/go2_sand/unitree_rl_mjlab/logs/rsl_rl/go2_velocity/2026-10-22_02-14-16_Unitree-Go2-Flat/model_10000.pt", "checkpoint_sha256": "7ee303f98c48044d792c884edeeedacb58142aece8af56de6f0ba58fb6c9723c", "iteration": 10000, "source": "manifest.json collectors[0].policy and every shard_meta" }, "used_by": { "nrd_fresh_b": "yes, source key 'rigid' (domain weight 0.5)", "ppo_v2n_s81": "yes, start states (Euler copy, same sha256)" }, "sha256": { "unified_data.npz": "b02c0c50b185a4e3851d1e948b20ea6ba88f9402009655313310ab621806ac78", "manifest.json": "68df3247d3e6e9ffd9099671cc877eb6d7b6b6052d2ff724d925902870e94ce5", "system.json": "e1a7de656a46b9493e1021e37d459198480c90e712c179039fe4c9cc94761309" } }, "crm_prod": { "release_folder": "go2_sand_finetune/data/crm_prod/", "original_folder": "/home/harry/go2_sand/nrd_data/export/crm_prod", "campaign": "crm_prod", "plan": "go2_sand_finetune/data/plans/crm_prod.json", "master_seed": 481062795, "plan_episodes": 2000, "plan_missing_episodes_in_this_export": 0, "created_utc": "2026-10-30T11:03:53Z", "export_code": "1346b2cfcc264fd150442e08fcbe4d096b9e62a4", "export_code_dirty": false, "pieces": 3489, "valid_records": 2141261, "hours": 5.938255555555556, "split_counts": { "0": 3138, "1": 351, "2": 0 }, "raw_shards": 2000, "platform": "AMD HPC Fund, MI210 (mi2101x), Chrono CRM HIP build, array job 487049, launched 2026-10-30 01:57 CDT", "simulation": { "simulator": "Chrono (pychrono)", "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e", "pychrono_core_md5": "600414ef1296c505" }, "generating_policy": { "kind": "legged_rl_deploy ONNX (teacher)", "onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45", "deploy_config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2", "per_shard_policy_sha256": null, "shards_with_policy_field": 0, "shards": 2000, "source": "system.json physics_config.crm.deploy; shard_meta has no policy field" }, "used_by": { "nrd_fresh_b": "yes, source key 'crm' (crm_half/crm_prod, weight 0.25)", "ppo_v2n_s81": "yes, start states (Euler copy, same sha256)" }, "sha256": { "unified_data.npz": "35b73ce2d8bd1c28f7de88c92347dd6f76ee7b3c509635d900565027f24f0271", "manifest.json": "d4600689fa41cd42f09f931c868b24670f7401ff5e5d074728697468388eba04", "system.json": "9e895fe65b13f0f7056f4c62979f8692379c5ae65449de9986d980ef8c77fa2a" } }, "lateral_crm_v2_hip": { "release_folder": "go2_sand_finetune/data/lateral_crm_v2_hip/", "original_folder": "/home/harry/go2_sand/nrd_data/export/lateral_stuck_20261108_crm_v2_hip", "campaign": "lateral_stuck_20261108_crm_v2", "plan": "go2_sand_finetune/data/plans/lateral_stuck_20261108_crm_v2.json", "master_seed": 2026110803, "plan_episodes": 480, "plan_missing_episodes_in_this_export": 80, "created_utc": "2026-11-09T05:42:02Z", "export_code": null, "export_code_dirty": false, "pieces": 730, "valid_records": 663634, "hours": 1.8413999999999997, "split_counts": { "0": 657, "1": 73, "2": 0 }, "raw_shards": 400, "platform": "AMD HPC Fund, MI210 (mi2104x), Chrono CRM HIP build (core md5 600414ef), bulk job 509760, export job 509836, 2026-11-08", "simulation": { "simulator": "Chrono (pychrono)", "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e", "pychrono_core_md5": "600414ef1296c505" }, "generating_policy": { "kind": "legged_rl_deploy ONNX (teacher)", "onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45", "deploy_config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2", "per_shard_policy_sha256": [ "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45" ], "shards_with_policy_field": 400, "shards": 400, "source": "system.json physics_config.crm.deploy and every shard_meta.policy" }, "used_by": { "nrd_fresh_b": "yes, source key 'crm_lat_v2_hip' (crm_half/lat_v2, shared weight 0.25 with cuda)", "ppo_v2n_s81": "no direct use" }, "sha256": { "unified_data.npz": "2e78115a8fef352781a6cb861bd530fd539260836152a07d155b2cabefeddf8b", "manifest.json": "c60ddc252f87f32457a9485f74cd2817872359aac223c86b01a6f3f1f974e4db", "system.json": "82b4a4e93ce8044d93f2ea491969407df912beebe131f8c18a960041add94e60" } }, "lateral_crm_v2_cuda": { "release_folder": "go2_sand_finetune/data/lateral_crm_v2_cuda/", "original_folder": "/home/harry/go2_sand/nrd_data/export/lateral_stuck_20261108_crm_v2_cuda", "campaign": "lateral_stuck_20261108_crm_v2", "plan": "go2_sand_finetune/data/plans/lateral_stuck_20261108_crm_v2.json", "master_seed": 2026110803, "plan_episodes": 480, "plan_missing_episodes_in_this_export": 400, "created_utc": "2026-11-09T05:41:59Z", "export_code": null, "export_code_dirty": false, "pieces": 149, "valid_records": 136413, "hours": 0.3785111111111111, "split_counts": { "0": 135, "1": 14, "2": 0 }, "raw_shards": 80, "platform": "Euler euler07, 5 x A4500, Chrono CRM CUDA build (core md5 2387ec6d), bulk job 113924, export job 113929, 2026-11-08", "simulation": { "simulator": "Chrono (pychrono)", "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e", "pychrono_core_md5": "2387ec6dda45eaa5" }, "generating_policy": { "kind": "legged_rl_deploy ONNX (teacher)", "onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45", "deploy_config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2", "per_shard_policy_sha256": [ "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45" ], "shards_with_policy_field": 80, "shards": 80, "source": "system.json physics_config.crm.deploy and every shard_meta.policy" }, "used_by": { "nrd_fresh_b": "yes, source key 'crm_lat_v2_cuda' (crm_half/lat_v2, shared weight 0.25 with hip)", "ppo_v2n_s81": "no direct use" }, "sha256": { "unified_data.npz": "f1079976f3f407596714bdcf9cc7616bd162280e1e6358cc9d21e03a6b9fa7a2", "manifest.json": "f1429b3f3bda6b3eaeb21bdb034c9c9e0f2053a6ee63abe8591c3b51d76ce35b", "system.json": "3a3f7b93b76048fe57b0bafff74f61c4639d21874d3fcb725036c600639809dc" } }, "lateral_crm_v2_test_hip": { "release_folder": "go2_sand_finetune/data/lateral_crm_v2_test_hip/", "original_folder": "/home/harry/go2_sand/nrd_data/export/lateral_stuck_20261108_crm_v2_test_hip", "campaign": "lateral_stuck_20261108_crm_v2_test", "plan": "go2_sand_finetune/data/plans/lateral_stuck_20261108_crm_v2_test.json", "master_seed": 2026110804, "plan_episodes": 60, "plan_missing_episodes_in_this_export": 0, "created_utc": "2026-11-09T05:42:20Z", "export_code": null, "export_code_dirty": false, "pieces": 105, "valid_records": 95556, "hours": 0.26514166666666666, "split_counts": { "0": 0, "1": 0, "2": 105 }, "raw_shards": 60, "platform": "AMD HPC Fund, MI210, Chrono CRM HIP build, bulk job 509760, export job 509836, 2026-11-08", "simulation": { "simulator": "Chrono (pychrono)", "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e", "pychrono_core_md5": "600414ef1296c505" }, "generating_policy": { "kind": "legged_rl_deploy ONNX (teacher)", "onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45", "deploy_config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2", "per_shard_policy_sha256": [ "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45" ], "shards_with_policy_field": 60, "shards": 60, "source": "system.json physics_config.crm.deploy and every shard_meta.policy" }, "used_by": { "nrd_fresh_b": "no (held out: splits_lateral_v2.json key heldout_test; load_arm refuses it)", "ppo_v2n_s81": "no" }, "sha256": { "unified_data.npz": "e1f18d4814353a5ff0dbf6b86771896b1cdd68c3243e21731676013a868e5701", "manifest.json": "b4dcaa08aaee26bb4290ee6e76c538340ef50d0f4a8bc348027e117f520ecd89", "system.json": "84406be3a230c24c70a1ae7b0c13c3b3f90bf39df11dfd15646a055cd3514f08" } }, "lateral_crm_v2_slim_diag": { "release_folder": "go2_sand_finetune/data/lateral_crm_v2_slim_diag/", "original_folder": "/home/harry/go2_sand/nrd_data/export/lateral_stuck_20261108_crm_v2_slim_diag", "campaign": "lateral_stuck_20261108_crm_v2 and _test", "content": "per-episode diagnostics (feet, com, t_sim, nonfoot_low, relief_dk, relief_lattice, surface maps, swing_lift offset/weight/env/k, injection_applied), keys e<episode_id>__<name>", "made_by": "collect/scripts/extract_slim_diag.py in post jobs AMD 509836 (hip, test_hip) and Euler 113929 (cuda)", "used_by": { "nrd_fresh_b": "no (QA / diagnostics only)", "ppo_v2n_s81": "no" }, "sha256": { "lateral_stuck_20261108_crm_v2_cuda_slim_diag.npz": "dc7158004218e2b6d05648b6b5de662620c15610b49d338f50d2200a4c08e761", "lateral_stuck_20261108_crm_v2_hip_slim_diag.npz": "bc37034cfd5adb2520128b3158b51c029036f7b10c969891b2e74bb4c6157285", "lateral_stuck_20261108_crm_v2_test_hip_slim_diag.npz": "6f1b7fff964c0e46dc2e94dee4408680c781205a7d1fe7709fc4ac25508c2b8c" } } }}123version https://git-lfs.github.com/spec/v1oid sha256:4291746111e9e496cfbfb0947ed7b8498105a146cc071b9855f8d5cc0bacd2cbsize 89542381123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230{ "planned": 2000, "with_marker": 2000, "missing": 0, "status": { "ok": 2000 }, "attempts": { "ok": 2000 }, "fsi_abort_share": 0.0, "terminal_reasons": { "nominal": { "planned_end": 404, "off_bed": 70, "nonfoot_contact": 4, "tilt": 2 }, "difficult": { "nonfoot_contact": 144, "tilt": 77, "planned_end": 475, "off_bed": 23, "fell": 1 }, "probe_drop": { "planned_end": 500 }, "probe_landing": { "planned_end": 300 } }, "wall_per_sim_s": { "nominal": { "median": 6.512005792403264, "min": 5.174011065669888, "max": 10.285052144544514, "n": 480 }, "difficult": { "median": 6.332915835010262, "min": 5.347029627434759, "max": 12.729182214075584, "n": 720 }, "probe_drop": { "median": 9.64788262499558, "min": 8.956308217409328, "max": 11.025985791348624, "n": 500 }, "probe_landing": { "median": 8.870916865456255, "min": 8.242487960185217, "max": 9.865579874565926, "n": 300 } }, "build_plus_stand_wall_s": { "nominal": { "median": 15.904413787648082, "max": 35.84517406951636 }, "difficult": { "median": 13.62626469694078, "max": 35.44896775390953 }, "probe_drop": { "median": 0.6121977488510311, "max": 0.7848611148074269 }, "probe_landing": { "median": 0.6079686884768307, "max": 0.9829784920439124 } }, "totals": { "sim_s": 21601.22000000035, "wall_s": 156931.79610943794, "wall_per_sim_s_overall": 7.264950595819838 }, "joint_limits": { "nominal": { "records": 887143, "active": 74, "episodes": 480, "episodes_active": 0, "torque_max": 0.0, "pen_max": 0.0, "steps": 0, "active_record_rate": 8.341383519906035e-05 }, "difficult": { "records": 1169179, "active": 4701, "episodes": 720, "episodes_active": 21, "torque_max": 115.5936559205135, "pen_max": 0.31834866181951493, "steps": 5787, "active_record_rate": 0.004020770130151157 }, "probe_drop": { "records": 60500, "active": 36, "episodes": 500, "episodes_active": 0, "torque_max": 0.0, "pen_max": 0.0, "steps": 0, "active_record_rate": 0.0005950413223140496 }, "probe_landing": { "records": 45300, "active": 0, "episodes": 300, "episodes_active": 0, "torque_max": 0.0, "pen_max": 0.0, "steps": 0, "active_record_rate": 0.0 } }, "tau_ff": { "finite": 3513816, "nonzero": 0 }, "crm_free": { "nominal": { "intervals": 886663, "free": 0, "share": 0.0, "probe_free_intervals_before_first_contact": {} }, "difficult": { "intervals": 1168459, "free": 12, "share": 1.0269936728631471e-05, "probe_free_intervals_before_first_contact": {} }, "probe_drop": { "intervals": 60000, "free": 11569, "share": 0.19281666666666666, "probe_free_intervals_before_first_contact": { "0": 8.0, "10": 15.0, "25": 18.0, "50": 24.0, "75": 28.0, "90": 31.0, "100": 33.0 } }, "probe_landing": { "intervals": 45000, "free": 2430, "share": 0.054, "probe_free_intervals_before_first_contact": { "0": 2.0, "10": 4.0, "25": 6.0, "50": 8.0, "75": 11.0, "90": 12.0, "100": 15.0 } } }, "nonfoot": { "records_flagged": 148, "cut:difficult": 144, "cut:nominal": 4 }, "soil": { "mismatch_vs_plan": [], "sources": { "plan": 2000 }, "cohesion_q": { "0": 0.03554628044818742, "10": 69.7009189480774, "25": 245.30562411684411, "50": 796.5552915564041, "75": 1862.264993882804, "90": 2961.5253065087345, "100": 3993.145463029502 }, "friction_q": { "0": 0.6001416839151741, "10": 0.6307398432471917, "25": 0.6779942816552935, "50": 0.7515661712860295, "75": 0.8229704294920599, "90": 0.8700151145600103, "100": 0.8997899850239188 }, "density": [ 1700.0 ], "young_modulus": [ 500000.0 ], "bins": { "c[0,250)": 509, "c[1000,2000)": 389, "c[2000,4001)": 462, "c[250,1000)": 640 } }, "checker": { "ok": true, "fails": [], "warnings": null, "gates": { "crm": { "split": "0", "core_windows": 1503, "core_ok": false, "single_windows": { "FL_leg_ground": 1575, "FR_leg_ground": 1007, "RL_leg_ground": 1906, "RR_leg_ground": 1324 }, "single_ok": true } } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "episodes": 3489, "valid_records": 2141261, "hours": 5.938255555555556, "split_counts": { "0": 3138, "1": 351, "2": 0 }, "family_counts": { "nominal": { "0": 843, "1": 92, "2": 0 }, "difficult": { "0": 1575, "1": 179, "2": 0 }, "probe_drop": { "0": 450, "1": 50, "2": 0 }, "probe_landing": { "0": 270, "1": 30, "2": 0 } }, "terminal_reason_counts": { "planned_end": 1679, "fell": 1, "tilt": 54, "nonfoot_contact": 113, "nonfinite": 0, "off_bed": 0, "fsi_abort": 0, "push_cut": 884, "validity_cut": 82, "chunk": 676 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706{ "name": "go2_locomotion", "contract": "go2nrd_contract_v1", "record_step_s": 0.01, "model_step_s": 0.02, "control_step_s": 0.02, "target_time_s": 1.0, "records_per_episode": 1001, "frame": "world, z up; z = height of the base_link frame origin above the nominal ground surface (mjlab plane z = 0, Chrono rigid box top 0.05 m, CRM soil top 0.20 m subtracted); SI units, radians; quaternion wxyz base_link -> world, unit, w >= 0 at the first record, sign continuous; base_link origin (not the COM) linear velocity and angular velocity in the world frame; instantaneous rates as the simulator reports them at the record instant; joint order FL, FR, RL, RR x (hip, thigh, calf), mjlab / policy order, Unitree sign", "bodies": [ { "name": "robot", "kind": "articulated", "moving": true, "state_dim": 37, "channels": [ "x", "y", "z", "qw", "qx", "qy", "qz", "FL_hip", "FL_thigh", "FL_calf", "FR_hip", "FR_thigh", "FR_calf", "RL_hip", "RL_thigh", "RL_calf", "RR_hip", "RR_thigh", "RR_calf", "vx", "vy", "vz", "wx", "wy", "wz", "FL_hip_rate", "FL_thigh_rate", "FL_calf_rate", "FR_hip_rate", "FR_thigh_rate", "FR_calf_rate", "RL_hip_rate", "RL_thigh_rate", "RL_calf_rate", "RR_hip_rate", "RR_thigh_rate", "RR_calf_rate" ], "channel_types": [ "position", "position", "position", "quaternion", "quaternion", "quaternion", "quaternion", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "velocity", "velocity", "velocity", "angular_velocity", "angular_velocity", "angular_velocity", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate" ], "channel_mask": [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], "action_dim": 12, "action_channels": [ "FL_hip_target", "FL_thigh_target", "FL_calf_target", "FR_hip_target", "FR_thigh_target", "FR_calf_target", "RL_hip_target", "RL_thigh_target", "RL_calf_target", "RR_hip_target", "RR_thigh_target", "RR_calf_target" ], "joint_names": [ "FL_hip_joint", "FL_thigh_joint", "FL_calf_joint", "FR_hip_joint", "FR_thigh_joint", "FR_calf_joint", "RL_hip_joint", "RL_thigh_joint", "RL_calf_joint", "RR_hip_joint", "RR_thigh_joint", "RR_calf_joint" ], "base_body": "base_link", "action_rule": "absolute joint position targets = default_joint_pos + 0.25 * raw policy output (+ any OU target noise), applied over [t, t + 10 ms), constant over each 20 ms control period (records 2c, 2c + 1)", "default_joint_pos": [ -0.1, 0.9, -1.8, 0.1, 0.9, -1.8, -0.1, 0.9, -1.8, 0.1, 0.9, -1.8 ], "action_scale": 0.25, "kp": [ 20.0, 20.0, 40.0, 20.0, 20.0, 40.0, 20.0, 20.0, 40.0, 20.0, 20.0, 40.0 ], "kd": [ 1.0, 1.0, 2.0, 1.0, 1.0, 2.0, 1.0, 1.0, 2.0, 1.0, 1.0, 2.0 ], "effort_limit_nm": [ 23.5, 23.5, 45.0, 23.5, 23.5, 45.0, 23.5, 23.5, 45.0, 23.5, 23.5, 45.0 ] }, { "name": "ground", "kind": "plane", "moving": false, "top_z_m": 0.0, "size": "flat ground (mjlab plane; CRM soil bed: see physics_config.crm)" } ], "pairs": [ [ 0, 1 ], [ 0, 1 ], [ 0, 1 ], [ 0, 1 ] ], "pair_metadata": [ { "name": "FL_leg_ground", "leg": "FL", "robot_geoms": { "rigid": [ "FL_foot_collision" ], "crm": [ "FL_foot (FSI sphere)", "FL_calf (FSI cylinder)" ] }, "ground_geoms": { "rigid": [ "terrain" ], "crm": [ "CRM soil" ] } }, { "name": "FR_leg_ground", "leg": "FR", "robot_geoms": { "rigid": [ "FR_foot_collision" ], "crm": [ "FR_foot (FSI sphere)", "FR_calf (FSI cylinder)" ] }, "ground_geoms": { "rigid": [ "terrain" ], "crm": [ "CRM soil" ] } }, { "name": "RL_leg_ground", "leg": "RL", "robot_geoms": { "rigid": [ "RL_foot_collision" ], "crm": [ "RL_foot (FSI sphere)", "RL_calf (FSI cylinder)" ] }, "ground_geoms": { "rigid": [ "terrain" ], "crm": [ "CRM soil" ] } }, { "name": "RR_leg_ground", "leg": "RR", "robot_geoms": { "rigid": [ "RR_foot_collision" ], "crm": [ "RR_foot (FSI sphere)", "RR_calf (FSI cylinder)" ] }, "ground_geoms": { "rigid": [ "terrain" ], "crm": [ "CRM soil" ] } } ], "target_body": 0, "contact_rule": { "crm": { "threshold_n": 20.0, "rule": "pair p (leg FL/FR/RL/RR vs soil) on in record interval k if the norm of the vector sum of the foot-sphere and calf-cylinder FSI forces (world, GetFsiBodyForce) of the leg, per force read; non-negative by construction (NRD_PLAN.md section 10, review D3) exceeds threshold_n in ANY force read acting inside (t_k, t_k + 10 ms]; contact_force = the largest value over those reads", "component": "norm of the vector sum of the foot-sphere and calf-cylinder FSI forces (world, GetFsiBodyForce) of the leg, per force read; non-negative by construction (NRD_PLAN.md section 10, review D3)", "aggregation": "max over the force reads acting in the interval", "step": "FSI exchange 1.0 ms (2 MBD substeps)", "read_window": [ 2, 1 ], "read_timing": "CRM: exchange s is driven by the GetFsiBodyForce values read after exchanges s-2 and s-1 (one 0.5 ms MBD substep each); rigid: GetContactForce after a step is that step's force", "diagnostics": "CRM foot_force / calf_force = max force norm over the same reads; crm_free = all 8 body norms < 1.0 N in every read of the interval (contract section 11)", "relabelled_from_contact_force": true } }, "categories": { "crm": { "ground_id": 1 } }, "grounds": [ "rigid", "crm" ], "ground_ids": { "rigid": 0, "crm": 1 }, "families": [ { "name": "nominal", "group": "nominal", "select": true, "note": "mjlab policy on Kyle Sha's 10 command families (20 s, redrawn every 10 s), OU target noise sigma U(0, 0.05) rad, no pushes" }, { "name": "difficult", "group": "difficult", "select": true, "note": "the same command families with Kyle's OU target noise (sigma log-U(0.10, 0.22) rad, tau 0.15 s) and 2 pushes of 0.1 s, 8-140 N; 25 % long push-free slowed episodes; push windows excised (pieces share the parent's group)" }, { "name": "probe_drop", "group": "probe", "select": false, "note": "walking pose released 0.10-0.60 m above the ground (attitude up to 15 deg, joint offsets +-0.15 rad, command in the evaluation envelope), policy active, 1.2 s: contact-free windows, then the landing" }, { "name": "probe_landing", "group": "probe", "select": false, "note": "low tilted release (0.01-0.12 m, tilt up to 20 deg), policy active, 1.5 s: single feet touch first" } ], "terminal_reasons": [ "planned_end", "fell", "tilt", "nonfoot_contact", "nonfinite", "off_bed", "fsi_abort", "push_cut", "validity_cut", "chunk" ], "termination": { "min_base_height_m": 0.15, "max_tilt_rad": 1.2217304763960306, "rule": "a collector ends an episode at: a non-foot robot geom touching the ground (rigid; the last kept record is the one before the interval with the contact), base z below min_base_height_m above the surface, tilt above max_tilt_rad, a non-finite state, the base off the soil bed (CRM), an FSI abort (CRM); the terminal state is recorded" }, "physics_config": { "crm": { "simulator": "Chrono (pychrono)", "pychrono": "unknown", "pychrono_core_md5": "600414ef1296c505", "backend": "chrono-crm", "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e", "soil": { "keys": { "cohesion_pa": "SoilProperties.cohesion_coeff (Pa)", "friction": "SoilProperties.mu_fric_s = mu_fric_2 (internal friction mu_s = mu_2)", "density": "SoilProperties.density (kg/m^3)", "young_modulus_pa": "SoilProperties.Young_modulus (Pa)" }, "base": { "cohesion_pa": 2000.0, "friction": 0.8, "density": 1700.0, "young_modulus_pa": 500000.0 }, "evaluator_defaults": { "cohesion_pa": 2000.0, "friction": 0.8, "density": 1700.0, "young_modulus_pa": 500000.0 }, "per_episode": "each episode's soil: RawEpisode.meta['soil'].values (raw shard meta 'soil'; export manifest shard_meta[i].soil); params.crm.soil and build_id here are the campaign base, the episode's own build id is RawEpisode.meta['build']" }, "terrain": "crm", "params": { "terrain": "crm", "pd_mode": "substep", "urdf": "go2_mjlab.urdf sha256 5d9b51e03a4215c71c2ad2dd9b97d3dce448a5baf67cdb7ae8262737201746d6", "rigid_mbd_step_s": 0.0005, "exchange_step_s": null, "solver_iterations": 100, "contact": { "friction": 0.9, "restitution": 0.01, "kn": 200000.0, "gn": 60.0, "envelope_m": 0.0025, "margin_m": 0.0025 }, "crm": { "spacing_m": 0.02, "depth_m": 0.2, "cfd_step_s": 0.0005, "integration": "RK2", "d0_multiplier": 1.0, "free_surface_threshold": 0.8, "artificial_viscosity": 2.0, "foot_radius_m": 0.025, "calf_fsi": true, "calf_radius_m": 0.02, "calf_length_m": 0.2, "active_domain_m": 0.5, "active_domain_delay_s": 0.1, "bed_margin_m": 0.25, "bed_override_m": null, "soil": { "density": 1700.0, "young_modulus_pa": 500000.0, "poisson_ratio": 0.3, "mu_i0": 0.04, "friction": 0.8, "average_diam_m": 0.005, "cohesion_pa": 2000.0 } } }, "robot": { "robot": "go2_mjlab", "rotor": { "enabled": true, "coupling": "relative", "ratio": 1.0, "shaft_inertia": 0.0001, "compensate": true, "armature_scale": 1.0 }, "armature": { "FL_hip_joint": 0.01, "FL_thigh_joint": 0.01, "FL_calf_joint": 0.02, "FR_hip_joint": 0.01, "FR_thigh_joint": 0.01, "FR_calf_joint": 0.02, "RL_hip_joint": 0.01, "RL_thigh_joint": 0.01, "RL_calf_joint": 0.02, "RR_hip_joint": 0.01, "RR_thigh_joint": 0.01, "RR_calf_joint": 0.02 }, "legacy_calf_fsi": true, "joint_limits": { "mode": "mujoco", "params_sha256": "e8de60cb6fe591c8" } }, "robot_mass_kg": 15.206408, "mbd_step_s": 0.0005, "sample_step_s": 0.001, "fsi_exchange_step_s": 0.001, "rigid_sample_note": null, "surface_z_in_sim": 0.2, "deploy": { "config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2", "model_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45", "ll_dt": 0.005, "policy_dt": 0.019999999552965164, "tau_max": [ 23.5, 23.5, 45.0, 23.5, 23.5, 45.0, 23.5, 23.5, 45.0, 23.5, 23.5, 45.0 ], "torque_clip": false, "command_clip": "none", "fixstand_kp": [ 60.0, 80.0, 80.0, 60.0, 80.0, 80.0, 60.0, 80.0, 80.0, 60.0, 80.0, 80.0 ], "fixstand_kd": [ 5.0, 4.0, 4.0, 5.0, 4.0, 4.0, 5.0, 4.0, 4.0, 5.0, 4.0, 4.0 ] }, "startup": "task: FixStand 1 s (go2.yaml gains, quintic from the spawn pose), START in the last stand tick, records from the first policy tick; probes: spawn in the air at the planned pose, policy gains and policy reset at spawn (phase counter = plan phase_k0)", "injection": "plan OU target noise added to the HighController target before torqueClip (motor order)", "push": "world-frame force at the base COM through a base force accumulator, set at the planned record boundaries; acts 0.5 ms (one MBD step) later for exactly 0.1 s (Chrono accumulator update lag)", "force_read_window": { "lo": 2, "hi": 1, "rule": "steps a+1..b <- reads a+1-lo..b-hi" }, "nonfoot": "rigid: kinematic, any mjlab non-foot collision geom (base, hips, thighs, calves) below the box top, or base contact force; CRM: base, hip or thigh geom below the nominal soil top in any 1.0 ms exchange; both end the episode (terminal reason nonfoot_contact)", "actuator": "PD law at every MBD step, clamped at the effort limit (23.5 / 45 N m) per step; no deploy torqueClip", "joint_limits": "MuJoCo default soft joint limit of the mjlab model as a one-sided torque in the PD law (go2nrd.chrono_robot.limits; robot.joint_limits)" } }, "extras": { "ground": "[N] int8 ground id of each episode (system.json ground_ids); optional (version B of the NRD)", "episode_id": "[N] int64 = parent_episode_id * 10 + piece", "parent_episode_id": "[N] int64 planned episode id; piece [N] int8 its push piece; record_offset [N] int32 first parent record of the piece", "group_id": "[N] int64 = the parent's planned group (pieces share it and the split)", "obs": "[N, T, 47] policy observation at policy records (even records), NaN elsewhere", "raw_action": "[N, T, 12] raw policy output at policy records, NaN elsewhere", "command": "[N, T, 3] (vx, vy, wz) command of the control period containing the record", "phase_k": "[N, T] int32 the policy's phase counter k", "push_force": "[N, T, 3] world push force in [t, t + 10 ms) (excised in kept data: zero)", "nonfoot_contact": "[N, T] uint8 non-foot ground contact in [t, t + 10 ms)", "contact_force": "[N, T-1, 4] max pair normal force over the interval's steps (N)", "foot_force, calf_force": "[N, T-1, 4] optional CRM diagnostics (N)", "validity_check": "[N] int8 0 = none, else 1 + index of the export validity check that cut the episode", "soil": "[N, 4] float32 soil of each episode, columns soil_columns (cohesion_pa, friction = mu_s = mu_2, density, young_modulus_pa); NaN on rigid ground (ground 0)", "ground_features": "[N, 3] float32 version-B ground features, names ground_feature_names; f = [1, log1p(cohesion_pa / 250) / log(17), (friction - 0.6) / 0.3] on CRM (0..1 over the corpus soil range cohesion [0, 4000] Pa, friction [0.6, 0.9]); f = [0, 0, 0] on rigid ground", "prev_raw_action": "[N, 12] float32 the raw action the policy saw as its last action at the piece's first record (obs[35:47] there: the hand-over / stand value at record 0, 0 for probes, raw_action[s - 2] inside an episode); review D8", "crm_free": "[N, T-1] uint8 CRM free flag per interval (1 = all 8 FSI force norms < 1 N in every exchange; rigid rows 0 = not applicable; padding 0); a CRM core window needs it on all its intervals (core_free_flag)" }, "core_free_flag": { "array": "crm_free", "grounds": [ "crm" ], "rule": "a core (contact-free) window of an episode whose ground is listed also needs array = 1 on every record interval the window spans (train.py: intervals r - stride .. r + stride - 1 of the window at record r); other grounds: the contact labels only" }, "soil_columns": [ "cohesion_pa", "friction", "density", "young_modulus_pa" ], "ground_feature_names": [ "is_crm", "cohesion_code", "friction_code" ], "ground_feature_rule": "f = [1, log1p(cohesion_pa / 250) / log(17), (friction - 0.6) / 0.3] on CRM (0..1 over the corpus soil range cohesion [0, 4000] Pa, friction [0.6, 0.9]); f = [0, 0, 0] on rigid ground", "evaluation": { "note": "Task metrics of Go2 contact NRD training (checkpoint selection) and test. Port of NeDM configs/contact_nrd/evaluation/g1_locomotion.json (6d3f4396d, sha256 43013438...) to Go2: 4 leg-ground pairs, fall flag base z < 0.15 m or tilt > 45 deg, 2 s long windows (report), event windows at least 0.1 s apart. Every value and its reason: configs/evaluation/README.md. Provisional: freeze after the pilot, before main training and the sealed test.", "free": {}, "windows": { "horizons_s": [ 0.02, 0.2, 0.5, 1.0 ], "first_start_s": 0.1, "start_every_s": 0.5, "end_window": true }, "long_windows": { "horizons_s": [ 2.0 ], "first_start_s": 0.1, "start_every_s": 1.0 }, "event_windows": { "horizons_s": [ 0.2, 0.5, 1.0 ], "lead_s": 0.1, "min_gap_s": 0.1, "events": [ "onset" ] }, "flags": { "fall": { "any": [ { "body": "robot", "channel": "z", "below": 0.15 }, { "body": "robot", "tilt_above_rad": 0.7853981633974483 } ] } }, "contact_tolerance_steps": 2, "batch": 2048, "score": [ { "stat": "windows/1.0/robot/pos_m/p95", "scale": 0.05, "weight": 1.0 }, { "stat": "windows/1.0/robot/angle_rad/p95", "scale": 0.08726646259971647, "weight": 1.0 }, { "stat": "windows/1.0/robot/joint_rms_rad/p95", "scale": 0.1, "weight": 1.0 }, { "stat": "windows/contacts/all/event_error_rate", "scale": 0.1, "weight": 1.0 }, { "stat": "windows/contacts/all/timing_s/p95", "scale": 0.02, "weight": 1.0 }, { "stat": "windows/flags/fall/disagreement", "scale": 0.01, "weight": 1.0 }, { "stat": "nonfinite_fraction", "scale": 0.01, "weight": 1.0 } ] }, "campaigns": [ "crm_prod" ]}123version https://git-lfs.github.com/spec/v1oid sha256:35b73ce2d8bd1c28f7de88c92347dd6f76ee7b3c509635d900565027f24f0271size 1096892318123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471{ "dir": "/home/harry/go2_sand/nrd_data/export/crm_prod", "system": "go2_locomotion", "episodes": 3489, "valid_records": 2141261, "records_per_episode": 1001, "hours": 5.938255555555556, "padded_records": 3492489, "padding_fraction": 0.3868954204293843, "quat_norm_err_max": 4.209746207184395e-08, "ground_counts": { "crm": 3489 }, "soil": { "cohesion_pa": { "min": 0.035546280443668365, "p50": 821.8724975585938, "max": 3993.1455078125 }, "friction": { "min": 0.600141704082489, "p50": 0.7523771524429321, "max": 0.8997899889945984 }, "density": { "min": 1700.0, "p50": 1700.0, "max": 1700.0 }, "young_modulus_pa": { "min": 500000.0, "p50": 500000.0, "max": 500000.0 } }, "ground_features_formula_max_err": 1.1920928955078125e-07, "ground_features": { "is_crm": { "min": 1.0, "max": 1.0 }, "cohesion_code": { "min": 5.018154115532525e-05, "max": 0.9994302988052368 }, "friction_code": { "min": 0.00047227973118424416, "max": 0.999299943447113 } }, "prev_raw_action": { "unknown": 0, "zero": 1989, "abs_max": 8.03856372833252 }, "groups": 1989, "split_family_counts": { "nominal": { "0": 843, "1": 92, "2": 0 }, "difficult": { "0": 1575, "1": 179, "2": 0 }, "probe_drop": { "0": 450, "1": 50, "2": 0 }, "probe_landing": { "0": 270, "1": 30, "2": 0 } }, "validation_group_fraction": { "nominal": 0.1, "difficult": 0.1001410437235543, "probe_drop": 0.1, "probe_landing": 0.1 }, "terminal_reasons": { "planned_end": 1679, "fell": 1, "tilt": 54, "nonfoot_contact": 113, "push_cut": 884, "validity_cut": 82, "chunk": 676 }, "task_pieces": { "count": 2689, "min_records": 256, "shorter_than_256": 0 }, "rate_consistency": { "crm": { "base_position": { "record_10ms": { "rms": 0.0008552051479089693, "p50": 0.00028859497979283333, "p95": 0.001703498512506483, "max": 0.04324042797088623, "relative_rms": 0.0035588069327056504 }, "shift_relative_rms": { "aligned": 0.0035542627149714495, "rates_one_record_late": 0.0777165189655358, "rates_one_record_early": 0.08212193609071944 }, "best_alignment": "aligned", "step_20ms_simpson": { "rms": 0.0006516958501499254, "p50": 0.00025070862223704887, "p95": 0.0013325675080219914, "max": 0.01913793881734227, "relative_rms": 0.0027119337567129875 }, "step_20ms_relative_rms_per_channel": [ 0.0016, 0.0017, 0.0036 ] }, "joints": { "record_10ms": { "rms": 0.07984451823691222, "p50": 0.023865535855293274, "p95": 0.16232565045356745, "max": 7.728699743747711, "relative_rms": 0.04516961940879301 }, "shift_relative_rms": { "aligned": 0.04499651834439178, "rates_one_record_late": 0.2617835738817814, "rates_one_record_early": 0.31160872561617914 }, "best_alignment": "aligned", "step_20ms_simpson": { "rms": 0.07646891726612944, "p50": 0.013368030389149937, "p95": 0.16061253001292553, "max": 3.8240599234898873, "relative_rms": 0.043259975334370857 }, "step_20ms_relative_rms_per_channel": [ 0.0184, 0.0209, 0.0479, 0.0186, 0.0206, 0.0472, 0.0192, 0.0211, 0.0462, 0.0189, 0.0203, 0.0459 ] }, "base_angular": { "record_10ms": { "rms": 0.010827812006917107, "p50": 0.002913675942259287, "p95": 0.023299576331908666, "max": 0.7863338810551888, "relative_rms": 0.02308993313151337 }, "record_10ms_if_body_frame": { "rms": 0.5291096325679482, "p50": 0.08995285710925553, "p95": 1.1821052761522857, "max": 24.14709121207038, "relative_rms": 1.1283079192203287 }, "frame_hint": "world", "shift_relative_rms": { "aligned": 0.023069739780111648, "rates_one_record_late": 0.29664622617147135, "rates_one_record_early": 0.31922825030145313 }, "best_alignment": "aligned", "step_20ms_simpson": { "rms": 0.012490932673752914, "p50": 0.0023940412705333314, "p95": 0.02659319169069073, "max": 0.5334440947880124, "relative_rms": 0.02663648020513682 } }, "episodes": 400 } }, "strict_rule": "crm_free = 1 in every interval of the window (CRM rows)", "coverage": { "all": { "episodes": 3489, "windows": 1068382, "free_robot": 7059, "core_robot": 1722, "free_robot_strict_1N": 6808, "core_robot_strict_1N": 1669, "single_FL_leg_ground": 1710, "on_FL_leg_ground": 771203, "single_FR_leg_ground": 1099, "on_FR_leg_ground": 744988, "single_RL_leg_ground": 2135, "on_RL_leg_ground": 753592, "single_RR_leg_ground": 1441, "on_RR_leg_ground": 742124, "multi_contact": 1054938, "feet_on_histogram": { "0": 7059, "1": 6385, "2": 466178, "3": 281874, "4": 306886 }, "onsets_FL_leg_ground": 47446, "onsets_FR_leg_ground": 49932, "onsets_RL_leg_ground": 48840, "onsets_RR_leg_ground": 48749 }, "split0": { "episodes": 3138, "windows": 962979, "free_robot": 6371, "core_robot": 1554, "free_robot_strict_1N": 6141, "core_robot_strict_1N": 1503, "single_FL_leg_ground": 1575, "on_FL_leg_ground": 694308, "single_FR_leg_ground": 1007, "on_FR_leg_ground": 671908, "single_RL_leg_ground": 1906, "on_RL_leg_ground": 679325, "single_RR_leg_ground": 1324, "on_RR_leg_ground": 669097, "multi_contact": 950796, "feet_on_histogram": { "0": 6371, "1": 5812, "2": 420302, "3": 253754, "4": 276740 }, "onsets_FL_leg_ground": 42769, "onsets_FR_leg_ground": 44941, "onsets_RL_leg_ground": 44076, "onsets_RR_leg_ground": 43880 }, "split1": { "episodes": 351, "windows": 105403, "free_robot": 688, "core_robot": 168, "free_robot_strict_1N": 667, "core_robot_strict_1N": 166, "single_FL_leg_ground": 135, "on_FL_leg_ground": 76895, "single_FR_leg_ground": 92, "on_FR_leg_ground": 73080, "single_RL_leg_ground": 229, "on_RL_leg_ground": 74267, "single_RR_leg_ground": 117, "on_RR_leg_ground": 73027, "multi_contact": 104142, "feet_on_histogram": { "0": 688, "1": 573, "2": 45876, "3": 28120, "4": 30146 }, "onsets_FL_leg_ground": 4677, "onsets_FR_leg_ground": 4991, "onsets_RL_leg_ground": 4764, "onsets_RR_leg_ground": 4869 }, "family_nominal": { "episodes": 935, "windows": 443278, "free_robot": 0, "core_robot": 0, "free_robot_strict_1N": 0, "core_robot_strict_1N": 0, "single_FL_leg_ground": 15, "on_FL_leg_ground": 314504, "single_FR_leg_ground": 4, "on_FR_leg_ground": 300356, "single_RL_leg_ground": 24, "on_RL_leg_ground": 304955, "single_RR_leg_ground": 15, "on_RR_leg_ground": 299383, "multi_contact": 443220, "feet_on_histogram": { "0": 0, "1": 58, "2": 243440, "3": 66860, "4": 132920 }, "onsets_FL_leg_ground": 14938, "onsets_FR_leg_ground": 15322, "onsets_RL_leg_ground": 15741, "onsets_RR_leg_ground": 14930 }, "family_difficult": { "episodes": 1754, "windows": 572604, "free_robot": 57, "core_robot": 12, "free_robot_strict_1N": 2, "core_robot_strict_1N": 1, "single_FL_leg_ground": 1499, "on_FL_leg_ground": 424610, "single_FR_leg_ground": 886, "on_FR_leg_ground": 413493, "single_RL_leg_ground": 1895, "on_RL_leg_ground": 417143, "single_RR_leg_ground": 1241, "on_RR_leg_ground": 412087, "multi_contact": 567026, "feet_on_histogram": { "0": 57, "1": 5521, "2": 201195, "3": 203902, "4": 161929 }, "onsets_FL_leg_ground": 30337, "onsets_FR_leg_ground": 32421, "onsets_RL_leg_ground": 30924, "onsets_RR_leg_ground": 31653 }, "family_probe_drop": { "episodes": 500, "windows": 30000, "free_robot": 5746, "core_robot": 1340, "free_robot_strict_1N": 5667, "core_robot_strict_1N": 1326, "single_FL_leg_ground": 100, "on_FL_leg_ground": 17899, "single_FR_leg_ground": 97, "on_FR_leg_ground": 17209, "single_RL_leg_ground": 102, "on_RL_leg_ground": 17514, "single_RR_leg_ground": 100, "on_RR_leg_ground": 16828, "multi_contact": 23855, "feet_on_histogram": { "0": 5746, "1": 399, "2": 9851, "3": 6667, "4": 7337 }, "onsets_FL_leg_ground": 1234, "onsets_FR_leg_ground": 1252, "onsets_RL_leg_ground": 1235, "onsets_RR_leg_ground": 1238 }, "family_probe_landing": { "episodes": 300, "windows": 22500, "free_robot": 1256, "core_robot": 370, "free_robot_strict_1N": 1139, "core_robot_strict_1N": 342, "single_FL_leg_ground": 96, "on_FL_leg_ground": 14190, "single_FR_leg_ground": 112, "on_FR_leg_ground": 13930, "single_RL_leg_ground": 114, "on_RL_leg_ground": 13980, "single_RR_leg_ground": 85, "on_RR_leg_ground": 13826, "multi_contact": 20837, "feet_on_histogram": { "0": 1256, "1": 407, "2": 11692, "3": 4445, "4": 4700 }, "onsets_FL_leg_ground": 937, "onsets_FR_leg_ground": 937, "onsets_RL_leg_ground": 940, "onsets_RR_leg_ground": 928 }, "ground_crm": { "episodes": 3489, "windows": 1068382, "free_robot": 7059, "core_robot": 1722, "free_robot_strict_1N": 6808, "core_robot_strict_1N": 1669, "single_FL_leg_ground": 1710, "on_FL_leg_ground": 771203, "single_FR_leg_ground": 1099, "on_FR_leg_ground": 744988, "single_RL_leg_ground": 2135, "on_RL_leg_ground": 753592, "single_RR_leg_ground": 1441, "on_RR_leg_ground": 742124, "multi_contact": 1054938, "feet_on_histogram": { "0": 7059, "1": 6385, "2": 466178, "3": 281874, "4": 306886 }, "onsets_FL_leg_ground": 47446, "onsets_FR_leg_ground": 49932, "onsets_RL_leg_ground": 48840, "onsets_RR_leg_ground": 48749 }, "ground_crm_split0": { "episodes": 3138, "windows": 962979, "free_robot": 6371, "core_robot": 1554, "free_robot_strict_1N": 6141, "core_robot_strict_1N": 1503, "single_FL_leg_ground": 1575, "on_FL_leg_ground": 694308, "single_FR_leg_ground": 1007, "on_FR_leg_ground": 671908, "single_RL_leg_ground": 1906, "on_RL_leg_ground": 679325, "single_RR_leg_ground": 1324, "on_RR_leg_ground": 669097, "multi_contact": 950796, "feet_on_histogram": { "0": 6371, "1": 5812, "2": 420302, "3": 253754, "4": 276740 }, "onsets_FL_leg_ground": 42769, "onsets_FR_leg_ground": 44941, "onsets_RL_leg_ground": 44076, "onsets_RR_leg_ground": 43880 } }, "gates": { "crm": { "split": "0", "core_windows": 1503, "core_ok": false, "single_windows": { "FL_leg_ground": 1575, "FR_leg_ground": 1007, "RL_leg_ground": 1906, "RR_leg_ground": 1324 }, "single_ok": true } }, "fails": [], "warns": [ "gate: crm: 1503 contact-free core-grid training windows (< 10000)" ], "ok": true}1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "episodes": 149, "valid_records": 136413, "hours": 0.3785111111111111, "split_counts": { "0": 135, "1": 14, "2": 0 }, "family_counts": { "nominal": { "0": 103, "1": 12, "2": 0 }, "difficult": { "0": 32, "1": 2, "2": 0 }, "probe_drop": { "0": 0, "1": 0, "2": 0 }, "probe_landing": { "0": 0, "1": 0, "2": 0 } }, "terminal_reason_counts": { "planned_end": 56, "fell": 0, "tilt": 2, "nonfoot_contact": 22, "nonfinite": 0, "off_bed": 0, "fsi_abort": 0, "push_cut": 0, "validity_cut": 0, "chunk": 69 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734{ "name": "go2_locomotion", "contract": "go2nrd_contract_v1", "record_step_s": 0.01, "model_step_s": 0.02, "control_step_s": 0.02, "target_time_s": 1.0, "records_per_episode": 1001, "frame": "world, z up; z = height of the base_link frame origin above the nominal ground surface (mjlab plane z = 0, Chrono rigid box top 0.05 m, CRM soil top 0.20 m subtracted); SI units, radians; quaternion wxyz base_link -> world, unit, w >= 0 at the first record, sign continuous; base_link origin (not the COM) linear velocity and angular velocity in the world frame; instantaneous rates as the simulator reports them at the record instant; joint order FL, FR, RL, RR x (hip, thigh, calf), mjlab / policy order, Unitree sign", "bodies": [ { "name": "robot", "kind": "articulated", "moving": true, "state_dim": 37, "channels": [ "x", "y", "z", "qw", "qx", "qy", "qz", "FL_hip", "FL_thigh", "FL_calf", "FR_hip", "FR_thigh", "FR_calf", "RL_hip", "RL_thigh", "RL_calf", "RR_hip", "RR_thigh", "RR_calf", "vx", "vy", "vz", "wx", "wy", "wz", "FL_hip_rate", "FL_thigh_rate", "FL_calf_rate", "FR_hip_rate", "FR_thigh_rate", "FR_calf_rate", "RL_hip_rate", "RL_thigh_rate", "RL_calf_rate", "RR_hip_rate", "RR_thigh_rate", "RR_calf_rate" ], "channel_types": [ "position", "position", "position", "quaternion", "quaternion", "quaternion", "quaternion", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "angle", "velocity", "velocity", "velocity", "angular_velocity", "angular_velocity", "angular_velocity", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate", "angular_rate" ], "channel_mask": [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], "action_dim": 12, "action_channels": [ "FL_hip_target", "FL_thigh_target", "FL_calf_target", "FR_hip_target", "FR_thigh_target", "FR_calf_target", "RL_hip_target", "RL_thigh_target", "RL_calf_target", "RR_hip_target", "RR_thigh_target", "RR_calf_target" ], "joint_names": [ "FL_hip_joint", "FL_thigh_joint", "FL_calf_joint", "FR_hip_joint", "FR_thigh_joint", "FR_calf_joint", "RL_hip_joint", "RL_thigh_joint", "RL_calf_joint", "RR_hip_joint", "RR_thigh_joint", "RR_calf_joint" ], "base_body": "base_link", "action_rule": "absolute joint position targets = default_joint_pos + 0.25 * raw policy output (+ any OU target noise), applied over [t, t + 10 ms), constant over each 20 ms control period (records 2c, 2c + 1)", "default_joint_pos": [ -0.1, 0.9, -1.8, 0.1, 0.9, -1.8, -0.1, 0.9, -1.8, 0.1, 0.9, -1.8 ], "action_scale": 0.25, "kp": [ 20.0, 20.0, 40.0, 20.0, 20.0, 40.0, 20.0, 20.0, 40.0, 20.0, 20.0, 40.0 ], "kd": [ 1.0, 1.0, 2.0, 1.0, 1.0, 2.0, 1.0, 1.0, 2.0, 1.0, 1.0, 2.0 ], "effort_limit_nm": [ 23.5, 23.5, 45.0, 23.5, 23.5, 45.0, 23.5, 23.5, 45.0, 23.5, 23.5, 45.0 ] }, { "name": "ground", "kind": "plane", "moving": false, "top_z_m": 0.0, "size": "flat ground (mjlab plane; CRM soil bed: see physics_config.crm)" } ], "pairs": [ [ 0, 1 ], [ 0, 1 ], [ 0, 1 ], [ 0, 1 ] ], "pair_metadata": [ { "name": "FL_leg_ground", "leg": "FL", "robot_geoms": { "rigid": [ "FL_foot_collision" ], "crm": [ "FL_foot (FSI sphere)", "FL_calf (FSI cylinder)" ] }, "ground_geoms": { "rigid": [ "terrain" ], "crm": [ "CRM soil" ] } }, { "name": "FR_leg_ground", "leg": "FR", "robot_geoms": { "rigid": [ "FR_foot_collision" ], "crm": [ "FR_foot (FSI sphere)", "FR_calf (FSI cylinder)" ] }, "ground_geoms": { "rigid": [ "terrain" ], "crm": [ "CRM soil" ] } }, { "name": "RL_leg_ground", "leg": "RL", "robot_geoms": { "rigid": [ "RL_foot_collision" ], "crm": [ "RL_foot (FSI sphere)", "RL_calf (FSI cylinder)" ] }, "ground_geoms": { "rigid": [ "terrain" ], "crm": [ "CRM soil" ] } }, { "name": "RR_leg_ground", "leg": "RR", "robot_geoms": { "rigid": [ "RR_foot_collision" ], "crm": [ "RR_foot (FSI sphere)", "RR_calf (FSI cylinder)" ] }, "ground_geoms": { "rigid": [ "terrain" ], "crm": [ "CRM soil" ] } } ], "target_body": 0, "contact_rule": { "crm": { "threshold_n": 20.0, "rule": "pair p (leg FL/FR/RL/RR vs soil) on in record interval k if the norm of the vector sum of the foot-sphere and calf-cylinder FSI forces (world, GetFsiBodyForce) of the leg, per force read; non-negative by construction (NRD_PLAN.md section 10, review D3) exceeds threshold_n in ANY force read acting inside (t_k, t_k + 10 ms]; contact_force = the largest value over those reads", "component": "norm of the vector sum of the foot-sphere and calf-cylinder FSI forces (world, GetFsiBodyForce) of the leg, per force read; non-negative by construction (NRD_PLAN.md section 10, review D3)", "aggregation": "max over the force reads acting in the interval", "step": "FSI exchange 1.0 ms (2 MBD substeps)", "read_window": [ 2, 1 ], "read_timing": "CRM: exchange s is driven by the GetFsiBodyForce values read after exchanges s-2 and s-1 (one 0.5 ms MBD substep each); rigid: GetContactForce after a step is that step's force", "diagnostics": "CRM foot_force / calf_force = max force norm over the same reads; crm_free = all 8 body norms < 1.0 N in every read of the interval (contract section 11)", "relabelled_from_contact_force": true } }, "categories": { "crm": { "ground_id": 1 } }, "grounds": [ "rigid", "crm" ], "ground_ids": { "rigid": 0, "crm": 1 }, "families": [ { "name": "nominal", "group": "nominal", "select": true, "note": "mjlab policy on Kyle Sha's 10 command families (20 s, redrawn every 10 s), OU target noise sigma U(0, 0.05) rad, no pushes" }, { "name": "difficult", "group": "difficult", "select": true, "note": "the same command families with Kyle's OU target noise (sigma log-U(0.10, 0.22) rad, tau 0.15 s) and 2 pushes of 0.1 s, 8-140 N; 25 % long push-free slowed episodes; push windows excised (pieces share the parent's group)" }, { "name": "probe_drop", "group": "probe", "select": false, "note": "walking pose released 0.10-0.60 m above the ground (attitude up to 15 deg, joint offsets +-0.15 rad, command in the evaluation envelope), policy active, 1.2 s: contact-free windows, then the landing" }, { "name": "probe_landing", "group": "probe", "select": false, "note": "low tilted release (0.01-0.12 m, tilt up to 20 deg), policy active, 1.5 s: single feet touch first" } ], "terminal_reasons": [ "planned_end", "fell", "tilt", "nonfoot_contact", "nonfinite", "off_bed", "fsi_abort", "push_cut", "validity_cut", "chunk" ], "termination": { "min_base_height_m": 0.15, "max_tilt_rad": 1.2217304763960306, "rule": "a collector ends an episode at: a non-foot robot geom touching the ground (rigid; the last kept record is the one before the interval with the contact), base z below min_base_height_m above the surface, tilt above max_tilt_rad, a non-finite state, the base off the soil bed (CRM), an FSI abort (CRM); the terminal state is recorded" }, "physics_config": { "crm": { "simulator": "Chrono (pychrono)", "pychrono": "unknown", "pychrono_core_md5": "2387ec6dda45eaa5", "backend": "chrono-crm", "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e", "soil": { "keys": { "cohesion_pa": "SoilProperties.cohesion_coeff (Pa)", "friction": "SoilProperties.mu_fric_s = mu_fric_2 (internal friction mu_s = mu_2)", "density": "SoilProperties.density (kg/m^3)", "young_modulus_pa": "SoilProperties.Young_modulus (Pa)" }, "base": { "cohesion_pa": 2000.0, "friction": 0.8, "density": 1700.0, "young_modulus_pa": 500000.0 }, "evaluator_defaults": { "cohesion_pa": 2000.0, "friction": 0.8, "density": 1700.0, "young_modulus_pa": 500000.0 }, "per_episode": "each episode's soil: RawEpisode.meta['soil'].values (raw shard meta 'soil'; export manifest shard_meta[i].soil); params.crm.soil and build_id here are the campaign base, the episode's own build id is RawEpisode.meta['build']" }, "terrain": "crm", "params": { "terrain": "crm", "pd_mode": "substep", "urdf": "go2_mjlab.urdf sha256 5d9b51e03a4215c71c2ad2dd9b97d3dce448a5baf67cdb7ae8262737201746d6", "rigid_mbd_step_s": 0.0005, "exchange_step_s": null, "solver_iterations": 100, "contact": { "friction": 0.9, "restitution": 0.01, "kn": 200000.0, "gn": 60.0, "envelope_m": 0.0025, "margin_m": 0.0025 }, "crm": { "spacing_m": 0.02, "depth_m": 0.2, "cfd_step_s": 0.0005, "integration": "RK2", "d0_multiplier": 1.0, "free_surface_threshold": 0.8, "artificial_viscosity": 2.0, "foot_radius_m": 0.025, "calf_fsi": true, "calf_radius_m": 0.02, "calf_length_m": 0.2, "active_domain_m": 0.5, "active_domain_delay_s": 0.1, "bed_margin_m": 0.25, "bed_override_m": null, "soil": { "density": 1700.0, "young_modulus_pa": 500000.0, "poisson_ratio": 0.3, "mu_i0": 0.04, "friction": 0.8, "average_diam_m": 0.005, "cohesion_pa": 2000.0 } } }, "robot": { "robot": "go2_mjlab", "rotor": { "enabled": true, "coupling": "relative", "ratio": 1.0, "shaft_inertia": 0.0001, "compensate": true, "armature_scale": 1.0 }, "armature": { "FL_hip_joint": 0.01, "FL_thigh_joint": 0.01, "FL_calf_joint": 0.02, "FR_hip_joint": 0.01, "FR_thigh_joint": 0.01, "FR_calf_joint": 0.02, "RL_hip_joint": 0.01, "RL_thigh_joint": 0.01, "RL_calf_joint": 0.02, "RR_hip_joint": 0.01, "RR_thigh_joint": 0.01, "RR_calf_joint": 0.02 }, "legacy_calf_fsi": true, "joint_limits": { "mode": "mujoco", "params_sha256": "e8de60cb6fe591c8" } }, "robot_mass_kg": 15.206408, "mbd_step_s": 0.0005, "sample_step_s": 0.001, "fsi_exchange_step_s": 0.001, "rigid_sample_note": null, "surface_z_in_sim": 0.2, "deploy": { "config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2", "model_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45", "ll_dt": 0.005, "policy_dt": 0.019999999552965164, "tau_max": [ 23.5, 23.5, 45.0, 23.5, 23.5, 45.0, 23.5, 23.5, 45.0, 23.5, 23.5, 45.0 ], "torque_clip": false, "command_clip": "none", "fixstand_kp": [ 60.0, 80.0, 80.0, 60.0, 80.0, 80.0, 60.0, 80.0, 80.0, 60.0, 80.0, 80.0 ], "fixstand_kd": [ 5.0, 4.0, 4.0, 5.0, 4.0, 4.0, 5.0, 4.0, 4.0, 5.0, 4.0, 4.0 ] }, "startup": "task: FixStand 1 s (go2.yaml gains, quintic from the spawn pose), START in the last stand tick, records from the first policy tick; probes: spawn in the air at the planned pose, policy gains and policy reset at spawn (phase counter = plan phase_k0)", "injection": "plan OU target noise added to the HighController target before torqueClip (motor order)", "push": "world-frame force at the base COM through a base force accumulator, set at the planned record boundaries; acts 0.5 ms (one MBD step) later for exactly 0.1 s (Chrono accumulator update lag)", "force_read_window": { "lo": 2, "hi": 1, "rule": "steps a+1..b <- reads a+1-lo..b-hi" }, "nonfoot": "rigid: kinematic, any mjlab non-foot collision geom (base, hips, thighs, calves) below the box top, or base contact force; CRM: base, hip or thigh geom below the nominal soil top in any 1.0 ms exchange; both end the episode (terminal reason nonfoot_contact)", "actuator": "PD law at every MBD step, clamped at the effort limit (23.5 / 45 N m) per step; no deploy torqueClip", "joint_limits": "MuJoCo default soft joint limit of the mjlab model as a one-sided torque in the PD law (go2nrd.chrono_robot.limits; robot.joint_limits)", "terrain_relief": { "schema": "go2nrd_crm_relief_v1", "construct": "ChFsiProblemCartesian::Construct(sph_file, bce_file, (-px/2, -py/2, 0), grid) with the flat-bed lattice and column tops shifted by dk = round(h / spacing) layers; AddBoxContainer walls/bottom written point for point; flat blocks use the unchanged box Construct", "nominal_surface": "z = depth_m (flat-bed top); state z and diag foot z stay relative to it", "nonfoot_rule": "relief beds: base / hip / thigh lowest point below the LOCAL initial soil top (nominal + dk * spacing at the geom centre) in any 1 ms exchange ends the episode; flat blocks: nominal top", "per_episode": "RawEpisode.meta['terrain_relief'] (spec, seed, dk sha256, layer stats); diag relief_dk, surface_*" }, "swing_lift": { "schema": "go2nrd_swing_lift_v1", "module": "go2nrd.collect.chrono.swing_lift", "rule": "per control step, if ||command|| >= 0.1 and a plan hold is active: leg j in swing (teacher gait clock gp = fmod(k*0.02, 0.6)/0.6, leg offsets FL 0.5 FR 0 RL 0 RR 0.5, window [swing_start, swing_start + swing_length)) gets calf -= A ramp sin(pi s)^2 and thigh += thigh_per_calf * that; added to the HighController target with the OU injection, before torqueClip and float32 LowCmd; recorded action contains it", "leg_phase_offset": [ 0.5, 0.0, 0.0, 0.5 ], "period_s": 0.6, "command_threshold": 0.1, "raw_per_record": "swing_lift [L, 12] policy order (rad)", "diag": [ "swing_lift_offset", "swing_lift_weight", "swing_lift_env", "swing_lift_k", "injection_applied" ] } } }, "extras": { "ground": "[N] int8 ground id of each episode (system.json ground_ids); optional (version B of the NRD)", "episode_id": "[N] int64 = parent_episode_id * 10 + piece", "parent_episode_id": "[N] int64 planned episode id; piece [N] int8 its push piece; record_offset [N] int32 first parent record of the piece", "group_id": "[N] int64 = the parent's planned group (pieces share it and the split)", "obs": "[N, T, 47] policy observation at policy records (even records), NaN elsewhere", "raw_action": "[N, T, 12] raw policy output at policy records, NaN elsewhere", "command": "[N, T, 3] (vx, vy, wz) command of the control period containing the record", "phase_k": "[N, T] int32 the policy's phase counter k", "push_force": "[N, T, 3] world push force in [t, t + 10 ms) (excised in kept data: zero)", "nonfoot_contact": "[N, T] uint8 non-foot ground contact in [t, t + 10 ms)", "contact_force": "[N, T-1, 4] max pair normal force over the interval's steps (N)", "foot_force, calf_force": "[N, T-1, 4] optional CRM diagnostics (N)", "validity_check": "[N] int8 0 = none, else 1 + index of the export validity check that cut the episode", "soil": "[N, 4] float32 soil of each episode, columns soil_columns (cohesion_pa, friction = mu_s = mu_2, density, young_modulus_pa); NaN on rigid ground (ground 0)", "ground_features": "[N, 3] float32 version-B ground features, names ground_feature_names; f = [1, log1p(cohesion_pa / 250) / log(17), (friction - 0.6) / 0.3] on CRM (0..1 over the corpus soil range cohesion [0, 4000] Pa, friction [0.6, 0.9]); f = [0, 0, 0] on rigid ground", "prev_raw_action": "[N, 12] float32 the raw action the policy saw as its last action at the piece's first record (obs[35:47] there: the hand-over / stand value at record 0, 0 for probes, raw_action[s - 2] inside an episode); review D8", "crm_free": "[N, T-1] uint8 CRM free flag per interval (1 = all 8 FSI force norms < 1 N in every exchange; rigid rows 0 = not applicable; padding 0); a CRM core window needs it on all its intervals (core_free_flag)" }, "core_free_flag": { "array": "crm_free", "grounds": [ "crm" ], "rule": "a core (contact-free) window of an episode whose ground is listed also needs array = 1 on every record interval the window spans (train.py: intervals r - stride .. r + stride - 1 of the window at record r); other grounds: the contact labels only" }, "soil_columns": [ "cohesion_pa", "friction", "density", "young_modulus_pa" ], "ground_feature_names": [ "is_crm", "cohesion_code", "friction_code" ], "ground_feature_rule": "f = [1, log1p(cohesion_pa / 250) / log(17), (friction - 0.6) / 0.3] on CRM (0..1 over the corpus soil range cohesion [0, 4000] Pa, friction [0.6, 0.9]); f = [0, 0, 0] on rigid ground", "evaluation": { "note": "Task metrics of Go2 contact NRD training (checkpoint selection) and test. Port of NeDM configs/contact_nrd/evaluation/g1_locomotion.json (6d3f4396d, sha256 43013438...) to Go2: 4 leg-ground pairs, fall flag base z < 0.15 m or tilt > 45 deg, 2 s long windows (report), event windows at least 0.1 s apart. Every value and its reason: configs/evaluation/README.md. Provisional: freeze after the pilot, before main training and the sealed test.", "free": {}, "windows": { "horizons_s": [ 0.02, 0.2, 0.5, 1.0 ], "first_start_s": 0.1, "start_every_s": 0.5, "end_window": true }, "long_windows": { "horizons_s": [ 2.0 ], "first_start_s": 0.1, "start_every_s": 1.0 }, "event_windows": { "horizons_s": [ 0.2, 0.5, 1.0 ], "lead_s": 0.1, "min_gap_s": 0.1, "events": [ "onset" ] }, "flags": { "fall": { "any": [ { "body": "robot", "channel": "z", "below": 0.15 }, { "body": "robot", "tilt_above_rad": 0.7853981633974483 } ] } }, "contact_tolerance_steps": 2, "batch": 2048, "score": [ { "stat": "windows/1.0/robot/pos_m/p95", "scale": 0.05, "weight": 1.0 }, { "stat": "windows/1.0/robot/angle_rad/p95", "scale": 0.08726646259971647, "weight": 1.0 }, { "stat": "windows/1.0/robot/joint_rms_rad/p95", "scale": 0.1, "weight": 1.0 }, { "stat": "windows/contacts/all/event_error_rate", "scale": 0.1, "weight": 1.0 }, { "stat": "windows/contacts/all/timing_s/p95", "scale": 0.02, "weight": 1.0 }, { "stat": "windows/flags/fall/disagreement", "scale": 0.01, "weight": 1.0 }, { "stat": "nonfinite_fraction", "scale": 0.01, "weight": 1.0 } ] }, "campaigns": [ "lateral_stuck_20261108_crm_v2" ]}123version https://git-lfs.github.com/spec/v1oid sha256:f1079976f3f407596714bdcf9cc7616bd162280e1e6358cc9d21e03a6b9fa7a2size 54009166go2_sand_finetune/README.mdAdded+160
go2_sand_finetune/code/REPRODUCE.mdAdded+199
go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/episode.pyAdded+785
go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/relief.pyAdded+386
go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/run.pyAdded+349
go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/swing_lift.pyAdded+161
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/cluster/train_amd.sbatchAdded+63
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/configs/fresh_lat_v2.jsonAdded+53
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/nrd_v3_train.pyAdded+571
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/samplers.pyAdded+326
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/stall_support.pyAdded+88
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/src/go2nrd/fixed_base/three_transformer.pyAdded+436
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/ppo_nrdv3_euler.sbatchAdded+46
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/recipes/overlay_nrdv3_ood.jsonAdded+9
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/recipes/v2.jsonAdded+71
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/eval/export_onnx.pyAdded+247
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/fixed_base/ppo_lateral_v3.pyAdded+166
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/env.pyAdded+898
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/lateral_v3.pyAdded+529
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/ppo.pyAdded+129
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/runner.pyAdded+286
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/helpers_src/go2nrd/eval/parity.pyAdded+134
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/nrd_v3/train/export_loader.pyAdded+102
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_nrdv3/build_ood_reference.pyAdded+169
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_nrdv3/export_nrdv3.pyAdded+142
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_v3/build_start_groups.pyAdded+92
go2_sand_finetune/code/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75.tar.gzAdded+3
go2_sand_finetune/code/collector_crm_code_v1_d8ef2fc8d989.tar.gzAdded+3
go2_sand_finetune/code/collector_rigid_mjlab_nrd_3a9155b.tar.gzAdded+3
go2_sand_finetune/code/eval_capsule_runtime_eval_v1_30417413.tar.gzAdded+3
go2_sand_finetune/code/eval_chrono_suite_v1_p2nrd_699bc991a430.tar.gzAdded+3
go2_sand_finetune/code/eval_chrono_suite_v2_q1_d407c6940ef1.tar.gzAdded+3
go2_sand_finetune/code/go2nrd_worktree_snapshot.tar.gzAdded+3
go2_sand_finetune/code/nrd_capsule_c0e07a22e57434cd.tar.gzAdded+3
go2_sand_finetune/code/ppo_snapshot_8e08e2544f0d.tar.gzAdded+3
go2_sand_finetune/code/source_manifest.jsonAdded
go2_sand_finetune/code/study_scripts_lateral_stuck_20261108.tar.gzAdded+3
go2_sand_finetune/data/EXPORT_NAMES.jsonAdded+268
go2_sand_finetune/data/aux/rigid_test_s0000.npzAdded+3
go2_sand_finetune/data/crm_prod/crm_gates.jsonAdded
go2_sand_finetune/data/crm_prod/crm_gates_brief.jsonAdded+230
go2_sand_finetune/data/crm_prod/export.logAdded+44
go2_sand_finetune/data/crm_prod/manifest.jsonAdded
go2_sand_finetune/data/crm_prod/system.jsonAdded+706
go2_sand_finetune/data/crm_prod/unified_data.npzAdded+3
go2_sand_finetune/data/crm_prod/validate_report.jsonAdded+471
go2_sand_finetune/data/lateral_crm_v2_cuda/export.logAdded+44
go2_sand_finetune/data/lateral_crm_v2_cuda/manifest.jsonAdded
go2_sand_finetune/data/lateral_crm_v2_cuda/system.jsonAdded+734
go2_sand_finetune/data/lateral_crm_v2_cuda/unified_data.npzAdded+3