harryzhang1018 commited on
Commit
ee97b73
·
verified ·
1 Parent(s): 8a7a59e

go2_sand_finetune: data, NRD, policy V2n s81, code and evaluation records

Browse files

Go2 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) hide show
  1. go2_sand_finetune/README.md +160 -0
  2. go2_sand_finetune/code/REPRODUCE.md +199 -0
  3. go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/episode.py +785 -0
  4. go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/relief.py +386 -0
  5. go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/run.py +349 -0
  6. go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/swing_lift.py +161 -0
  7. go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/cluster/train_amd.sbatch +63 -0
  8. go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/configs/fresh_lat_v2.json +53 -0
  9. go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/nrd_v3_train.py +571 -0
  10. go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/samplers.py +326 -0
  11. go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/stall_support.py +88 -0
  12. go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/src/go2nrd/fixed_base/three_transformer.py +436 -0
  13. go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/ppo_nrdv3_euler.sbatch +46 -0
  14. go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/recipes/overlay_nrdv3_ood.json +9 -0
  15. go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/recipes/v2.json +71 -0
  16. go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/eval/export_onnx.py +247 -0
  17. go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/fixed_base/ppo_lateral_v3.py +166 -0
  18. go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/env.py +898 -0
  19. go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/lateral_v3.py +529 -0
  20. go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/ppo.py +129 -0
  21. go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/runner.py +286 -0
  22. go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/helpers_src/go2nrd/eval/parity.py +134 -0
  23. go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/nrd_v3/train/export_loader.py +102 -0
  24. go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_nrdv3/build_ood_reference.py +169 -0
  25. go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_nrdv3/export_nrdv3.py +142 -0
  26. go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_v3/build_start_groups.py +92 -0
  27. go2_sand_finetune/code/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75.tar.gz +3 -0
  28. go2_sand_finetune/code/collector_crm_code_v1_d8ef2fc8d989.tar.gz +3 -0
  29. go2_sand_finetune/code/collector_rigid_mjlab_nrd_3a9155b.tar.gz +3 -0
  30. go2_sand_finetune/code/eval_capsule_runtime_eval_v1_30417413.tar.gz +3 -0
  31. go2_sand_finetune/code/eval_chrono_suite_v1_p2nrd_699bc991a430.tar.gz +3 -0
  32. go2_sand_finetune/code/eval_chrono_suite_v2_q1_d407c6940ef1.tar.gz +3 -0
  33. go2_sand_finetune/code/go2nrd_worktree_snapshot.tar.gz +3 -0
  34. go2_sand_finetune/code/nrd_capsule_c0e07a22e57434cd.tar.gz +3 -0
  35. go2_sand_finetune/code/ppo_snapshot_8e08e2544f0d.tar.gz +3 -0
  36. go2_sand_finetune/code/source_manifest.json +0 -0
  37. go2_sand_finetune/code/study_scripts_lateral_stuck_20261108.tar.gz +3 -0
  38. go2_sand_finetune/data/EXPORT_NAMES.json +268 -0
  39. go2_sand_finetune/data/aux/rigid_test_s0000.npz +3 -0
  40. go2_sand_finetune/data/crm_prod/crm_gates.json +0 -0
  41. go2_sand_finetune/data/crm_prod/crm_gates_brief.json +230 -0
  42. go2_sand_finetune/data/crm_prod/export.log +44 -0
  43. go2_sand_finetune/data/crm_prod/manifest.json +0 -0
  44. go2_sand_finetune/data/crm_prod/system.json +706 -0
  45. go2_sand_finetune/data/crm_prod/unified_data.npz +3 -0
  46. go2_sand_finetune/data/crm_prod/validate_report.json +471 -0
  47. go2_sand_finetune/data/lateral_crm_v2_cuda/export.log +44 -0
  48. go2_sand_finetune/data/lateral_crm_v2_cuda/manifest.json +0 -0
  49. go2_sand_finetune/data/lateral_crm_v2_cuda/system.json +734 -0
  50. go2_sand_finetune/data/lateral_crm_v2_cuda/unified_data.npz +3 -0
go2_sand_finetune/README.md ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Go2 sand finetune: data, NRD and the policy V2n s81
2
+
3
+ This folder holds the full pipeline of one study: data → NRD → policy. A Unitree Go2 velocity policy stalled when it
4
+ walked sideways on sand. PPO fine-tuned it only inside a neural reduced dynamics model (NRD) of the Go2 on Project
5
+ Chrono CRM sand and on rigid ground. The released policy is **V2n s81** (deploy ONNX SHA-256
6
+ `1419d9722698c23a04b8805dd15f6eb25710e1f11860ffbad0cb1a63159674e9`). This is follow-on work to the NeDM paper, not
7
+ part of it. The results, the limits and the pinned manifest are in
8
+ [`go2_sand_finetune/` of the NeDM code repository](https://github.com/uwsbel/NeDM/tree/main/go2_sand_finetune).
9
+
10
+ ## Status
11
+
12
+ | Item | Status |
13
+ |---|---|
14
+ | 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 |
15
+ | MuJoCo rigid ground, 120 development paths | Tracking loss ratio 0.854 (95 % range 0.836 to 0.874), 0 falls |
16
+ | C++ deploy stack in MuJoCo, flat ground | Both test profiles completed, 0 falls (one run each) |
17
+ | 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` |
18
+ | 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/` |
19
+ | License | BSD-3-Clause, the same as the rest of this dataset |
20
+
21
+ All numbers in this table are simulation results. "Stuck time" is lateral hold time in 1 s windows where the lateral speed
22
+ is less than 0.4 of the command. A fall or an early stop counts the rest of the hold as stuck.
23
+
24
+ ## Layout
25
+
26
+ Sizes are approximate. `release_manifest.json` gives the exact size and SHA-256 of each file.
27
+
28
+ | Path under `go2_sand_finetune/` | Contents | Size |
29
+ |---|---|---|
30
+ | `README.md` | This study card | - |
31
+ | `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 | - |
32
+ | `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 |
33
+ | `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 |
34
+ | `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 |
35
+ | `data/lateral_crm_v2_cuda/` | The same plan, Euler CUDA build: 80 episodes, 149 pieces, 0.38 h | 54 MB |
36
+ | `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 |
37
+ | `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 |
38
+ | `data/splits/` | The parent split manifest and the lateral split manifest that the NRD used | 14 MB |
39
+ | `data/plans/` | Collection plans and plan arrays (commands, injections) | 0.22 GB |
40
+ | `data/reports/` | Collection, export and validation reports | 15 MB |
41
+ | `data/EXPORT_NAMES.json` | Map from these folder names to the original export names | - |
42
+ | `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 |
43
+ | `teacher/` | The base policy: PPO checkpoint `model_10000.pt`, deploy ONNX and configs, training parameters, job record | 6.6 MB |
44
+ | `nrd/fresh_b/` | The NRD: last checkpoint, resume state, stage-end checkpoints, loader export, training logs, validations, lineage, cluster job records | 89 MB |
45
+ | `nrd/gates/` | Pre-registered NRD gates, the waiver and the gate results. The gate scripts are in `code/` | 14 MB |
46
+ | `nrd/reports/` | NRD training, gate, replication and verification reports | 1.3 MB |
47
+ | `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/`) |
48
+ | `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) |
49
+ | `policy/inputs/` | PPO inputs: base config, recipe, overlay, start groups, OOD reference | 7.5 MB |
50
+ | `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 |
51
+ | `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 |
52
+ | `videos/mujoco_eval/` | Replays of the C++ deploy runs on rigid ground (base policy, V2n s81, an ensemble policy) | 60 MB |
53
+ | `code/` | Source archives of each step, `source_manifest.json`, `REPRODUCE.md`, browsable key scripts | 0.15 GB |
54
+ | `reports/` | Study report, durable state, verification reports, receipts, hardware note | 2.8 MB |
55
+
56
+ Total approximately 5.5 GB, of which `data/` is 5.0 GB.
57
+
58
+ ## Lineage
59
+
60
+ | Step | File in this folder | SHA-256 (first 8) |
61
+ |---|---|---|
62
+ | Base policy checkpoint / ONNX | `teacher/model_10000.pt` / `teacher/deploy/policy.onnx` | `7ee303f9` / `c58a3494` |
63
+ | Rigid data | `data/rigid_prod_v2/unified_data.npz` | `b02c0c50` |
64
+ | CRM data | `data/crm_prod/unified_data.npz` | `35b73ce2` |
65
+ | Lateral data, HIP / CUDA | `data/lateral_crm_v2_hip/unified_data.npz` / `data/lateral_crm_v2_cuda/unified_data.npz` | `2e78115a` / `f1079976` |
66
+ | Held-out lateral test | `data/lateral_crm_v2_test_hip/unified_data.npz` | `e1f18d48` |
67
+ | Split manifests, parent / lateral | `data/splits/splits_fixed_base_20261102.json` / `data/splits/splits_lateral_v2.json` | `f1d264dd` / `9ba6dce9` |
68
+ | NRD last checkpoint / loader export | `nrd/fresh_b/last.pt` / `nrd/fresh_b/export/nrd_v3_FRESH-b_loader.pt` | `b41561c3` / `501c9b8d` |
69
+ | PPO checkpoint | `policy/v2n_s81/run/model_299.pt` | `cdb54fb5` |
70
+ | Deploy ONNX | `policy/v2n_s81/deploy/legged_rl_deploy_package/policy.onnx` | `1419d972` |
71
+
72
+ - The base policy made all NRD training data. No episode of a fine-tuned policy is in the NRD data.
73
+ - The NRD trained from random weights in one AMD MI350X job (509956, 2.39 h). PPO ran in one Euler RTX A4500 job
74
+ (114010, 601 s of training).
75
+ - The deploy ONNX is a CPU re-export of `model_299.pt`. The run's own `policy.onnx` (`6e82a553`) has other bytes.
76
+
77
+ ## What the files contain
78
+
79
+ - `unified_data.npz` (uncompressed NumPy): `robot` [N, 1001, 37] (base position, quaternion wxyz, 12 joint angles,
80
+ base velocity, base angular velocity, 12 joint rates), `action` [N, 1001, 12] (joint position targets),
81
+ `contacts` [N, 1000, 4] (four feet), `command` [N, 1001, 3], `ground_features` [N, 3], `soil` [N, 4] (cohesion,
82
+ friction, density, Young's modulus), `lengths`, `splits` and more arrays. Records are 10 ms apart. The NRD step is
83
+ 20 ms. `system.json` gives the channels, families and contact rule. `manifest.json` gives the raw shards with their
84
+ SHA-256, the code hashes and the counts.
85
+ - The NRD loader export is a PyTorch checkpoint (`model_config`, `system`, `masks`, `model_state_dict`). It has three
86
+ Transformer networks (core, collision, contact; 4 layers, width 128, 4 heads, feed-forward 512) and a ground code of
87
+ 3 features. Load it with the `go2nrd` loader of the code archives. The raw `last.pt` does not load in that loader.
88
+ - `model_299.pt` is an RSL-RL checkpoint (`actor_state_dict`, `critic_state_dict`, `optimizer_state_dict`). The deploy
89
+ ONNX takes `obs` [1, 47] and gives `actions` [1, 12]. The observation normalization is in the graph.
90
+
91
+ ## Download and examine the files
92
+
93
+ `release_manifest.json` gives the size and the SHA-256 of each file. Its `hf_revision` is the Hub commit that added
94
+ the files. This example reads the manifest, downloads the policy and the NRD at `hf_revision`, then examines each
95
+ downloaded file:
96
+
97
+ ```python
98
+ import hashlib, json
99
+ from pathlib import Path
100
+ from huggingface_hub import hf_hub_download, snapshot_download
101
+
102
+ REPO = "harryzhang1018/NeDM"
103
+ MANIFEST_REV = "main" # to pin the manifest, use hub_manifest.hf_revision of the NeDM go2_sand_finetune pin file
104
+ manifest = json.loads(Path(hf_hub_download(REPO, "go2_sand_finetune/release_manifest.json",
105
+ repo_type="dataset", revision=MANIFEST_REV)).read_text())
106
+ REV = manifest["hf_revision"] # the commit that added the files in "files"
107
+ root = Path(snapshot_download(REPO, repo_type="dataset", revision=REV,
108
+ allow_patterns=["go2_sand_finetune/policy/*",
109
+ "go2_sand_finetune/nrd/fresh_b/*"]))
110
+ files = manifest["files"]
111
+ if isinstance(files, list):
112
+ files = {f["repo_path"]: f for f in files}
113
+ for path, f in sorted(files.items()):
114
+ p = root / path
115
+ if not p.exists():
116
+ continue
117
+ h = hashlib.sha256()
118
+ with p.open("rb") as fh:
119
+ for block in iter(lambda: fh.read(1 << 20), b""):
120
+ h.update(block)
121
+ assert p.stat().st_size == f["bytes"] and h.hexdigest() == f["sha256"], path
122
+ print("ok", path)
123
+ ```
124
+
125
+ - Add `"go2_sand_finetune/data/*"` to `allow_patterns` for the 5.0 GB of episodes.
126
+ - You cannot load the files with `datasets.load_dataset`. Read them with NumPy, PyTorch or ONNX Runtime.
127
+ - `code/REPRODUCE.md` tells how to rebuild each step from the source archives.
128
+
129
+ ## Paths in the files
130
+
131
+ Except the generated files (code archives, log archives, the compressed training log of the base policy, job records,
132
+ file inventories and release documents), the files are byte-exact copies of the study files. They keep
133
+ the machine-local and cluster paths of the study, for example `/home/harry/...` (workstation), `/work1/dannegrut/harry/...` (AMD cluster) and `/srv/home/hzhang699/...`
134
+ (Euler cluster). These paths are records of the original runs. Change them to your own paths before you run the code.
135
+ The split manifests and the run configs name the data folders by their original export names, for example
136
+ `lateral_stuck_20261108_crm_v2_hip`. `data/EXPORT_NAMES.json` maps these names to the folder names of this release.
137
+
138
+ ## Known limitations
139
+
140
+ - **Simulation results only.** The real-robot test is a user report. Nothing records the number of trials or the file
141
+ that ran.
142
+ - **NOT_CONFIRMED.** V2n s81 did not pass the held-out gates for falls, soft-sand wrong-way motion and power. The
143
+ study released it only as an experimental candidate.
144
+ - **NRD gates.** The NRD missed 2 rigid accuracy rules. A written waiver, made during the study, let PPO use
145
+ it.
146
+ - **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
147
+ a typical seed.
148
+ - **Falls are not in the NRD.** The NRD predicts almost no falls. All 5 held-out falls were on medium uneven sand.
149
+ - **Study soils.** The soil levels are study levels, not measured sand. Only the feet and calves of the Chrono robot
150
+ touch the particles.
151
+ - **Statistical reproduction.** Chrono CRM is not bit-deterministic on MI210. NRD training is not bitwise across GPU
152
+ types. PPO set no determinism flags. The Chrono builds are not in this folder.
153
+ - **Development data reuse.** The selection suite and the 120 rigid paths guided choices during the study.
154
+
155
+ ## License and citation
156
+
157
+ BSD-3-Clause, the same as the rest of this dataset and the NeDM code. Upstream projects keep their own licenses
158
+ (`unitree_rl_mjlab`: Apache License 2.0; the Unitree Go2 model files and the `legged_rl_deploy` code in the archives: their
159
+ upstream licenses). The study has no publication yet: please cite the NeDM paper and name the
160
+ dataset revision you used (`hf_revision` in `release_manifest.json`).
go2_sand_finetune/code/REPRODUCE.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reproduce the Go2 sand lateral fine-tune (data -> NRD -> policy V2n s81)
2
+
3
+ This guide gives the stages that made the policy V2n s81.
4
+ The real robot ran this policy as ONNX `1419d9722698c23a04b8805dd15f6eb25710e1f11860ffbad0cb1a63159674e9`.
5
+ Each stage names its entry point, its arguments, its archive and its environment.
6
+ The archive sha256 values and the per-file sha256 values are in `source_manifest.json`.
7
+
8
+ Important: a re-run gives a statistically similar result, not the same bytes.
9
+ Use the archived artifacts (data exports, NRD loader, model_299.pt, ONNX) as the reference.
10
+ Section 6 tells what is not bitwise reproducible.
11
+
12
+ ## 1. Archives in `code/`
13
+
14
+ | Archive | Stage | Code digest | How the digest was checked |
15
+ |---|---|---|---|
16
+ | `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. |
17
+ | `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. |
18
+ | `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. |
19
+ | `nrd_capsule_c0e07a22e57434cd.tar.gz` | NRD FRESH-b training | `c0e07a22e57434cd` | `sha256sum -c FILES.sha256` passes. Digest = sha256(FILES.sha256)[:16]. |
20
+ | `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]. |
21
+ | `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`. |
22
+ | `eval_capsule_runtime_eval_v1_30417413.tar.gz` | rigid dev120 judge (`go2nrd.fixed_base.rigid_judge`) | `30417413...` | SOURCE_SHA256.json verifies. Digest recomputed. |
23
+ | `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). |
24
+ | `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. |
25
+ | `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. |
26
+
27
+ The archives contain no git history.
28
+ Each archive has one top folder with the archive name.
29
+ `browse/<archive>/<path>` holds plain copies of the main entry points, taken from the archives.
30
+
31
+ ## 2. Before you start
32
+
33
+ 1. Unpack the archives into one work folder.
34
+ 2. The scripts contain absolute paths of the original machines. Replace them with your paths:
35
+ - 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).
36
+ - AMD HPC Fund cluster: `/work1/dannegrut/harry/go2nrd` and `/work1/dannegrut/harry/lateral_stuck_20261108`.
37
+ - Euler cluster: `/srv/home/hzhang699/go2nrd` and `/scratch/hzhang699/...`.
38
+ 3. The release renames the data folders. The code expects the original names. Make a data root with links:
39
+
40
+ | Release folder | Original folder name (use this name in the data root) |
41
+ |---|---|
42
+ | `data/rigid_prod_v2` | `rigid_prod_v2` |
43
+ | `data/crm_prod` | `crm_prod` |
44
+ | `data/lateral_crm_v2_hip` | `lateral_stuck_20261108_crm_v2_hip` |
45
+ | `data/lateral_crm_v2_cuda` | `lateral_stuck_20261108_crm_v2_cuda` |
46
+ | `data/lateral_crm_v2_test_hip` | `lateral_stuck_20261108_crm_v2_test_hip` (held out; the NRD driver refuses it) |
47
+ | `data/lateral_crm_v2_slim_diag` | `lateral_stuck_20261108_crm_v2_slim_diag` |
48
+
49
+ 4. There is no `pyproject.toml`. Each stage runs with `PYTHONPATH=<snapshot>/src`.
50
+ 5. The scripts check sha256 values of their inputs. A wrong file stops the script.
51
+
52
+ ## 3. Stage table
53
+
54
+ | # | Stage | Entry point | Archive | Where it ran | Date (CST) |
55
+ |---|---|---|---|---|---|
56
+ | 0 | Base teacher | unitree_rl_mjlab `Unitree-Go2-Flat` PPO, seed 42, 10,001 iterations | `teacher/` part | Euler job 95472 (euler17) | 2026-10-22 |
57
+ | 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 |
58
+ | 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 |
59
+ | 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 |
60
+ | 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 |
61
+ | 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 |
62
+ | 2b | lateral code freeze | `collect/scripts/cluster_freeze_code_v2.sh amd\|euler` | same | luffy -> clusters | 2026-11-08 22:57 |
63
+ | 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 |
64
+ | 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 |
65
+ | 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 |
66
+ | 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 |
67
+ | 4b | NRD capsule | `nrd_v3/train/cluster/make_capsule.sh OUT_PARENT` | study scripts; result = `nrd_capsule_c0e07a22e57434cd` | luffy | 2026-11-09 00:26 |
68
+ | 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 |
69
+ | 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 |
70
+ | 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 |
71
+ | 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 |
72
+ | 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 |
73
+ | 8c | PPO code snapshot | `ppo_nrdv3/make_snapshot.sh` | study scripts; result = `ppo_snapshot_8e08e2544f0d` | luffy | 2026-11-09 05:20:36 |
74
+ | 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 |
75
+ | 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 |
76
+ | 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 |
77
+ | 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 |
78
+ | 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 |
79
+ | 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 |
80
+
81
+ ## 4. Stage details
82
+
83
+ ### Stage 1: old data (rigid_prod_v2, crm_prod)
84
+
85
+ - The base teacher `model_10000.pt` (sha256 `7ee303f9...`) made all data. Its ONNX is `c58a3494...`.
86
+ - rigid_prod: MuJoCo Warp plane, deterministic mean action, 8,700 episodes, collector pushes.
87
+ - The rigid collector ran from a dirty tree. Its 7 file hashes equal commit `3a9155b`. The archive is `git archive 3a9155b -- src configs`.
88
+ - 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.
89
+ - 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`.
90
+ - The export step of both data sets equals commit `1346b2c` (`src/go2nrd/collect/common`, in `collector_crm_code_v1_d8ef2fc8d989`).
91
+
92
+ ### Stage 2: lateral v2 data
93
+
94
+ - Plan `lateral_stuck_20261108_crm_v2.json` sha256 `77ef91d9...`, master seed 2026110803, 480 planned episodes. Held-out plan `_test` sha256 `ae1f525c...`, seed 2026110804.
95
+ - The plans and their arrays are in `collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/configs/collect/plans/`.
96
+ - 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.
97
+ - 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`).
98
+ - The deploy config of all Chrono collections is `config_noclip.yaml` (`5ea19848`). It is with the teacher files, not in the code archives.
99
+
100
+ ### Stage 3: split manifest
101
+
102
+ - `splits_lateral_v2.json` (`9ba6dce9...`) extends `splits.json` (`f1d264dd...`). Both are in `nrd_capsule_c0e07a22e57434cd/manifests/`.
103
+ - Arm `mixed_plus_lat_v2`, budget `matched`. The test export is only in `heldout_test`.
104
+
105
+ ### Stage 5: NRD FRESH-b training
106
+
107
+ - Command inside `train_amd.sbatch`:
108
+ `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`
109
+ - `CODE` = the unpacked `nrd_capsule_c0e07a22e57434cd`. `DATA_ROOT` = the data root of section 2 (only the 4 training folders are read).
110
+ - Env: `OMP_NUM_THREADS=1`, `OPENBLAS_NUM_THREADS=1`, `PYTHONDONTWRITEBYTECODE=1`.
111
+ - Key file hashes: driver `nrd_v3_train.py` `73b6f253...`, `samplers.py` `b75f8f99...`, `stall_support.py` `adff6f30...`, recipe `df61c402...`.
112
+ - Schedule: stage A updates 1-12000 (core, collision, joint one-step, rollout H10->H50), stage B 12001-13000, stage C 13001-13500.
113
+ - 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/`.
114
+ - The sbatch refuses to run when `OUT/complete.json` exists. Use a new output folder.
115
+
116
+ ### Stage 6: loader export
117
+
118
+ - Command (same as `nrd_v3/replicate/collect_n2.sh`):
119
+ `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...`)
120
+ - `--frozen-src` = `nrd_capsule_c0e07a22e57434cd/src` (the frozen yaw_correction_v1 source).
121
+ - 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.
122
+ - `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`.
123
+ - 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.
124
+ - The weights do not change. The result is `501c9b8d...`. A re-run reproduced it bitwise with `OMP_NUM_THREADS=1`.
125
+
126
+ ### Stage 7: gates
127
+
128
+ - `gates_v1.json` (`38c85547...`) and `gates_v2.json` (`7ee59cb6...`) were registered before training.
129
+ - FRESH-b fails G1 on 2 rigid rules. `waiver_v1.json` (by the coordinator) allows its use for PPO.
130
+
131
+ ### Stage 8: PPO inputs
132
+
133
+ - 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/`.
134
+
135
+ ### Stage 9: PPO V2n s81
136
+
137
+ - Command inside `ppo_nrdv3_euler.sbatch`:
138
+ `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`
139
+ - `CODE` = the unpacked `ppo_snapshot_8e08e2544f0d`. `PYTHONPATH=<pydeps>:CODE/src`. `OMP_NUM_THREADS=8`.
140
+ - 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.
141
+ - The driver merges base config `5ceaa0bc` + recipe `162b4883` + overlay `17d563ae` into `config.json`.
142
+ - 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.
143
+ - Output: `model_299.pt` (`cdb54fb5...`), `config.json`, `frozen_audit.json`, `complete.json`, an in-run `policy.onnx` (`6e82a553...`, not the deployed file).
144
+ - The driver resumes from `last.pt` in OUT. Use a new output folder for a clean run.
145
+
146
+ ### Stage 10: deploy ONNX re-export and parity
147
+
148
+ - `export_nrdv3.py` asserts the exporter sha256 `5e418e4c...` and the teacher ONNX `c58a3494...`.
149
+ - 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>`.
150
+ - Exporter: opset 18, static input [1, 47], metadata copied from the teacher ONNX, normalizer inside the graph.
151
+ - Then `python -m go2nrd.eval.parity --folder EXPORTS/<name>_i299 --rows 4000` and a 4,000-row CRM parity.
152
+ - 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`.
153
+ - 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.
154
+ - Result: `policy.onnx` `1419d972...`. Max ONNX vs torch difference 9.5e-6.
155
+ - 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.
156
+
157
+ ### Stage 11: evaluation
158
+
159
+ - 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.
160
+ - Selection rule v1 (`selection/selection_rule_v1.json`, `9d30877c...`) picked V2n s81 (rank 1, score 0.221).
161
+ - The held-out suite_v2 label is NOT_CONFIRMED (G2, G3, S1). The rigid dev120 gate and the C++ sim_deploy check passed.
162
+ - The C++ `legged_rl_deploy_node` binary is not archived. Build it from the public legged_rl_deploy repo.
163
+
164
+ ## 5. Environments and hardware
165
+
166
+ | Stage | Hardware | Software (recorded) |
167
+ |---|---|---|
168
+ | Teacher | Euler euler17 | unitree_rl_mjlab commit `1425b15f` (see `teacher/`) |
169
+ | rigid_prod collection | luffy, NVIDIA RTX 5090 | python 3.11.17, mjlab env (MuJoCo Warp) |
170
+ | 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) |
171
+ | crm_prod collection | AMD MI210 (mi2101x) | Chrono CRM HIP build, venv `go2nrd`, module pytorch/2.10.0 |
172
+ | 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 |
173
+ | NRD training | AMD Instinct MI350X (mi3501x) | python 3.12.12, torch 2.10.0+rocm7.1, HIP 7.1.25424, numpy 2.4.3 |
174
+ | Loader export, gates | luffy RTX 5090 / CPU | `go2eval` env, torch 2.12.0+cu130 |
175
+ | 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` |
176
+ | Deploy ONNX export | luffy CPU | torch 2.12.0+cu130, onnx 1.22.0, numpy 2.4.6, onnxruntime 1.30.0 |
177
+ | Chrono evaluation | AMD MI210 (mi2101x) | HIP Chrono build (one binary for all roles of a tag) |
178
+ | Rigid dev120 | luffy RTX 5090 | unitree_rl_mjlab conda env |
179
+
180
+ No lock file exists. The cluster environments are not captured beyond these version strings.
181
+ The Chrono builds (pychrono with CRM, HIP and CUDA) are not archived.
182
+
183
+ ## 6. What is not bitwise reproducible
184
+
185
+ - Chrono collection on GPU: the CRM collector is not bit-deterministic on MI210. HIP and CUDA builds give different numbers.
186
+ - 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.
187
+ - PPO: only `torch.manual_seed` is set. No deterministic flags. A bitwise re-run was not tested.
188
+ - 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.
189
+ - 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.
190
+ - Loader export: bitwise with `OMP_NUM_THREADS=1` (shown).
191
+ - Deploy ONNX export: bitwise from the archived code (shown on 2026-11-17).
192
+ - The archives themselves are deterministic: sorted members, fixed mtime, owner 0, gzip mtime 0.
193
+
194
+ ## 7. Known gaps
195
+
196
+ - The go2nrd repository has no remote. Most study code is uncommitted. The archives are the only published copy.
197
+ - Intermediate NRD checkpoints (update_*.pt), PPO checkpoints model_25..model_275 and the Slurm stdout files exist only on the clusters.
198
+ - 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.
199
+ - The selection label of V2n s81 is NOT_CONFIRMED. It was packaged as experimental.
go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/episode.py ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One Chrono collection episode (task or probe) of the mjlab policy, deploy-faithful, recorded at 10 ms.
2
+
3
+ New file (go2nrd Chrono collector builder, 2026-10-29). The loop follows legged_sim_eval ``episode.run_episode``
4
+ (``/home/harry/go2_sand/legged_rl_deploy/sim_eval/legged_sim_eval/episode.py``, uncommitted user checkout of
5
+ 2026-10-22, read-only): build, ``LowLevel.enter_fixstand``, 1 s FixStand (go2.yaml gains, quintic), START in the last
6
+ stand tick (``DeployPolicy.reset``), then the policy at every 4th 5 ms tick through ``DirectCommand``, ``torqueClip``,
7
+ the float32 LowCmd and the PD law at every 0.5 ms MBD step (``pd_mode=substep``, also inside the FSI step). Changes
8
+ for collection (plan: specs/NRD_PLAN.md; contract: nrd/configs/collect/CONTRACT.md):
9
+
10
+ * fix_chrono worker, 2026-10-30 (NRD_PLAN.md section 10): ``torqueClip`` OFF by default (``EpisodeSpec.torque_clip``;
11
+ 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
12
+ recorded action); the robot's MuJoCo soft joint limit (``go2nrd.chrono_robot.limits``, backend option
13
+ ``joint_limits``); CRM label = norm of the vector sum of the foot-sphere and calf-cylinder FSI forces; per-interval
14
+ CRM free flag ``crm_free`` (contract section 11); a CRM non-foot geom below the soil top ends the episode
15
+ (``nonfoot_contact``, review D11); diag keeps every read's force vectors and the per-record joint-limit torque;
16
+
17
+ * records every 2 ticks from the hand-over tick (record 0 = the first policy tick; the stand is not recorded): the
18
+ 37-channel base_link REF-frame state (``CollectorGo2Sim.state37``) read at the tick start, before ``apply``;
19
+ * ``action[t]`` = the joint target the PD law gets over [t, t + 10 ms) (``sent.q`` in policy order: float32 of
20
+ ``default + 0.25 raw + injection``), checked equal on the record's two ticks;
21
+ * the plan's command per control step, the plan's OU injection (``InjectingLowLevel``), pushes (base COM, world);
22
+ * per physics step (CRM: every 1.0 ms FSI exchange; rigid: every 0.5 ms MBD step) the pair forces; labels from the
23
+ max over the reads that act inside the interval (measured read timing, :data:`FORCE_READ_WINDOW`);
24
+ * terminations: nonfinite, fell (z < 0.15 m), tilt (> 70 deg), off_bed (CRM: base REF x, y within 0.25 m of the bed
25
+ edge), nonfoot_contact (rigid: a non-foot mjlab collision geom below the surface or base contact in the interval;
26
+ CRM: a base / hip / thigh mjlab collision geom below the NOMINAL soil top in any 1.0 ms exchange of the interval --
27
+ those bodies are not FSI bodies, the soil would not push them; the nominal top is conservative where the soil has
28
+ sunk and is never more than the few cm of heave below the deformed top); a nonfoot event finishes its already
29
+ driven 10ms interval and retains the finite endpoint before another policy/low-level tick; nonfinite endpoints
30
+ are discarded as numerical failure rather than fabricated;
31
+ * probes: no stand; spawn at the planned attitude / clearance with default + offsets, policy gains from tick 0, the
32
+ policy reset at spawn with its phase counter set to ``phase_k0``;
33
+ * CRM soil per episode (:mod:`go2nrd.collect.chrono.soil`, soil_sweep worker 2026-10-29): cohesion, internal friction
34
+ mu_s = mu_2, density, Young's modulus from the plan entry's ``soil`` / the run's soil map / the campaign base, as
35
+ evaluator backend options; defaults = the evaluator's soil. Recorded in ``RawEpisode.meta["soil"]`` and the raw
36
+ shard meta; ``physics_config`` keeps the campaign base (identical over the campaign).
37
+
38
+ * opt-in uneven initial CRM surface (lateral_stuck_20261108, :mod:`go2nrd.collect.chrono.relief`): a plan entry's
39
+ ``terrain_relief`` block makes the scene build the bed from a relief lattice (flat blocks: the unchanged box bed),
40
+ adds ``physics_config["terrain_relief"]``, ``RawEpisode.meta["terrain_relief"]`` and the diag arrays ``relief_dk`` /
41
+ ``surface_*``; entries without the key run exactly as before.
42
+ * opt-in swing-lift perturbation (lateral_stuck_20261108 track A, :mod:`go2nrd.collect.chrono.swing_lift`): a plan
43
+ entry's ``swing_lift`` block adds, per control step, a leg-folding offset to the joint target of each leg in its
44
+ swing phase (teacher gait clock, causal) next to the OU injection; the recorded ``action`` contains it. Adds
45
+ ``physics_config["swing_lift"]``, ``RawEpisode.meta["swing_lift"]``, the raw per-record array ``swing_lift`` and
46
+ the diag arrays ``swing_lift_*`` / ``injection_applied``; entries without the key run exactly as before.
47
+
48
+ Partial records are flushed every ``flush_every`` records (atomic npz), so an FSI process abort keeps what was done.
49
+
50
+ Child entry point (one process per attempt; ``go2nrd.collect.chrono.run`` writes the spec)::
51
+
52
+ python -B -m go2nrd.collect.chrono.episode SPEC.json
53
+ """
54
+
55
+ from __future__ import annotations
56
+
57
+ import dataclasses
58
+ import hashlib
59
+ import json
60
+ import math
61
+ import os
62
+ import shutil
63
+ import sys
64
+ import time
65
+ import traceback
66
+ from dataclasses import dataclass, field
67
+ from functools import lru_cache
68
+ from pathlib import Path
69
+ from typing import Any
70
+
71
+ import numpy as np
72
+
73
+ from go2nrd.collect.chrono import soil as S
74
+ from go2nrd.collect.common import contract as C
75
+ from go2nrd.collect.common.plan import probe_initial_state, probe_initial_velocity
76
+
77
+ COLLECTOR_NAME = "go2nrd.collect.chrono"
78
+ COLLECTOR_VERSION = "2"
79
+ FORCE_READ_WINDOW = {"crm": (2, 1), "rigid": (0, 0)}
80
+ """Which force reads act inside a span of steps: the steps a+1 .. b are driven by the reads a+1-lo .. b-hi
81
+ (read j = the value read right after step j; read 0 = before the first step). Measured with the robot's linear
82
+ momentum balance (go2nrd.collect.chrono.analysis.momentum_timing; reports/build_chrono.md):
83
+
84
+ * rigid (lo, hi) = (0, 0): ``GetContactForce`` read after an MBD step is the force of that step (residual 3e-6 N);
85
+ * CRM (lo, hi) = (2, 1): the momentum change over FSI exchange s is exactly (read[s-2] + read[s-1]) / 2 * dt
86
+ (residual < 1e-6 N): the first 0.5 ms MBD substep of exchange s uses the ``GetFsiBodyForce`` value read after
87
+ 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
88
+ steps a+1 .. b use the reads a-1 .. b-1 (11 reads, the outer two for half an exchange each).
89
+ """
90
+ CONTACT_THRESHOLD_N = {"rigid": 1.0, "crm": 20.0}
91
+ """Label threshold written into the raw shards: rigid 1 N (G1 rule); CRM 20 N: the NRD_PLAN.md section 10 rule on the
92
+ HIP-build pilot (fix_chrono 2026-10-30, reports/fix_chrono.md: 8 soils, cohesion 0 / 250 / 1000 / 4000 Pa x mu 0.6 /
93
+ 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 best
94
+ mean agreement with the kinematic stance estimate, 0.888, with flicker <= 0.04 per s per foot on every soil; 10 and
95
+ 15 N exceed 0.1 per s on soft soil). export --threshold-n relabels exactly from contact_force."""
96
+ CRM_PAIR_RULE = ("norm of the vector sum of the foot-sphere and calf-cylinder FSI forces (world, GetFsiBodyForce) of "
97
+ "the leg, per force read; non-negative by construction (NRD_PLAN.md section 10, review D3)")
98
+ CRM_FREE_FORCE_N = C.CRM_FREE_FORCE_N
99
+ FREE_FLAG = getattr(C, "CRM_FREE_FLAG", "crm_free")
100
+ """Per-interval CRM free flag name (contract section 11)."""
101
+ STAND_S = 1.0
102
+ FLUSH_EVERY = 100
103
+ TEST_ABORT_ENV = "GO2NRD_CHRONO_TEST_ABORT"
104
+ """Test hook: ``"<record>:<attempt>,<attempt>"`` makes the child call ``os.abort()`` (SIGABRT, like a CUDA / FSI
105
+ abort) when it reaches that record in one of those attempts. Unset in real runs."""
106
+
107
+
108
+ def _test_abort(record: int, attempt: int) -> None:
109
+ hook = os.environ.get(TEST_ABORT_ENV)
110
+ if not hook:
111
+ return
112
+ at, _, attempts = hook.partition(":")
113
+ if record == int(at) and (not attempts or attempt in {int(a) for a in attempts.split(",")}):
114
+ sys.stdout.flush()
115
+ os.abort()
116
+
117
+
118
+ @dataclass
119
+ class EpisodeSpec:
120
+ """Everything one attempt needs (JSON: the parent writes it, the child reads it)."""
121
+
122
+ campaign: str
123
+ entry: dict
124
+ commands: list
125
+ injection: list
126
+ terrain: str
127
+ out: str
128
+ partial: str
129
+ diag: str
130
+ error: str
131
+ attempt: int = 1
132
+ max_records: int | None = None
133
+ override_command: list | None = None
134
+ override_sigma_zero: bool = False
135
+ trace_fsi: bool = False
136
+ threshold_n: float | None = None
137
+ read_window: list | None = None
138
+ config: str | None = None
139
+ command_clip: str = "none"
140
+ torque_clip: bool = False
141
+ """Deploy ``torqueClip`` (the judge's; NRD_PLAN.md section 10: off in the collector, so the PD law tracks the
142
+ recorded action with only the per-MBD-step actuator clamp)."""
143
+ flush_every: int = FLUSH_EVERY
144
+ backend_options: dict = field(default_factory=dict)
145
+ shard_meta: dict = field(default_factory=dict)
146
+ soil_campaign: dict = field(default_factory=dict)
147
+ """CRM campaign base soil (``run --soil``); see :mod:`go2nrd.collect.chrono.soil`."""
148
+ soil_episode: dict | None = None
149
+ """This episode's soil from the run's ``--soil-map`` (the plan entry's ``soil`` is read from ``entry``)."""
150
+ policy: str | None = None
151
+ """A deploy folder of go2nrd.eval.export_onnx (``run --policy``; round_tools 2026-10-30): its ONNX instead of the
152
+ mjlab policy's, same deploy settings (:func:`go2nrd.collect.chrono.deploy.with_policy_folder`). None = default."""
153
+
154
+ def save(self, path: Path) -> None:
155
+ path.parent.mkdir(parents=True, exist_ok=True)
156
+ tmp = path.with_name(path.name + ".tmp")
157
+ tmp.write_text(json.dumps(self.__dict__))
158
+ os.replace(tmp, path)
159
+
160
+ @classmethod
161
+ def load(cls, path: Path | str) -> "EpisodeSpec":
162
+ return cls(**json.loads(Path(path).read_text()))
163
+
164
+
165
+ # ====================================================================== helpers
166
+ def category_of(terrain: str) -> str:
167
+ return "crm" if terrain == "crm" else "rigid"
168
+
169
+
170
+ def rigid_floor_size(entry: dict, commands: np.ndarray) -> float:
171
+ """Edge of the rigid ground box: covers the spawn plus an upper bound of the planned travel, with 5 m margin
172
+ (an entry key ``floor_size_m`` overrides it: tests against the evaluator's own floor)."""
173
+ if entry.get("floor_size_m"):
174
+ return float(entry["floor_size_m"])
175
+ r0 = math.hypot(entry["spawn"]["x"], entry["spawn"]["y"])
176
+ travel = float(np.hypot(commands[:, 0], commands[:, 1]).sum() * C.CONTROL_STEP_S) if len(commands) else 0.0
177
+ return max(10.0, 2.0 * (r0 + travel + 5.0))
178
+
179
+
180
+ def backend_options(terrain: str, extra: dict | None = None) -> dict:
181
+ """The evaluator's scene options; rigid: sample every 0.5 ms MBD step (physics-neutral in substep mode). CRM
182
+ without ``nvidia-smi`` (AMD / ROCm): GPU admission off unless asked for (its lock and memory poll need
183
+ ``nvidia-smi``; physics-neutral, reports/build_cluster.md section 4)."""
184
+ opts = dict(extra or {})
185
+ if terrain == "rigid":
186
+ opts.setdefault("exchange_step_s", float(opts.get("rigid_mbd_step_s", 5e-4)))
187
+ elif shutil.which("nvidia-smi") is None:
188
+ opts.setdefault("gpu_admission", False)
189
+ return opts
190
+
191
+
192
+ def episode_soil(spec: EpisodeSpec, opts: dict) -> tuple[dict, dict | None]:
193
+ """(backend options with the episode's soil, the soil record or None). CRM: the soil keys of ``opts`` become
194
+ the campaign base, the episode's values (:func:`go2nrd.collect.chrono.soil.resolve`) are passed as backend
195
+ options. Rigid: options unchanged; a soil request is noted as ignored."""
196
+ if spec.terrain != "crm":
197
+ asked = spec.entry.get("soil") or spec.soil_episode or spec.soil_campaign
198
+ return opts, (dict(ignored="rigid terrain has no soil", requested=dict(
199
+ plan=spec.entry.get("soil"), map=spec.soil_episode, campaign=spec.soil_campaign or None)) if asked else None)
200
+ rest, backend_soil = S.split_backend_options(opts)
201
+ record = S.resolve(spec.entry, spec.soil_campaign, spec.soil_episode, backend_soil)
202
+ record["defaults"] = S.evaluator_defaults()
203
+ return {**rest, **record["values"]}, record
204
+
205
+
206
+ @lru_cache(maxsize=1)
207
+ def pychrono_core_md5() -> str | None:
208
+ """md5 (16 hex) of the loaded pychrono ``_core.so`` (AMD HIP builds report ``pychrono: unknown``)."""
209
+ try:
210
+ import pychrono
211
+
212
+ path = Path(pychrono.__file__).parent / "_core.so"
213
+ h = hashlib.md5()
214
+ with open(path, "rb") as f:
215
+ for chunk in iter(lambda: f.read(1 << 22), b""):
216
+ h.update(chunk)
217
+ return h.hexdigest()[:16]
218
+ except Exception: # noqa: BLE001 - informational
219
+ return None
220
+
221
+
222
+ def canonical_build(backend: Any, soil_base: dict | None = None) -> tuple[str, dict]:
223
+ """(build id, ``params.physics()``) of ``backend`` with the URDF named by file name + sha256 instead of its path
224
+ (the cluster jobs run from per-job code snapshots, so the path differs between jobs; the evaluator does the same
225
+ for its canonical go2_irrvis URDF) and, if ``soil_base`` is given, the soil replaced by the campaign base."""
226
+ p = backend.params
227
+ q = dataclasses.replace(p, urdf=f"{Path(backend.sim.urdf.path).name} sha256 {backend.sim.urdf.sha256}")
228
+ if soil_base is not None:
229
+ q = dataclasses.replace(q, crm=dataclasses.replace(q.crm, soil=dataclasses.replace(q.crm.soil, **soil_base)))
230
+ backend.params = q
231
+ try:
232
+ return backend.build_id(), backend.params.physics()
233
+ finally:
234
+ backend.params = p
235
+
236
+
237
+ def physics_config(backend: Any, cfg: Any, terrain: str, command_clip: str, window: tuple,
238
+ soil: dict | None = None, torque_clip: bool = False) -> dict:
239
+ """Simulator settings for system.json (identical for every episode of a campaign on one build; no paths). CRM
240
+ with a soil record: ``params.crm.soil`` and ``build_id`` are the campaign base, ``soil`` says where the
241
+ per-episode values are (:func:`go2nrd.collect.chrono.soil.physics_block`)."""
242
+ from legged_sim_eval.backends.chrono_backend import pychrono_build
243
+
244
+ sim = backend.sim
245
+ build_id, phys = canonical_build(backend, soil["base"] if (soil is not None and "base" in soil) else None)
246
+ extra = dict(soil=S.physics_block(soil["base"], soil["defaults"])) if (soil is not None and "base" in soil) else {}
247
+ return dict(
248
+ simulator="Chrono (pychrono)", pychrono=pychrono_build(), pychrono_core_md5=pychrono_core_md5(),
249
+ backend=backend.name, build_id=build_id, **extra,
250
+ terrain=terrain, params=phys, robot=backend.robot_extras(), robot_mass_kg=None,
251
+ mbd_step_s=sim.mbd_dt, sample_step_s=sim.exchange_dt,
252
+ fsi_exchange_step_s=sim.exchange_dt if terrain == "crm" else None,
253
+ rigid_sample_note=("rigid: exchange_step_s = the 0.5 ms MBD step only to read every MBD step's contact "
254
+ "force; same DoStepDynamics calls as the evaluator's 2.5 ms samples") if terrain == "rigid"
255
+ else None,
256
+ surface_z_in_sim=sim.surface_z() if sim.system is not None else (0.2 if terrain == "crm" else 0.05),
257
+ deploy=dict(config_sha256=cfg.sha256, model_sha256=cfg.model_sha256, ll_dt=cfg.ll_dt,
258
+ policy_dt=float(np.float32(cfg.policy.get("policy_dt", 0.02))),
259
+ tau_max=cfg.tau_max.tolist(), torque_clip=bool(torque_clip), command_clip=command_clip,
260
+ fixstand_kp=cfg.llc.kp.tolist(), fixstand_kd=cfg.llc.kd.tolist()),
261
+ startup="task: FixStand 1 s (go2.yaml gains, quintic from the spawn pose), START in the last stand tick, "
262
+ "records from the first policy tick; probes: spawn in the air at the planned pose, policy gains "
263
+ "and policy reset at spawn (phase counter = plan phase_k0)",
264
+ injection="plan OU target noise added to the HighController target before torqueClip (motor order)",
265
+ push=("world-frame force at the base COM through a base force accumulator, set at the planned record "
266
+ "boundaries; acts 0.5 ms (one MBD step) later for exactly 0.1 s (Chrono accumulator update lag)"),
267
+ force_read_window=dict(lo=int(window[0]), hi=int(window[1]), rule="steps a+1..b <- reads a+1-lo..b-hi"),
268
+ nonfoot=("rigid: kinematic, any mjlab non-foot collision geom (base, hips, thighs, calves) below the box "
269
+ "top, or base contact force; CRM: base, hip or thigh geom below the nominal soil top in any 1.0 ms "
270
+ "exchange; both end the episode (terminal reason nonfoot_contact)"),
271
+ actuator=("PD law at every MBD step, clamped at the effort limit (23.5 / 45 N m) per step"
272
+ + ("; deploy torqueClip on the 5 ms ticks" if torque_clip else "; no deploy torqueClip")),
273
+ joint_limits=("MuJoCo default soft joint limit of the mjlab model as a one-sided torque in the PD law "
274
+ "(go2nrd.chrono_robot.limits; robot.joint_limits)" if "joint_limits" in backend.robot_extras()
275
+ else "none"),
276
+ )
277
+
278
+
279
+ def build_meta(spec: EpisodeSpec) -> dict:
280
+ e = spec.entry
281
+ keep = ("index", "shard", "shard_slot", "command_family", "long_run", "duration_s", "records", "control_steps",
282
+ "spawn", "bed", "noise", "pushes", "clearance_m", "tilt_rad", "tilt_axis_rad", "joint_offsets_rad",
283
+ "command", "phase_k0", "command_scale")
284
+ return {"plan": {k: e[k] for k in keep if k in e}, "campaign": spec.campaign}
285
+
286
+
287
+ # ====================================================================== the episode
288
+ class Recorder:
289
+ """Per-record arrays (L planned records) + per-step force reads."""
290
+
291
+ def __init__(self, L: int, crm: bool) -> None:
292
+ self.L = L
293
+ self.state = np.full((L, C.STATE_DIM), np.nan)
294
+ self.action = np.full((L, C.ACTION_DIM), np.nan)
295
+ aux = C.empty_aux(L)
296
+ self.obs, self.raw, self.command = aux["obs"], aux["raw_action"], aux["command"]
297
+ self.phase_k, self.push_force, self.nonfoot = aux["phase_k"], aux["push_force"], aux["nonfoot_contact"]
298
+ self.com = np.full((L, 6), np.nan) # base COM position (z minus surface) and velocity, world
299
+ self.feet = np.full((L, 4, 3), np.nan) # foot sphere centres (world, z minus surface)
300
+ self.tau_ff = np.full((L, 2, 12), np.nan) # torqueClip feed-forward of the record's 2 ticks (policy order)
301
+ self.t_sim = np.full(L, np.nan)
302
+ self.reads: list[np.ndarray] = [] # per step (P, 3); reads[0] = before the first step
303
+ self.step_record: list[int] = [-2] # record of each read's step (-1 = stand, -2 = before any)
304
+ self.extra: dict[str, list] = {"torque": [], "momentum": [], "t": []}
305
+ self.crm = crm
306
+ self.nonfoot_low = np.full(L, np.inf) # smallest non-foot clearance seen in the interval (m)
307
+ self.first_step_of_record = np.full(L, -1, np.int64)
308
+ self.limit_torque = np.zeros((L, 12)) # max |joint-limit torque| in the interval (policy order, N m)
309
+ self.limit_pen = np.zeros((L, 12)) # max limit penetration in the interval (rad)
310
+ self.limit_steps = np.zeros((L, 12), np.int32) # MBD steps with an active limit in the interval
311
+ self.stand_limit = None
312
+
313
+
314
+ def interval_forces(rec: Recorder, L: int, window: tuple, crm: bool) -> dict:
315
+ """Per-interval forces from the step reads (reads acting in the interval, :data:`FORCE_READ_WINDOW`):
316
+
317
+ * ``contact_force`` [L-1, 4]: CRM: the max over the reads of the NORM of the vector sum foot sphere + calf
318
+ cylinder of the leg (:data:`CRM_PAIR_RULE`; sees pull and shear, review D3); rigid: max(0, max over the reads
319
+ of the foot's world z contact force);
320
+ * CRM ``foot_force`` / ``calf_force`` [L-1, 4]: max over the reads of the force NORM of the foot sphere / calf
321
+ cylinder (per-body diagnostics; the full vectors of every read are in the diag file);
322
+ * CRM ``crm_free`` [L-1] uint8 (contract section 11): 1 iff all 8 body force norms are below
323
+ ``CRM_FREE_FORCE_N`` (1 N) in every read acting in the interval."""
324
+ reads = np.asarray(rec.reads) # [S + 1, P, 3]: reads[s] = after step s
325
+ fz = reads[..., 2]
326
+ fn = np.linalg.norm(reads, axis=-1)
327
+ pn = np.linalg.norm(reads[:, :4] + reads[:, 4:8], axis=-1) if crm else None
328
+ first = rec.first_step_of_record[:L] # steps done when record r was read
329
+ if (first[: L] < 0).any() or np.any(np.diff(first) <= 0):
330
+ raise RuntimeError("record step bookkeeping is broken")
331
+ out_pair = np.zeros((L - 1, 4))
332
+ out_foot = np.zeros((L - 1, 4))
333
+ out_calf = np.zeros((L - 1, 4))
334
+ out_free = np.zeros(L - 1, np.uint8)
335
+ for r in range(L - 1):
336
+ # the steps of interval r are first[r] + 1 .. first[r + 1]; they are driven by the reads below
337
+ idx = np.clip(np.arange(first[r] + 1 - window[0], first[r + 1] + 1 - window[1]), 0, len(fz) - 1)
338
+ if crm:
339
+ out_pair[r] = pn[idx].max(0)
340
+ out_foot[r] = fn[idx, :4].max(0)
341
+ out_calf[r] = fn[idx, 4:8].max(0)
342
+ out_free[r] = np.uint8(fn[idx, :8].max() < CRM_FREE_FORCE_N)
343
+ else:
344
+ out_pair[r] = np.maximum(fz[idx, :4].max(0), 0.0)
345
+ out: dict[str, np.ndarray] = {"contact_force": out_pair}
346
+ if crm:
347
+ out.update(foot_force=out_foot, calf_force=out_calf)
348
+ out[FREE_FLAG] = out_free
349
+ return out
350
+
351
+
352
+ def assemble(spec: EpisodeSpec, rec: Recorder, L: int, terminal: str, info: dict, window: tuple,
353
+ threshold: float) -> C.RawEpisode:
354
+ """RawEpisode of the first L records."""
355
+ e = spec.entry
356
+ crm = category_of(spec.terrain) == "crm"
357
+ forces = interval_forces(rec, L, window, crm)
358
+ cf = forces.pop("contact_force")
359
+ action = rec.action[:L].copy()
360
+ if not np.isfinite(action[L - 1]).all():
361
+ action[L - 1] = action[L - 2]
362
+ extra = {}
363
+ if getattr(rec, "per_record_extra", None): # swing_lift episodes only (swing_lift.py)
364
+ for k, v in rec.per_record_extra.items():
365
+ x = v[:L].copy()
366
+ if not np.isfinite(rec.action[L - 1]).all(): # the last record repeats the last interval's values
367
+ x[L - 1] = x[L - 2]
368
+ extra[k] = x
369
+ events = []
370
+ for p in e.get("pushes", []):
371
+ a, b = int(p["start_record"]), min(int(p["stop_record"]), L)
372
+ if a < b:
373
+ events.append([a, b])
374
+ push_force = rec.push_force[:L].copy()
375
+ push_force[L - 1] = 0.0
376
+ meta = build_meta(spec)
377
+ meta.update(info)
378
+ if crm and e.get("bed"):
379
+ meta["bed_bounds"] = e["bed"]["bounds_m"]
380
+ return C.RawEpisode(
381
+ episode_id=int(e["episode_id"]), group_id=int(e["group_id"]), seed=int(e["seed"]), family=e["family"],
382
+ category=category_of(spec.terrain), terminal_reason=terminal, state=rec.state[:L], action=action,
383
+ contacts=(cf > threshold).astype(np.uint8), contact_force=cf, obs=rec.obs[:L], raw_action=rec.raw[:L],
384
+ command=rec.command[:L], phase_k=rec.phase_k[:L], push_force=push_force,
385
+ nonfoot_contact=rec.nonfoot[:L], push_events=events, per_interval=forces, meta=meta,
386
+ **({"per_record": extra} if extra else {})).check()
387
+
388
+
389
+ def save_episode(path: Path | str, ep: C.RawEpisode, shard_meta: dict) -> None:
390
+ C.save_raw_shard(path, [ep], shard_meta)
391
+
392
+
393
+ def save_diag(path: Path | str, rec: Recorder, L: int, trace: bool) -> None:
394
+ path = Path(path)
395
+ path.parent.mkdir(parents=True, exist_ok=True)
396
+ reads = np.asarray(rec.reads, np.float32)
397
+ arrays = dict(com=rec.com[:L], feet=rec.feet[:L], tau_ff=rec.tau_ff[:L], t_sim=rec.t_sim[:L],
398
+ step_record=np.asarray(rec.step_record, np.int32), nonfoot_low=rec.nonfoot_low[:L],
399
+ first_step_of_record=rec.first_step_of_record[:L], limit_torque=rec.limit_torque[:L],
400
+ limit_pen=rec.limit_pen[:L], limit_steps=rec.limit_steps[:L])
401
+ arrays["force_z"] = reads[..., 2]
402
+ arrays["force_norm"] = np.linalg.norm(reads, axis=-1)
403
+ arrays["force"] = reads # every read's per-body vectors (CRM: 4 feet then 4 calves)
404
+ for k, v in (getattr(rec, "relief_arrays", None) or {}).items(): # terrain_relief episodes only (relief.py)
405
+ arrays[k] = v
406
+ for k, v in (getattr(rec, "lift_arrays", None) or {}).items(): # swing_lift episodes only (swing_lift.py)
407
+ arrays[k] = v[:L]
408
+ if trace:
409
+ for k, v in rec.extra.items():
410
+ if v:
411
+ arrays[k] = np.asarray(v, np.float64)
412
+ tmp = path.with_name(path.name + ".tmp.npz")
413
+ np.savez_compressed(tmp, **arrays)
414
+ os.replace(tmp, path)
415
+
416
+
417
+ def _lift_copy_last(rec: Recorder, r: int) -> None:
418
+ """swing_lift: the terminal record r (no interval of its own) repeats record r-1's offsets, like its action."""
419
+ for k, v in rec.lift_arrays.items():
420
+ v[r] = v[r - 1]
421
+ for v in rec.per_record_extra.values():
422
+ v[r] = v[r - 1]
423
+
424
+
425
+ def run_episode(spec: EpisodeSpec) -> dict:
426
+ """Run one attempt; writes spec.out (raw shard of one episode) and spec.diag; returns the summary."""
427
+ from legged_sim_eval.lowlevel import DirectCommand
428
+
429
+ from go2nrd.collect.chrono.deploy import load_policy, make_low_level_class, policy_record
430
+ from go2nrd.collect.chrono.scene import JMAP, collector_backend_class, to_motor
431
+
432
+ t_start = time.perf_counter()
433
+ e = spec.entry
434
+ terrain = spec.terrain
435
+ category = category_of(terrain)
436
+ crm = terrain == "crm"
437
+ probe = e["family"] in C.PROBE_FAMILIES
438
+ initial_velocity = probe_initial_velocity(e) # reject malformed opt-in before policy/backend/world build
439
+ window = tuple(FORCE_READ_WINDOW[category] if spec.read_window is None else spec.read_window)
440
+ threshold = float(spec.threshold_n if spec.threshold_n is not None else CONTACT_THRESHOLD_N[category])
441
+ commands = np.asarray(spec.commands, np.float32).reshape(-1, 3)
442
+ injection = np.asarray(spec.injection, np.float32).reshape(-1, 12)
443
+ if spec.override_command is not None:
444
+ commands = np.tile(np.asarray(spec.override_command, np.float32), (len(commands), 1))
445
+ if spec.override_sigma_zero:
446
+ injection = np.zeros_like(injection)
447
+ L = int(e["records"])
448
+ if spec.max_records is not None and spec.max_records < L:
449
+ L = 2 * ((int(spec.max_records) - 1) // 2) + 1
450
+ if L < 3 or (L - 1) // 2 > len(commands):
451
+ raise ValueError(f"episode {e['episode_id']}: {L} records for {len(commands)} control steps")
452
+
453
+ cfg, policy = load_policy(spec.config, spec.command_clip, spec.policy)
454
+ ll_dt = float(cfg.ll_dt)
455
+ if abs(2 * ll_dt - C.RECORD_STEP_S) > 1e-12:
456
+ raise RuntimeError(f"two low-level ticks ({2 * ll_dt}) must equal the 10ms record interval")
457
+ Backend = collector_backend_class()
458
+ opts, soil = episode_soil(spec, backend_options(terrain, spec.backend_options))
459
+ backend = Backend(terrain, pd_mode="substep", **opts)
460
+ backend.set_tick_period(ll_dt)
461
+ sim = backend.sim
462
+ n_tick = int(round(ll_dt / sim.exchange_dt))
463
+ if abs(n_tick * sim.exchange_dt - ll_dt) > 1e-12:
464
+ raise RuntimeError(f"tick {ll_dt} is not a multiple of the step {sim.exchange_dt}")
465
+
466
+ # ---------------------------------------------------------------- build
467
+ if probe:
468
+ init = probe_initial_state(e)
469
+ q_motor = to_motor(np.asarray(init["joint_pos"]))
470
+ sim.spawn_quat = np.asarray(init["quat_wxyz"], np.float64)
471
+ sim.spawn_clearance = float(init["clearance_m"])
472
+ if initial_velocity is not None:
473
+ sim.spawn_velocity_world = initial_velocity
474
+ x, y, yaw = float(init["x"]), float(init["y"]), 0.0
475
+ else:
476
+ q_motor = np.asarray(cfg.llc.fixstand_q, np.float64)
477
+ x, y, yaw = float(e["spawn"]["x"]), float(e["spawn"]["y"]), float(e["spawn"]["yaw"])
478
+ relief = None
479
+ if "terrain_relief" in e: # opt-in uneven initial CRM surface (relief.py); entries without the key: flat bed
480
+ from go2nrd.collect.chrono import relief as R
481
+
482
+ if not crm:
483
+ raise ValueError(f"episode {e['episode_id']}: terrain_relief needs CRM terrain")
484
+ relief = R.validate(e["terrain_relief"])
485
+ if relief is not None:
486
+ sim.terrain_relief = relief
487
+ sim.relief_spawn_xy = (x, y)
488
+ lift = None
489
+ if "swing_lift" in e: # opt-in swing-lift perturbation (swing_lift.py); entries without the key: unchanged
490
+ from go2nrd.collect.chrono import swing_lift as SL
491
+
492
+ if probe:
493
+ raise ValueError(f"episode {e['episode_id']}: swing_lift is for task episodes")
494
+ lift = SL.validate(e["swing_lift"])
495
+ bed = tuple(e["bed"]["patch_m"]) if (crm and e.get("bed")) else ((8.0, 4.0) if crm else None)
496
+ t0 = time.perf_counter()
497
+ build_stats = sim.build(x, y, q_motor, yaw=yaw, bed=bed, floor_size_m=rigid_floor_size(e, commands))
498
+ build_s = time.perf_counter() - t0
499
+ surface = sim.surface_z()
500
+ shard_meta = dict(spec.shard_meta)
501
+ shard_meta["soil"] = soil
502
+ shard_meta["policy"] = policy_record(cfg, spec.policy)
503
+ build_id = canonical_build(backend)[0] # this episode's build (its own soil; URDF by name + sha256)
504
+ pc = physics_config(backend, cfg, terrain, spec.command_clip, window, soil, spec.torque_clip)
505
+ pc["robot_mass_kg"] = sim.mass()
506
+ probe_every = 0
507
+ if relief is not None:
508
+ pc["terrain_relief"] = R.physics_block() # campaign-constant; the episode's own relief is in its meta
509
+ sp = relief.get("surface_probe") or {}
510
+ probe_every = int(sp.get("every_records", 0))
511
+ surf_maps, surf_index = [], []
512
+ if lift is not None:
513
+ pc["swing_lift"] = SL.physics_block() # campaign-constant; the episode's holds are in its meta
514
+ shard_meta.setdefault("physics_config", pc)
515
+ shard_meta.setdefault("contact_rule", C.contact_rule(
516
+ category, threshold,
517
+ rule=(f"pair p (leg FL/FR/RL/RR vs soil) on in record interval k if the {CRM_PAIR_RULE} exceeds threshold_n "
518
+ "in ANY force read acting inside (t_k, t_k + 10 ms]; contact_force = the largest value over those reads")
519
+ if crm else None,
520
+ component=CRM_PAIR_RULE if crm else "world z of the foot contact force, clipped at 0",
521
+ aggregation="max over the force reads acting in the interval",
522
+ step="FSI exchange 1.0 ms (2 MBD substeps)" if crm else "MBD step 0.5 ms", read_window=list(window),
523
+ read_timing=("CRM: exchange s is driven by the GetFsiBodyForce values read after exchanges s-2 and s-1 (one "
524
+ "0.5 ms MBD substep each); rigid: GetContactForce after a step is that step's force"),
525
+ diagnostics=(f"CRM foot_force / calf_force = max force norm over the same reads; {FREE_FLAG} = all 8 body "
526
+ f"norms < {CRM_FREE_FORCE_N} N in every read of the interval (contract section 11)") if crm
527
+ else None))
528
+
529
+ LowLevel = make_low_level_class()
530
+ low = LowLevel(cfg, policy, loop_cnt0=0, torque_clip=bool(spec.torque_clip))
531
+ source = DirectCommand(policy)
532
+ rec = Recorder(L, crm)
533
+ if lift is not None:
534
+ rec.per_record_extra = dict(swing_lift=np.zeros((L, 12), np.float32))
535
+ rec.lift_arrays = dict(swing_lift_offset=np.zeros((L, 12)), swing_lift_weight=np.zeros((L, 4)),
536
+ swing_lift_env=np.zeros(L), swing_lift_k=np.full(L, -1, np.int64),
537
+ injection_applied=np.zeros((L, 12)))
538
+ lift_inj = None
539
+ rec.reads.append(sim.pair_forces())
540
+ state = backend.state()
541
+ if probe:
542
+ policy.reset(state)
543
+ policy.policy_steps = int(e["phase_k0"])
544
+ low.mode = "high"
545
+ n_stand = 0
546
+ else:
547
+ low.enter_fixstand(state)
548
+ n_stand = max(1, int(round(STAND_S / ll_dt)))
549
+ inj_motor = np.zeros((len(injection), 12))
550
+ inj_motor[:, JMAP] = injection.astype(np.float64)
551
+ pushes = [(int(p["start_record"]), int(p["stop_record"]), np.asarray(p["force_n"], np.float64))
552
+ for p in e.get("pushes", [])]
553
+ bounds = e["bed"]["bounds_m"] if (crm and e.get("bed")) else None
554
+ zero3 = np.zeros(3, np.float32)
555
+ trace = bool(spec.trace_fsi)
556
+ check_every = 1 if crm else 2 # non-foot kinematics every 1 ms
557
+ steps = 0
558
+
559
+ def physics(record: int) -> None:
560
+ nonlocal steps
561
+ for j in range(n_tick):
562
+ sim.step(1)
563
+ steps += 1
564
+ rec.reads.append(sim.pair_forces())
565
+ rec.step_record.append(record)
566
+ if trace:
567
+ rec.extra["momentum"].append(sim.momentum())
568
+ rec.extra["t"].append(sim.time)
569
+ if crm:
570
+ rec.extra["torque"].append(sim.fsi_torques())
571
+ if record >= 0:
572
+ if steps % check_every == 0:
573
+ low_z = sim.nonfoot_clearance(include_calves=not crm)
574
+ rec.nonfoot_low[record] = min(rec.nonfoot_low[record], low_z)
575
+ if low_z < 0.0:
576
+ rec.nonfoot[record] = 1
577
+ if not crm and np.any(rec.reads[-1][4] != 0.0):
578
+ rec.nonfoot[record] = 1
579
+
580
+ # ---------------------------------------------------------------- stand (task episodes)
581
+ t_loop = time.perf_counter()
582
+ for k in range(n_stand):
583
+ if k > 0:
584
+ state = backend.state()
585
+ pad = source.update(zero3)
586
+ sent = low.tick(state, pad, start=(k == n_stand - 1))
587
+ backend.apply(sent.q, sent.kp, sent.kd, sent.tau)
588
+ physics(-1)
589
+ stand_wall = time.perf_counter() - t_loop
590
+ stand_lim = sim.take_limit_stats()
591
+ rec.stand_limit = dict(torque_max=float(stand_lim[0].max()), pen_max=float(stand_lim[1].max()),
592
+ steps=int(stand_lim[2].sum()))
593
+
594
+ # ---------------------------------------------------------------- records
595
+ terminal = "planned_end"
596
+ L_end = L
597
+ pending_nonfoot_endpoint = False
598
+ info: dict[str, Any] = {}
599
+ t_rec = time.perf_counter()
600
+ for r in range(L):
601
+ if r > 0 or n_stand > 0:
602
+ state = backend.state()
603
+ x37 = sim.state37()
604
+ if not np.isfinite(x37).all():
605
+ terminal, L_end = "nonfinite", r
606
+ break
607
+ rec.state[r] = x37
608
+ rec.t_sim[r] = sim.time
609
+ rec.com[r, :3] = [sim.base.GetPos().x, sim.base.GetPos().y, sim.base.GetPos().z - surface]
610
+ v = sim.base.GetPosDt()
611
+ rec.com[r, 3:] = [v.x, v.y, v.z]
612
+ fc = sim.foot_centres()
613
+ fc[:, 2] -= surface
614
+ rec.feet[r] = fc
615
+ if probe_every and r % probe_every == 0:
616
+ smap, (sx0, sy0, st) = R.surface_map(sim, float(sp["half_box_m"]), float(sp["cell_m"]))
617
+ surf_maps.append(smap)
618
+ surf_index.append((r, sx0, sy0, st))
619
+ c = r // 2
620
+ rec.command[r] = commands[min(c, len(commands) - 1)]
621
+ rec.first_step_of_record[r] = steps # reads index of the first step after record r
622
+ if pending_nonfoot_endpoint:
623
+ # The previous iteration already completed both 5ms low-level
624
+ # ticks. Read this exact grid endpoint, without another action or
625
+ # simulation step. FSI exceptions never reach this path; a
626
+ # nonfinite endpoint was rejected above and remains "nonfinite".
627
+ if r == 0 or abs(rec.t_sim[r] - rec.t_sim[r - 1] - C.RECORD_STEP_S) > 1e-8:
628
+ raise RuntimeError("nonfoot endpoint is not one completed 10ms record interval later")
629
+ rec.phase_k[r] = policy.policy_steps if r % 2 == 0 else rec.phase_k[r - 1]
630
+ rec.action[r] = rec.action[r - 1]
631
+ if lift is not None:
632
+ _lift_copy_last(rec, r)
633
+ terminal, L_end = "nonfoot_contact", r + 1
634
+ break
635
+ 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]))))
636
+ if x37[2] < C.TERMINATION["min_base_height_m"]:
637
+ terminal, L_end = "fell", r + 1
638
+ elif tilt > C.TERMINATION["max_tilt_rad"]:
639
+ terminal, L_end = "tilt", r + 1
640
+ elif bounds is not None and not (bounds[0][0] + 0.25 <= x37[0] <= bounds[1][0] - 0.25
641
+ and bounds[0][1] + 0.25 <= x37[1] <= bounds[1][1] - 0.25):
642
+ terminal, L_end = "off_bed", r + 1
643
+ if terminal != "planned_end" or r == L - 1:
644
+ rec.phase_k[r] = policy.policy_steps if r % 2 == 0 else rec.phase_k[r - 1]
645
+ if r % 2 == 1:
646
+ rec.action[r] = rec.action[r - 1]
647
+ if lift is not None and r > 0:
648
+ _lift_copy_last(rec, r)
649
+ break
650
+ if spec.flush_every and r > 0 and r % spec.flush_every == 0:
651
+ ep = assemble(spec, rec, r + 1, "fsi_abort", dict(partial=True, attempt=spec.attempt, soil=soil,
652
+ build=build_id, **({"terrain_relief": sim.relief_info}
653
+ if relief is not None else {}),
654
+ **({"swing_lift": SL.summary(lift)}
655
+ if lift is not None else {})),
656
+ window, threshold)
657
+ save_episode(spec.partial, ep, shard_meta)
658
+ _test_abort(r, spec.attempt)
659
+ # the interval [r, r + 1): two low-level ticks
660
+ push = next((f for a, b, f in pushes if a <= r < b), None)
661
+ sim.set_push(push)
662
+ if push is not None:
663
+ rec.push_force[r] = push
664
+ if lift is None:
665
+ low.injection = inj_motor[c]
666
+ else: # swing_lift: OU + lift offset, constant over control step c
667
+ if r % 2 == 0 or lift_inj is None:
668
+ k_now = int(policy.policy_steps) # the counter of this control step's observation (causal)
669
+ lo, lw, le = SL.offset(lift, k_now, rec.command[r], c)
670
+ lift_motor = np.zeros(12)
671
+ lift_motor[JMAP] = lo
672
+ lift_inj = (inj_motor[c] + lift_motor, lo, lw, le, k_now)
673
+ low.injection = lift_inj[0]
674
+ la = rec.lift_arrays
675
+ la["swing_lift_offset"][r], la["swing_lift_weight"][r] = lift_inj[1], lift_inj[2]
676
+ la["swing_lift_env"][r], la["swing_lift_k"][r] = lift_inj[3], lift_inj[4]
677
+ la["injection_applied"][r] = lift_inj[0][JMAP]
678
+ rec.per_record_extra["swing_lift"][r] = lift_inj[1]
679
+ for sub in (0, 1):
680
+ if sub == 1:
681
+ state = backend.state()
682
+ pad = source.update(rec.command[r])
683
+ sent = low.tick(state, pad)
684
+ target = sent.q[JMAP]
685
+ if sub == 0:
686
+ rec.action[r] = target
687
+ if low.policy_ran:
688
+ rec.obs[r] = policy.last_input
689
+ rec.raw[r] = policy.last_raw
690
+ rec.phase_k[r] = policy.policy_steps - 1
691
+ if lift is not None and rec.phase_k[r] != lift_inj[4]:
692
+ raise RuntimeError(f"swing_lift: phase counter {lift_inj[4]} != observed {rec.phase_k[r]}")
693
+ elif r % 2 == 0:
694
+ raise RuntimeError(f"no policy step at record {r}")
695
+ else:
696
+ rec.phase_k[r] = rec.phase_k[r - 1]
697
+ elif not np.array_equal(target, rec.action[r]):
698
+ raise RuntimeError(f"target changed inside record {r}")
699
+ rec.tau_ff[r, sub] = sent.tau[JMAP]
700
+ backend.apply(sent.q, sent.kp, sent.kd, sent.tau)
701
+ physics(r)
702
+ lt, lp, ls = sim.take_limit_stats()
703
+ rec.limit_torque[r], rec.limit_pen[r], rec.limit_steps[r] = lt[JMAP], lp[JMAP], ls[JMAP]
704
+ if rec.nonfoot[r]: # rigid and CRM (review D11)
705
+ pending_nonfoot_endpoint = True
706
+ sim.set_push(None)
707
+ loop_wall = time.perf_counter() - t_loop
708
+ rec_wall = time.perf_counter() - t_rec
709
+ if L_end < 2:
710
+ raise RuntimeError(f"episode {e['episode_id']}: only {L_end} records ({terminal})")
711
+ stats = sim.stats()
712
+ if initial_velocity is not None:
713
+ info["initial_velocity"] = dict(e["initial_velocity"],
714
+ base_angular_world_rad_s=list(initial_velocity["base_ang_vel"]),
715
+ linear_velocity_origin="base_link_REF", applied_before_record0=True)
716
+ info["study_initialization_family"] = e.get("study_initialization_family")
717
+ info.update(
718
+ terminal_capture=dict(version="finite_10ms_endpoint_v1", last_record=L_end - 1,
719
+ last_interval_nonfoot=bool(L_end > 1 and rec.nonfoot[L_end - 2]),
720
+ nonfoot_endpoint_retained=terminal == "nonfoot_contact",
721
+ note="Finite nonfoot interval endpoint retained in raw data; export may exclude the nonfoot interval."),
722
+ attempt=spec.attempt, terrain=terrain, build=build_id, soil=soil, read_window=list(window),
723
+ threshold_n=threshold,
724
+ overrides=dict(max_records=spec.max_records, command=spec.override_command,
725
+ sigma_zero=spec.override_sigma_zero) if (spec.max_records or spec.override_command
726
+ or spec.override_sigma_zero) else None,
727
+ spawn=dict(build_stats={k: v for k, v in build_stats.items() if isinstance(v, (int, float, str, list))},
728
+ probe=sim.spawn_info or None),
729
+ timing=dict(build_s=build_s, stand_wall_s=stand_wall, record_wall_s=rec_wall, loop_wall_s=loop_wall,
730
+ sim_s=sim.time, record_sim_s=(L_end - 1) * C.RECORD_STEP_S,
731
+ wall_per_sim_s=loop_wall / max(sim.time, 1e-9), steps=steps,
732
+ cfd_s=stats.get("cfd_s"), mbd_s=stats.get("mbd_s"), fsi_s=stats.get("fsi_s"),
733
+ total_s=time.perf_counter() - t_start),
734
+ gpu=stats.get("gpu"), pd_calls_per_mbd_step=stats.get("pd_calls_per_mbd_step"),
735
+ sph_particles=stats.get("sph_particles"), boundary_markers=stats.get("boundary_markers"),
736
+ rotor_violation=float(sim.rotors.violation()) if sim.rotors is not None else None,
737
+ nonfoot_records=int(rec.nonfoot[:L_end].sum()), nan_rejections=int(policy.nan_rejections),
738
+ torque_clip=bool(spec.torque_clip),
739
+ joint_limits=dict(mode=getattr(sim, "limit_params", None).mode if getattr(sim, "limit_params", None) else None,
740
+ records_active=int((rec.limit_steps[:L_end] > 0).any(1).sum()),
741
+ torque_max=float(rec.limit_torque[:L_end].max()), pen_max=float(rec.limit_pen[:L_end].max()),
742
+ stand=rec.stand_limit),
743
+ )
744
+ if relief is not None: # terrain_relief episodes only: meta block + diag arrays (relief.py)
745
+ info["terrain_relief"] = dict(sim.relief_info, surface_probe=dict(
746
+ relief.get("surface_probe") or {}, maps=len(surf_maps)) if probe_every else None)
747
+ rec.relief_arrays = {}
748
+ if sim.relief_dk is not None:
749
+ rec.relief_arrays.update(relief_dk=sim.relief_dk.astype(np.int8),
750
+ relief_lattice=np.array([sim.params.crm.spacing_m, -0.5 * bed[0], -0.5 * bed[1],
751
+ sim.params.crm.depth_m]))
752
+ if probe_every and surf_maps:
753
+ rec.relief_arrays.update(surface_maps=np.stack(surf_maps),
754
+ surface_index=np.asarray(surf_index, np.float64))
755
+ if lift is not None: # swing_lift episodes only: meta block (the per-step signal is in raw + diag)
756
+ off = rec.lift_arrays["swing_lift_offset"][:L_end]
757
+ info["swing_lift"] = dict(SL.summary(lift), records_active=int((np.abs(off).max(1) > 0).sum()),
758
+ max_calf_offset_rad=float(-off[:, 2::3].min()) if len(off) else 0.0)
759
+ ep = assemble(spec, rec, L_end, terminal, info, window, threshold)
760
+ save_diag(spec.diag, rec, L_end, trace)
761
+ save_episode(spec.out, ep, shard_meta)
762
+ backend.close()
763
+ return dict(status="ok", episode_id=int(e["episode_id"]), terminal_reason=terminal, length=L_end, **info)
764
+
765
+
766
+ def main(argv: list[str] | None = None) -> int:
767
+ argv = sys.argv[1:] if argv is None else argv
768
+ if len(argv) != 1:
769
+ print("usage: python -m go2nrd.collect.chrono.episode SPEC.json", file=sys.stderr)
770
+ return 2
771
+ spec = EpisodeSpec.load(argv[0])
772
+ try:
773
+ summary = run_episode(spec)
774
+ except Exception as exc: # noqa: BLE001 - recorded for the parent, which retries
775
+ Path(spec.error).parent.mkdir(parents=True, exist_ok=True)
776
+ Path(spec.error).write_text(json.dumps(dict(error=repr(exc), traceback=traceback.format_exc()), indent=1))
777
+ traceback.print_exc()
778
+ return 2
779
+ print(json.dumps({k: summary[k] for k in ("episode_id", "terminal_reason", "length")} | dict(
780
+ wall_per_sim_s=summary["timing"]["wall_per_sim_s"])), flush=True)
781
+ return 0
782
+
783
+
784
+ if __name__ == "__main__":
785
+ raise SystemExit(main())
go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/relief.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Uneven initial CRM soil surface (terrain relief) for the Chrono collector: opt-in, default off.
2
+
3
+ New file (lateral_stuck_20261108 crm_collection_design, 2026-11-08). Nothing here runs unless a plan entry carries a
4
+ ``terrain_relief`` block; plans without it build the flat box bed exactly as before (``CollectorGo2Sim._build_crm``
5
+ then calls the unchanged parent).
6
+
7
+ What this build of Chrono offers (Chrono f54254fa, ``ChFsiProblemCartesian::Construct`` overloads, the same commit on
8
+ the AMD HIP build, the Euler CUDA build and the local E19 copy):
9
+
10
+ * ``Construct(box_size, pos, side_flags)``: the flat bed of every earlier campaign;
11
+ * ``Construct(heightmap_file, length, width, height_range, depth, uniform_depth, pos, side_flags)``: an image
12
+ heightmap (bilinear, rounded to the particle grid);
13
+ * ``Construct(sph_file, bce_file, pos, use_grid_coordinates)``: explicit particle / boundary-marker grid points.
14
+
15
+ This module uses the third one: the SPH grid points of the flat bed (identical ``Nx = round(px / s) + 1`` x
16
+ ``Ny`` x ``Nz`` lattice and identical offset ``(-px / 2, -py / 2, 0)``), with each column's top raised or lowered by
17
+ ``dk(i, j) = round(h(x_i, y_j) / s)`` particle layers, and the boundary BCE markers of ``AddBoxContainer`` for the
18
+ sides X-, X+, Y-, Y+, Z- (``BoxSide_ALL & ~BoxSide_Z_POS``) written out point for point. The relief is forced to zero
19
+ within ``edge_taper_m`` of the bed edge (so the walls are those of the flat bed) and inside ``flat_radius_m`` of the
20
+ spawn (so the FixStand / hand-over happens on flat soil and the spawn clearance keeps its meaning).
21
+
22
+ Conventions kept: the bed bottom stays at z = 0, the NOMINAL surface stays the flat-bed top ``z = depth_m``
23
+ (``sim.surface_z()``); the 37-state z and the foot heights in the diag file stay "above the nominal surface". On a
24
+ relief bed the non-foot rule (base / hip / thigh geom in the soil ends the episode) uses the LOCAL initial top at the
25
+ geom 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 drawn
26
+ parameters and the seed are in ``RawEpisode.meta["terrain_relief"]`` and in the diag file (``relief_dk``), so an NRD
27
+ can be conditioned on it. Resolution: the particle spacing (0.02 m): reliefs are whole particle layers.
28
+
29
+ The relief h(x, y) (world metres) = clip((GRF + sum of features) * spawn_mask * edge_mask, -max_abs, max_abs):
30
+
31
+ * GRF: ``modes`` random cosine modes, |k| = 2 pi / wavelength * exp(N(0, 0.25^2)), uniform direction and phase,
32
+ scaled to ``rms_m``; drawn at run time from PCG64(SeedSequence([seed, 0x5E1EF])) in a fixed order;
33
+ * features (explicit in the plan): ``mound`` / ``dip`` Gaussian bumps (height_m signed, sigma_m) and ``berm``
34
+ ridges (height_m, width_m = Gaussian sigma across, length_m, angle_rad of the ridge axis, Gaussian end caps);
35
+ * masks: smoothstep from 0 at the spawn radius to 1 at radius + blend; exactly 0 within 0.15 m of the bed edge,
36
+ then a smoothstep to 1 over edge_taper_m.
37
+
38
+ Optional ``surface_probe`` ({"every_records", "half_box_m", "cell_m"}): the local surface (highest SPH particle per
39
+ cell, minus the nominal surface) around the base, read between steps (physics-neutral reads of particle positions);
40
+ saved in the diag file (``surface_*``) to measure sand pushed into piles. Allowed on flat ("rms 0, no features")
41
+ relief blocks as well; a flat block builds with the unchanged box ``Construct``.
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import hashlib
47
+ import inspect
48
+ import math
49
+ import os
50
+ import shutil
51
+ import tempfile
52
+ import time
53
+ from typing import Any
54
+
55
+ import numpy as np
56
+
57
+ RELIEF_SCHEMA = "go2nrd_crm_relief_v1"
58
+ GRF_SALT = 0x5E1EF
59
+ LEGACY_BUILD_SHA256 = "e9c63d098a3b017211f5e4dbf731c1ccefd20f56bf865972bb09e370acc05821"
60
+ """sha256 of ``inspect.getsource(go2nrd.chrono_robot.build._build_crm_legacy_calf)`` that :func:`build_crm_relief`
61
+ follows call for call (only the Construct call and the bounding-box check differ); checked at every relief build."""
62
+ SPEC_KEYS = {"schema", "seed", "grf", "features", "flat_radius_m", "flat_blend_m", "edge_taper_m", "max_abs_m"}
63
+ OPTIONAL_KEYS = {"grid_sha256", "surface_probe", "note", "draw"}
64
+ FEATURE_KEYS = {"mound": {"kind", "x", "y", "height_m", "sigma_m"},
65
+ "dip": {"kind", "x", "y", "height_m", "sigma_m"},
66
+ "berm": {"kind", "x", "y", "height_m", "width_m", "length_m", "angle_rad"}}
67
+ PROBE_KEYS = {"every_records", "half_box_m", "cell_m"}
68
+ EDGE_ZERO_M = 0.15
69
+ """The relief is exactly zero within this distance of the bed edge (then a smoothstep over edge_taper_m)."""
70
+
71
+
72
+ # ====================================================================== spec
73
+ def validate(spec: dict | None) -> dict | None:
74
+ """Strict schema check of a plan entry's ``terrain_relief`` block (absent / None = flat bed, legacy)."""
75
+ if spec is None:
76
+ return None
77
+ if not isinstance(spec, dict) or spec.get("schema") != RELIEF_SCHEMA:
78
+ raise ValueError(f"terrain_relief must use schema {RELIEF_SCHEMA}")
79
+ keys = set(spec)
80
+ if not SPEC_KEYS <= keys or keys - SPEC_KEYS - OPTIONAL_KEYS:
81
+ raise ValueError(f"terrain_relief keys {sorted(keys)}; need {sorted(SPEC_KEYS)} (+ {sorted(OPTIONAL_KEYS)})")
82
+ grf = spec["grf"]
83
+ if set(grf) != {"rms_m", "wavelength_m", "modes"} or grf["rms_m"] < 0 or grf["wavelength_m"] <= 0 \
84
+ or int(grf["modes"]) < 1:
85
+ raise ValueError(f"terrain_relief.grf needs rms_m >= 0, wavelength_m > 0, modes >= 1: {grf}")
86
+ for f in spec["features"]:
87
+ want = FEATURE_KEYS.get(f.get("kind"))
88
+ if want is None or set(f) != want:
89
+ raise ValueError(f"terrain_relief feature {f}: kind mound|dip|berm with keys {want}")
90
+ positive = f["kind"] in ("mound", "berm")
91
+ if (positive and not float(f["height_m"]) > 0) or (not positive and not float(f["height_m"]) < 0):
92
+ raise ValueError(f"terrain_relief feature {f}: mound / berm height > 0, dip height < 0")
93
+ for k in ("flat_radius_m", "flat_blend_m", "edge_taper_m", "max_abs_m"):
94
+ if not (math.isfinite(float(spec[k])) and float(spec[k]) >= 0):
95
+ raise ValueError(f"terrain_relief.{k} must be finite and >= 0")
96
+ if float(spec["edge_taper_m"]) < 0.2:
97
+ raise ValueError("terrain_relief.edge_taper_m >= 0.2 m (the walls must stay those of the flat bed)")
98
+ probe = spec.get("surface_probe")
99
+ if probe is not None and (set(probe) != PROBE_KEYS or int(probe["every_records"]) < 1
100
+ or not 0 < float(probe["cell_m"]) <= float(probe["half_box_m"])):
101
+ raise ValueError(f"terrain_relief.surface_probe needs {sorted(PROBE_KEYS)}: {probe}")
102
+ return spec
103
+
104
+
105
+ def is_flat(spec: dict) -> bool:
106
+ return float(spec["grf"]["rms_m"]) == 0.0 and not spec["features"]
107
+
108
+
109
+ def physics_block() -> dict:
110
+ """``physics_config["terrain_relief"]`` (identical for every episode of a campaign whose entries carry a block)."""
111
+ return dict(schema=RELIEF_SCHEMA, construct=(
112
+ "ChFsiProblemCartesian::Construct(sph_file, bce_file, (-px/2, -py/2, 0), grid) with the flat-bed lattice and "
113
+ "column tops shifted by dk = round(h / spacing) layers; AddBoxContainer walls/bottom written point for point; "
114
+ "flat blocks use the unchanged box Construct"),
115
+ nominal_surface="z = depth_m (flat-bed top); state z and diag foot z stay relative to it",
116
+ nonfoot_rule=("relief beds: base / hip / thigh lowest point below the LOCAL initial soil top (nominal + dk * "
117
+ "spacing at the geom centre) in any 1 ms exchange ends the episode; flat blocks: nominal top"),
118
+ per_episode="RawEpisode.meta['terrain_relief'] (spec, seed, dk sha256, layer stats); diag relief_dk, surface_*")
119
+
120
+
121
+ # ====================================================================== the height field
122
+ def _smoothstep(t: np.ndarray) -> np.ndarray:
123
+ t = np.clip(t, 0.0, 1.0)
124
+ return t * t * (3.0 - 2.0 * t)
125
+
126
+
127
+ def grf_modes(spec: dict) -> np.ndarray:
128
+ """(M, 4) [kx, ky, phase, 1] of the GRF (fixed draw order: |k| factors, directions, phases)."""
129
+ g = spec["grf"]
130
+ m = int(g["modes"])
131
+ rng = np.random.Generator(np.random.PCG64(np.random.SeedSequence([int(spec["seed"]) % (1 << 64), GRF_SALT])))
132
+ kmag = 2.0 * math.pi / float(g["wavelength_m"]) * np.exp(0.25 * rng.standard_normal(m))
133
+ theta = rng.uniform(0.0, 2.0 * math.pi, m)
134
+ phase = rng.uniform(0.0, 2.0 * math.pi, m)
135
+ return np.stack([kmag * np.cos(theta), kmag * np.sin(theta), phase, np.ones(m)], 1)
136
+
137
+
138
+ def height(spec: dict, X: np.ndarray, Y: np.ndarray, bed: tuple[float, float], spawn: tuple[float, float]) -> np.ndarray:
139
+ """h(x, y) in metres at world points (X, Y) of a bed (px, py) centred on the origin, spawn (x, y)."""
140
+ X = np.asarray(X, np.float64)
141
+ Y = np.asarray(Y, np.float64)
142
+ h = np.zeros(np.broadcast(X, Y).shape)
143
+ rms = float(spec["grf"]["rms_m"])
144
+ if rms > 0:
145
+ modes = grf_modes(spec)
146
+ acc = np.zeros_like(h)
147
+ for kx, ky, ph, _ in modes: # fixed order: reproducible sums
148
+ acc += np.cos(kx * X + ky * Y + ph)
149
+ h += rms * math.sqrt(2.0 / len(modes)) * acc
150
+ for f in spec["features"]:
151
+ dx, dy = X - float(f["x"]), Y - float(f["y"])
152
+ if f["kind"] in ("mound", "dip"):
153
+ s = float(f["sigma_m"])
154
+ h += float(f["height_m"]) * np.exp(-0.5 * (dx * dx + dy * dy) / (s * s))
155
+ else:
156
+ a, w, half = float(f["angle_rad"]), float(f["width_m"]), 0.5 * float(f["length_m"])
157
+ u = dx * math.cos(a) + dy * math.sin(a)
158
+ v = -dx * math.sin(a) + dy * math.cos(a)
159
+ over = np.maximum(np.abs(u) - half, 0.0)
160
+ h += float(f["height_m"]) * np.exp(-0.5 * (v * v + over * over) / (w * w))
161
+ r = np.hypot(X - spawn[0], Y - spawn[1])
162
+ blend = max(float(spec["flat_blend_m"]), 1e-9)
163
+ h *= _smoothstep((r - float(spec["flat_radius_m"])) / blend)
164
+ px, py = bed
165
+ edge = np.minimum(np.minimum(X + 0.5 * px, 0.5 * px - X), np.minimum(Y + 0.5 * py, 0.5 * py - Y))
166
+ h *= _smoothstep((edge - EDGE_ZERO_M) / float(spec["edge_taper_m"])) # exactly 0 in the outer 0.15 m
167
+ lim = float(spec["max_abs_m"])
168
+ return np.clip(h, -lim, lim)
169
+
170
+
171
+ def lattice(px: float, py: float, depth: float, spacing: float) -> dict:
172
+ """The flat-bed lattice of ``ChFsiProblemCartesian::Construct(box)`` (std::round of positive values)."""
173
+ rnd = lambda v: int(math.floor(v + 0.5)) # noqa: E731
174
+ nx, ny, nz = rnd(px / spacing) + 1, rnd(py / spacing) + 1, rnd(depth / spacing) + 1
175
+ return dict(nx=nx, ny=ny, nz=nz, spacing=float(spacing), offset=(-0.5 * px, -0.5 * py, 0.0))
176
+
177
+
178
+ def layer_grid(spec: dict, px: float, py: float, depth: float, spacing: float,
179
+ spawn: tuple[float, float]) -> tuple[np.ndarray, dict]:
180
+ """dk [nx, ny] int16 (particle layers added (> 0) / removed (< 0) at each lattice column) and the lattice."""
181
+ lat = lattice(px, py, depth, spacing)
182
+ xs = spacing * np.arange(lat["nx"]) + lat["offset"][0]
183
+ ys = spacing * np.arange(lat["ny"]) + lat["offset"][1]
184
+ X, Y = np.meshgrid(xs, ys, indexing="ij")
185
+ dk = np.rint(height(spec, X, Y, (px, py), spawn) / spacing).astype(np.int16)
186
+ if dk.min() <= -(lat["nz"] - 3):
187
+ raise ValueError(f"terrain_relief: a dip removes {int(-dk.min())} of {lat['nz']} layers")
188
+ ring = max(2, int(math.ceil(0.1 / spacing)))
189
+ border = np.ones_like(dk, bool)
190
+ border[ring:-ring, ring:-ring] = False
191
+ if np.any(dk[border] != 0):
192
+ raise ValueError("terrain_relief: non-zero relief within 0.1 m of the bed edge (walls would not fit)")
193
+ return dk, lat
194
+
195
+
196
+ def grid_sha256(dk: np.ndarray) -> str:
197
+ a = np.ascontiguousarray(dk, np.int16)
198
+ return hashlib.sha256(str(a.shape).encode() + a.tobytes()).hexdigest()
199
+
200
+
201
+ # ====================================================================== marker files
202
+ def sph_points(dk: np.ndarray, nz: int) -> np.ndarray:
203
+ """(N, 3) int32 lattice points: column (i, j) holds k = 0 .. nz - 1 + dk[i, j]."""
204
+ nx, ny = dk.shape
205
+ counts = (nz + dk.astype(np.int64)).ravel()
206
+ ii, jj = np.meshgrid(np.arange(nx), np.arange(ny), indexing="ij")
207
+ i = np.repeat(ii.ravel(), counts)
208
+ j = np.repeat(jj.ravel(), counts)
209
+ starts = np.repeat(np.cumsum(counts) - counts, counts)
210
+ k = np.arange(int(counts.sum())) - starts
211
+ return np.stack([i, j, k], 1).astype(np.int32)
212
+
213
+
214
+ def box_bce_points(nx: int, ny: int, nz: int, layers: int) -> np.ndarray:
215
+ """(M, 3) int32 unique BCE points of ``AddBoxContainer`` with X-, X+, Y-, Y+, Z- (point for point)."""
216
+ L = int(layers)
217
+ parts = []
218
+ I, J, K = np.meshgrid(np.arange(nx), np.arange(ny), np.arange(-L, 0), indexing="ij") # z_neg
219
+ parts.append(np.stack([I, J, K], -1).reshape(-1, 3))
220
+ kz = np.arange(-L, nz + L)
221
+ for ix in (np.arange(-L, 0), nx - 1 - np.arange(-L, 0)): # x_neg, x_pos
222
+ I, J, K = np.meshgrid(ix, np.arange(ny), kz, indexing="ij")
223
+ parts.append(np.stack([I, J, K], -1).reshape(-1, 3))
224
+ for iy in (np.arange(-L, 0), ny - 1 - np.arange(-L, 0)): # y_neg, y_pos
225
+ I, J, K = np.meshgrid(np.arange(-L, nx + L), iy, kz, indexing="ij")
226
+ parts.append(np.stack([I, J, K], -1).reshape(-1, 3))
227
+ return np.unique(np.concatenate(parts).astype(np.int32), axis=0)
228
+
229
+
230
+ def _write_lines(path: str, pts: np.ndarray) -> int:
231
+ """Write integer triples as fixed-width text lines ('%7d%7d%7d\\n', vectorised); returns bytes written."""
232
+ pts = np.asarray(pts, np.int64)
233
+ if pts.size and (pts.min() <= -10 ** 5 or pts.max() >= 10 ** 6):
234
+ raise ValueError("lattice index out of the fixed-width range")
235
+ w = 7
236
+ n = len(pts)
237
+ out = np.full((n, 3 * w + 1), ord(" "), np.uint8)
238
+ out[:, -1] = ord("\n")
239
+ for c in range(3):
240
+ v = pts[:, c]
241
+ a = np.abs(v)
242
+ ndig = 1 + sum((a >= 10 ** d).astype(np.int64) for d in range(1, 6))
243
+ for d in range(6): # digit d from the right
244
+ col = (c + 1) * w - 1 - d
245
+ digit = (a // 10 ** d) % 10
246
+ on = d < ndig
247
+ out[on, col] = (ord("0") + digit[on]).astype(np.uint8)
248
+ neg = v < 0
249
+ out[neg, (c + 1) * w - 1 - ndig[neg]] = ord("-")
250
+ with open(path, "wb") as fh:
251
+ fh.write(out.tobytes())
252
+ return int(out.size)
253
+
254
+
255
+ # ====================================================================== the CRM build
256
+ def build_crm_relief(sim: Any, system: Any, bodies: Any, px: float, py: float, spec: dict) -> Any:
257
+ """``go2nrd.chrono_robot.build._build_crm_legacy_calf`` with the relief Construct (see the module docstring).
258
+
259
+ Call for call the same as the pinned source (:data:`LEGACY_BUILD_SHA256`) except: the SPH / BCE lattice comes
260
+ from files written here, and the bounding-box check allows the relief's highest column. A flat block (rms 0, no
261
+ features) must not come here (the scene uses the unchanged box build)."""
262
+ import pychrono.fsi as fsi
263
+ import pychrono.vehicle as veh
264
+
265
+ from go2nrd.chrono_robot import build as B
266
+ from legged_sim_eval.backends.chrono_backend import CALF_BODIES, FOOT_BODIES, BackendError, crm_api
267
+
268
+ got = hashlib.sha256(inspect.getsource(B._build_crm_legacy_calf).encode()).hexdigest()
269
+ if got != LEGACY_BUILD_SHA256:
270
+ raise RuntimeError(f"_build_crm_legacy_calf changed ({got}); re-check build_crm_relief against it")
271
+ if not sim.legacy_calf_fsi:
272
+ raise RuntimeError("terrain_relief needs legacy_calf_fsi (the collector default)")
273
+ t0 = time.perf_counter()
274
+ ch, c = sim.chrono, sim.params.crm
275
+ spawn = tuple(getattr(sim, "relief_spawn_xy", (0.0, 0.0)))
276
+ dk, lat = layer_grid(spec, px, py, c.depth_m, c.spacing_m, spawn)
277
+ sha = grid_sha256(dk)
278
+ # plan-time sha256 of the same grid: a mismatch (different code / numpy / libm) is recorded, not fatal; the
279
+ # grid that was actually built is saved in the diag file (relief_dk) and its sha256 in the episode meta
280
+ sha_match = None if not spec.get("grid_sha256") else bool(spec["grid_sha256"] == sha)
281
+
282
+ names = crm_api(fsi, veh)
283
+ terrain = veh.CRMTerrain(system, c.spacing_m)
284
+ terrain.SetVerbose(False)
285
+ terrain.SetGravitationalAcceleration(system.GetGravitationalAcceleration())
286
+ terrain.SetStepSizeCFD(c.cfd_step_s)
287
+ soil = getattr(fsi, names["soil_properties"])()
288
+ soil.density = c.soil.density
289
+ soil.Young_modulus = c.soil.young_modulus_pa
290
+ soil.Poisson_ratio = c.soil.poisson_ratio
291
+ soil.mu_I0 = c.soil.mu_i0
292
+ soil.mu_fric_s = c.soil.friction
293
+ soil.mu_fric_2 = c.soil.friction
294
+ soil.average_diam = c.soil.average_diam_m
295
+ soil.cohesion_coeff = c.soil.cohesion_pa
296
+ getattr(terrain, names["set_soil"])(soil)
297
+ sph = fsi.SPHParameters()
298
+ sph.integration_scheme = getattr(fsi, f"IntegrationScheme_{c.integration}")
299
+ sph.initial_spacing = c.spacing_m
300
+ sph.d0_multiplier = c.d0_multiplier
301
+ sph.free_surface_threshold = c.free_surface_threshold
302
+ sph.artificial_viscosity = c.artificial_viscosity
303
+ sph.shifting_method = fsi.ShiftingMethod_NONE
304
+ sph.viscosity_method = fsi.ViscosityMethod_ARTIFICIAL_BILATERAL
305
+ sph.boundary_method = fsi.BoundaryMethod_ADAMI
306
+ terrain.SetSPHParameters(sph)
307
+ foot = ch.ChBodyGeometry()
308
+ foot.coll_spheres.append(ch.SphereShape(ch.VNULL, c.foot_radius_m))
309
+ pairs = [(name, foot) for name in FOOT_BODIES]
310
+ if c.calf_fsi:
311
+ offsets = B.calf_fsi_offsets(sim.urdf.path)
312
+ sim.calf_fsi_centres = {}
313
+ for name in CALF_BODIES:
314
+ off = offsets[name.split("_")[0]]
315
+ calf = ch.ChBodyGeometry()
316
+ calf.coll_cylinders.append(
317
+ ch.CylinderShape(ch.ChVector3d(*off), ch.QUNIT, c.calf_radius_m, c.calf_length_m)
318
+ )
319
+ sim.calf_fsi_centres[name] = off
320
+ pairs.append((name, calf))
321
+ for name, geometry in pairs:
322
+ terrain.AddRigidBody(bodies[name], geometry, False)
323
+ if c.active_domain_m is not None:
324
+ d = float(c.active_domain_m)
325
+ terrain.SetActiveDomain(ch.ChVector3d(d, d, d))
326
+ getattr(terrain, names["set_active_domain_delay"])(c.active_domain_delay_s)
327
+ # ---- the one replaced call: the relief lattice instead of Construct(box, origin, ALL & ~Z_POS)
328
+ layers = int(terrain.GetFluidSystemSPH().GetNumBCELayers())
329
+ sph_pts = sph_points(dk, lat["nz"])
330
+ bce_pts = box_bce_points(lat["nx"], lat["ny"], lat["nz"], layers)
331
+ work = tempfile.mkdtemp(prefix="crm_relief_")
332
+ try:
333
+ f_sph, f_bce = os.path.join(work, "sph.txt"), os.path.join(work, "bce.txt")
334
+ nbytes = _write_lines(f_sph, sph_pts) + _write_lines(f_bce, bce_pts)
335
+ t_files = time.perf_counter() - t0
336
+ terrain.Construct(f_sph, f_bce, ch.ChVector3d(-0.5 * px, -0.5 * py, 0.0), True)
337
+ finally:
338
+ shutil.rmtree(work, ignore_errors=True)
339
+ # ---- unchanged
340
+ fluid = terrain.GetFluidSystemSPH()
341
+ if hasattr(fluid, "EnableCudaErrorCheck"):
342
+ fluid.EnableCudaErrorCheck(bool(c.cuda_error_check))
343
+ if c.output_level is not None and hasattr(terrain, "SetOutputLevel"):
344
+ terrain.SetOutputLevel(getattr(fsi, f"OutputLevel_{c.output_level}"))
345
+ terrain.Initialize()
346
+ box = terrain.GetSPHBoundingBox()
347
+ top = c.depth_m + c.spacing_m * max(0, int(dk.max()))
348
+ want = (-0.5 * px, -0.5 * py, 0.0, 0.5 * px, 0.5 * py, top) # relief: the highest column's top
349
+ found = (box.min.x, box.min.y, box.min.z, box.max.x, box.max.y, box.max.z)
350
+ if any(abs(a - b) > 2.0 * c.spacing_m for a, b in zip(want, found, strict=True)):
351
+ raise BackendError(f"the CRM relief bed is not where it was asked for: {found} vs {want}")
352
+ mbd = terrain.GetFsiSystemSPH().GetStepSizeMBD()
353
+ if abs(mbd - sim.mbd_dt) > 1e-12:
354
+ raise BackendError(f"CRM MBD step is {mbd}, expected {sim.mbd_dt}")
355
+ n_sph = int(terrain.GetNumSPHParticles())
356
+ if n_sph != len(sph_pts):
357
+ raise BackendError(f"CRM relief: {n_sph} SPH particles built, {len(sph_pts)} written")
358
+ flat_n = lat["nx"] * lat["ny"] * lat["nz"]
359
+ sim.relief_dk = dk
360
+ sim.relief_origin = (lat["offset"][0], lat["offset"][1], float(c.spacing_m)) # non-foot rule: local surface
361
+ sim.relief_info = dict(
362
+ spec=spec, grid_sha256=sha, grid_sha256_matches_plan=sha_match, lattice=dict(lat, offset=list(lat["offset"])), bce_layers=layers,
363
+ layers_added=int(dk[dk > 0].sum()), layers_removed=int(-dk[dk < 0].sum()),
364
+ dk_min=int(dk.min()), dk_max=int(dk.max()), columns_raised=int((dk > 0).sum()),
365
+ columns_lowered=int((dk < 0).sum()), relief_rms_m=float(c.spacing_m * np.sqrt(np.mean(dk.astype(float) ** 2))),
366
+ sph_particles=n_sph, flat_bed_particles=int(flat_n), bce_markers=int(terrain.GetNumBoundaryBCEMarkers()),
367
+ bce_written=int(len(bce_pts)), file_bytes=nbytes, files_s=t_files, build_s=time.perf_counter() - t0,
368
+ spawn_xy=list(spawn), sph_bbox=list(found), construct="sph_bce_files")
369
+ return terrain
370
+
371
+
372
+ # ====================================================================== surface probe
373
+ def surface_map(sim: Any, half_box: float, cell: float) -> tuple[np.ndarray, tuple[float, float, float]]:
374
+ """(G, G) float16 highest particle centre per cell minus the nominal surface (NaN = no particle) around the
375
+ base COM (x, y), and (x0, y0, t) of the map's lower-left corner and the sim time. Read only."""
376
+ pos = sim.particles(half_box)
377
+ base = sim.base.GetPos()
378
+ x0, y0 = float(base.x) - half_box, float(base.y) - half_box
379
+ g = int(round(2 * half_box / cell))
380
+ out = np.full(g * g, -np.inf)
381
+ if len(pos):
382
+ ix = np.clip(((pos[:, 0] - x0) / cell).astype(np.int64), 0, g - 1)
383
+ iy = np.clip(((pos[:, 1] - y0) / cell).astype(np.int64), 0, g - 1)
384
+ np.maximum.at(out, ix * g + iy, pos[:, 2] - sim.surface_z())
385
+ out[~np.isfinite(out)] = np.nan
386
+ return out.reshape(g, g).astype(np.float16), (x0, y0, float(sim.time))
go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/run.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chrono collection of one plan shard: resumable per episode, one subprocess per episode attempt.
2
+
3
+ New file (go2nrd Chrono collector builder, 2026-10-29). The isolation / retry idea follows legged_sim_eval
4
+ ``runner.py`` (``--isolate``, ``--attempts``; ``/home/harry/go2_sand/legged_rl_deploy/sim_eval``, read-only); the code
5
+ is new.
6
+
7
+ python -B -m go2nrd.collect.chrono.run --campaign crm_prod --shard 3 --out /scratch/.../collect/crm_prod
8
+ [--episodes 0:10 | --episodes 2] [--terrain crm|rigid] [--attempts 3] [--max-seconds 8]
9
+ [--episode-ids 11000016,11000021] [--trace-fsi] [--threshold-n 5] [--no-isolate] ...
10
+ [--soil cohesion_pa=1000 --soil friction=1.0] [--soil-map map.json] [--torque-clip on]
11
+ [--backend-opt joint_limits=off] [--policy DEPLOY_FOLDER]
12
+
13
+ Physics of the collector (fix_chrono, 2026-10-30): torqueClip off unless ``--torque-clip on`` (the PD law's
14
+ per-MBD-step actuator clamp stays); the robot's MuJoCo soft joint limits (``go2nrd.chrono_robot.limits``; backend
15
+ option ``joint_limits=mujoco|mujoco_pd|off``).
16
+
17
+ Policy (round_tools, 2026-10-30): ``--policy FOLDER`` (a deploy folder of go2nrd.eval.export_onnx, e.g. a PPO
18
+ fine-tune of the mjlab actor) replaces the mjlab policy's ONNX; the deploy settings stay those of ``--config`` /
19
+ ``--command-clip`` (go2nrd.collect.chrono.deploy.with_policy_folder; the folder's config.yaml must agree with them).
20
+ Absent: the mjlab policy, as before. Every raw shard meta has a ``policy`` block (ONNX file, sha256, default flag,
21
+ folder, exported checkpoint); every marker has ``policy_sha256``. A shard directory whose markers name another policy
22
+ is refused (``--allow-mixed-policy`` overrides; markers without the key count as the default policy).
23
+
24
+ CRM soil (go2nrd.collect.chrono.soil): ``--soil KEY=VALUE`` sets the campaign base (keys cohesion_pa, friction =
25
+ mu_s = mu_2, density, young_modulus_pa; defaults = the evaluator's soil); the plan entry's ``soil`` dict and the
26
+ ``--soil-map`` JSON (``{"episodes": {"<id>": {...}}}``, e.g. from ``python -m go2nrd.collect.chrono.soil make-map``)
27
+ set per-episode values. Each episode's values are in its RawEpisode meta, its raw shard meta and its marker.
28
+
29
+ Outputs (all below ``OUT/shard_<SSS>/``, so the cluster templates sync only this shard's paths):
30
+
31
+ * ``ep_<episode_id>.npz`` -- a raw shard (``contract.save_raw_shard``) holding that one episode: the export reads
32
+ ``--raw OUT/shard_000 OUT/shard_001 ...`` (it globs ``*.npz`` in each directory, not below);
33
+ * ``ep_<episode_id>.json`` -- the commit marker: status ``ok`` | ``fsi_abort`` | ``failed``, attempts, timing. An
34
+ episode with a marker is skipped on a rerun (``--retry-failed`` reruns ``failed`` ones);
35
+ * ``diag/ep_<id>.npz`` -- per-step force reads (z of the 8 FSI bodies / 4 feet + base), COM, feet, torqueClip
36
+ feed-forward (``--trace-fsi``: full force vectors, FSI torques, robot momentum per step);
37
+ * ``partial/``, ``work/``, ``logs/`` -- attempt files (partials are flushed every 100 records by the child).
38
+
39
+ Attempts: a child that exits 0 with its output is a success. A child that dies otherwise (CUDA / FSI abort, signal,
40
+ or a Python error) is retried up to ``--attempts`` times. If every attempt failed and at least one died with
41
+ records flushed, the longest partial becomes the episode with ``terminal_reason = fsi_abort`` (the records before
42
+ the abort kept); else the marker says ``failed``. Exit 0 = every selected episode has a marker; 143 = SIGTERM (the
43
+ running child is stopped; its episode reruns from the start next time); 1 = a parent error; ``--strict``: 3 if any
44
+ episode ended ``failed``.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import argparse
50
+ import hashlib
51
+ import json
52
+ import os
53
+ import signal
54
+ import socket
55
+ import subprocess
56
+ import sys
57
+ import time
58
+ from pathlib import Path
59
+
60
+ import numpy as np
61
+
62
+ from go2nrd.collect.chrono import soil as S
63
+ from go2nrd.collect.common import contract as C
64
+ from go2nrd.collect.common.plan import PlanArrays, load_plan
65
+ from go2nrd.collect.chrono.episode import (COLLECTOR_NAME, COLLECTOR_VERSION, EpisodeSpec, category_of,
66
+ run_episode)
67
+
68
+ HERE = Path(__file__).resolve().parent
69
+ DONE = ("ok", "fsi_abort", "failed")
70
+ _STOP = {"flag": False, "child": None}
71
+
72
+
73
+ def code_sha256() -> str:
74
+ h = hashlib.sha256()
75
+ for p in sorted(HERE.glob("*.py")):
76
+ h.update(p.name.encode())
77
+ h.update(p.read_bytes())
78
+ return h.hexdigest()
79
+
80
+
81
+ def _on_term(signum, frame): # noqa: ARG001
82
+ _STOP["flag"] = True
83
+ child = _STOP["child"]
84
+ if child is not None and child.poll() is None:
85
+ child.terminate()
86
+
87
+
88
+ def select(plan: dict, shard: int, episodes: str | None, ids: str | None) -> list[dict]:
89
+ if ids:
90
+ want = [int(v) for v in ids.split(",") if v.strip()]
91
+ by_id = {e["episode_id"]: e for e in plan["episodes"]}
92
+ return [by_id[i] for i in want]
93
+ rows = sorted((e for e in plan["episodes"] if e["shard"] == shard), key=lambda e: e["shard_slot"])
94
+ if not episodes:
95
+ return rows
96
+ if ":" in episodes:
97
+ a, b = episodes.split(":")
98
+ return rows[int(a or 0):int(b) if b else None]
99
+ return rows[: int(episodes)]
100
+
101
+
102
+ def write_json(path: Path, obj: dict) -> None:
103
+ path.parent.mkdir(parents=True, exist_ok=True)
104
+ tmp = path.with_name(path.name + ".tmp")
105
+ tmp.write_text(json.dumps(obj, indent=1, allow_nan=True, default=str))
106
+ os.replace(tmp, path)
107
+
108
+
109
+ def _partial_length(path: Path) -> int:
110
+ try:
111
+ with np.load(path) as f:
112
+ return int(f["rec_offsets"][-1])
113
+ except Exception: # noqa: BLE001 - a missing / unreadable partial counts as none
114
+ return 0
115
+
116
+
117
+ def run_one(entry: dict, arrays: dict, args: argparse.Namespace, shard_dir: Path, shard_meta: dict) -> dict:
118
+ eid = int(entry["episode_id"])
119
+ final = shard_dir / f"ep_{eid}.npz"
120
+ marker = shard_dir / f"ep_{eid}.json"
121
+ attempts = []
122
+ t0 = time.time()
123
+ for k in range(1, args.attempts + 1):
124
+ spec = EpisodeSpec(
125
+ campaign=args.campaign, entry=entry, commands=np.asarray(arrays["commands"]).tolist(),
126
+ injection=np.asarray(arrays["injection"]).tolist(), terrain=args.terrain, out=str(final),
127
+ partial=str(shard_dir / "partial" / f"ep_{eid}.a{k}.npz"), diag=str(shard_dir / "diag" / f"ep_{eid}.npz"),
128
+ error=str(shard_dir / "work" / f"ep_{eid}.a{k}.error.json"), attempt=k,
129
+ max_records=(int(round(args.max_seconds / C.RECORD_STEP_S)) + 1) if args.max_seconds else None,
130
+ override_command=[float(v) for v in args.override_command.split(",")] if args.override_command else None,
131
+ override_sigma_zero=bool(args.sigma_zero), trace_fsi=bool(args.trace_fsi), threshold_n=args.threshold_n,
132
+ read_window=args.read_window, config=args.config, command_clip=args.command_clip,
133
+ torque_clip=args.torque_clip == "on", flush_every=args.flush_every,
134
+ backend_options=dict(args.backend_opt), shard_meta=shard_meta, soil_campaign=dict(args.soil),
135
+ soil_episode=args.soil_map.get(eid), policy=args.policy)
136
+ spec_path = shard_dir / "work" / f"ep_{eid}.a{k}.spec.json"
137
+ for stale in (Path(spec.error), Path(spec.partial), final): # leftovers of a stopped earlier run
138
+ stale.unlink(missing_ok=True)
139
+ spec.save(spec_path)
140
+ log = shard_dir / "logs" / f"ep_{eid}.a{k}.log"
141
+ log.parent.mkdir(parents=True, exist_ok=True)
142
+ ta = time.time()
143
+ if args.no_isolate:
144
+ try:
145
+ run_episode(spec)
146
+ rc = 0
147
+ except Exception as exc: # noqa: BLE001
148
+ Path(spec.error).write_text(json.dumps(dict(error=repr(exc))))
149
+ rc = 2
150
+ else:
151
+ env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1")
152
+ with open(log, "w") as fh:
153
+ child = subprocess.Popen([args.python, "-B", "-m", "go2nrd.collect.chrono.episode", str(spec_path)],
154
+ stdout=fh, stderr=subprocess.STDOUT, env=env, cwd=str(shard_dir))
155
+ _STOP["child"] = child
156
+ rc = child.wait()
157
+ _STOP["child"] = None
158
+ if _STOP["flag"]:
159
+ return dict(status="stopped", episode_id=eid)
160
+ err = Path(spec.error)
161
+ kind = "ok" if (rc == 0 and final.exists()) else ("error" if err.exists() else "abort")
162
+ rec = dict(attempt=k, rc=rc, kind=kind, wall_s=time.time() - ta, log=str(log),
163
+ partial_records=_partial_length(Path(spec.partial)) if kind == "abort" else 0)
164
+ if err.exists():
165
+ rec["error"] = json.loads(err.read_text()).get("error")
166
+ attempts.append(rec)
167
+ print(f"[ep {eid}] attempt {k}: {kind} rc={rc} {rec['wall_s']:.1f} s"
168
+ + (f" ({rec.get('error')})" if kind == "error" else ""), flush=True)
169
+ if kind == "ok":
170
+ with np.load(final) as f:
171
+ head = json.loads(str(f["episodes_json"]))[0]
172
+ soil = head["meta"].get("soil") or {}
173
+ out = dict(status="ok", episode_id=eid, family=entry["family"], terminal_reason=head["terminal_reason"],
174
+ length=head["length"], attempts=attempts, wall_s=time.time() - t0, host=socket.gethostname(),
175
+ timing=head["meta"].get("timing"), build=head["meta"].get("build"),
176
+ soil=soil.get("values"), soil_source=soil.get("source"), policy_sha256=args.policy_sha256)
177
+ write_json(marker, out)
178
+ for p in (shard_dir / "partial").glob(f"ep_{eid}.a*.npz"):
179
+ p.unlink()
180
+ return out
181
+ aborts = [a for a in attempts if a["kind"] == "abort" and a["partial_records"] >= 2]
182
+ if aborts:
183
+ best = max(aborts, key=lambda a: a["partial_records"])
184
+ part = shard_dir / "partial" / f"ep_{eid}.a{best['attempt']}.npz"
185
+ eps, meta = C.load_raw_shard(part)
186
+ ep = eps[0]
187
+ ep.terminal_reason = "fsi_abort"
188
+ ep.meta.update(partial=False, fsi_abort=dict(attempts=attempts, kept_attempt=best["attempt"]))
189
+ C.save_raw_shard(final, [ep], meta)
190
+ soil = ep.meta.get("soil") or {}
191
+ out = dict(status="fsi_abort", episode_id=eid, family=entry["family"], terminal_reason="fsi_abort",
192
+ length=ep.length, attempts=attempts, wall_s=time.time() - t0, host=socket.gethostname(),
193
+ soil=soil.get("values"), soil_source=soil.get("source"), policy_sha256=args.policy_sha256)
194
+ else:
195
+ out = dict(status="failed", episode_id=eid, family=entry["family"], attempts=attempts,
196
+ wall_s=time.time() - t0, host=socket.gethostname(), policy_sha256=args.policy_sha256)
197
+ write_json(marker, out)
198
+ return out
199
+
200
+
201
+ def run_policy_sha256(args: argparse.Namespace) -> str | None:
202
+ """sha256 of this run's policy ONNX (the --policy folder's, or the default config's model; None if the default
203
+ model cannot be resolved here, e.g. without legged_sim_eval). Also sets args.default_policy_sha256."""
204
+ from go2nrd.collect.chrono.deploy import CONFIG_NAMES, policy_dir, resolve_policy_folder
205
+
206
+ args.default_policy_sha256 = None
207
+ try:
208
+ from legged_sim_eval.config import load_deploy_config
209
+
210
+ base = load_deploy_config(Path(args.config) if args.config else policy_dir() / CONFIG_NAMES[args.command_clip])
211
+ args.default_policy_sha256 = base.model_sha256 or None
212
+ except Exception: # noqa: BLE001 - informational in the parent; the child loads it for real
213
+ pass
214
+ if args.policy:
215
+ return resolve_policy_folder(args.policy)["sha256"] # raises on a folder that is not a deploy folder
216
+ return args.default_policy_sha256
217
+
218
+
219
+ def marker_policies(shard_dir: Path, sha: str | None, default_sha: str | None) -> list[str]:
220
+ """Policy sha256 of the existing markers of shard_dir that differ from sha (markers without policy_sha256 were
221
+ written before the --policy option: the default policy)."""
222
+ if sha is None or not shard_dir.exists():
223
+ return []
224
+ seen = set()
225
+ for m in shard_dir.glob("ep_*.json"):
226
+ try:
227
+ got = json.loads(m.read_text()).get("policy_sha256", default_sha)
228
+ except (OSError, json.JSONDecodeError):
229
+ continue
230
+ if got is not None and got != sha:
231
+ seen.add(got)
232
+ return sorted(seen)
233
+
234
+
235
+ def parse_backend_opt(items: list[str]) -> list[tuple[str, object]]:
236
+ out = []
237
+ for item in items:
238
+ key, _, value = item.partition("=")
239
+ try:
240
+ v: object = json.loads(value)
241
+ except json.JSONDecodeError:
242
+ v = value
243
+ out.append((key, v))
244
+ return out
245
+
246
+
247
+ def main(argv: list[str] | None = None) -> int:
248
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
249
+ ap.add_argument("--campaign", required=True, help="campaign name or plan JSON path")
250
+ ap.add_argument("--shard", type=int, default=0)
251
+ ap.add_argument("--episodes", help="slot range i:j of the shard, or a count N (= 0:N)")
252
+ ap.add_argument("--episode-ids", help="comma-separated episode ids (overrides --shard selection)")
253
+ ap.add_argument("--terrain", choices=("crm", "rigid"), help="default: the plan's category")
254
+ ap.add_argument("--out", type=Path, required=True)
255
+ ap.add_argument("--attempts", type=int, default=3)
256
+ ap.add_argument("--max-seconds", type=float, help="truncate episodes (smoke tests / pilots)")
257
+ ap.add_argument("--override-command", help="vx,vy,wz for every control step (pilot: standing still)")
258
+ ap.add_argument("--sigma-zero", action="store_true", help="no OU injection (pilot)")
259
+ ap.add_argument("--trace-fsi", action="store_true", help="diag: full per-step force vectors, torques, momentum")
260
+ ap.add_argument("--threshold-n", type=float, help="label threshold (default: episode.CONTACT_THRESHOLD_N)")
261
+ ap.add_argument("--read-window", type=lambda v: [int(x) for x in v.split(",")], metavar="LO,HI",
262
+ help="force read window (default: episode.FORCE_READ_WINDOW, CRM 2,1, rigid 0,0)")
263
+ ap.add_argument("--config", help="deploy config (default: config_noclip.yaml, see deploy.py)")
264
+ ap.add_argument("--policy", help="deploy folder of go2nrd.eval.export_onnx (its ONNX replaces the mjlab policy's)")
265
+ ap.add_argument("--allow-mixed-policy", action="store_true",
266
+ help="run into a shard directory whose markers name another policy")
267
+ ap.add_argument("--command-clip", choices=("none", "deploy"), default="none")
268
+ ap.add_argument("--torque-clip", choices=("off", "on"), default="off",
269
+ help="deploy torqueClip (default off: NRD_PLAN.md section 10; the judge path keeps it on)")
270
+ ap.add_argument("--flush-every", type=int, default=100)
271
+ ap.add_argument("--backend-opt", action="append", default=[], metavar="KEY=VALUE")
272
+ ap.add_argument("--soil", action="append", default=[], metavar="KEY=VALUE",
273
+ help="CRM campaign base soil: cohesion_pa, friction (= mu_s = mu_2), density, young_modulus_pa")
274
+ ap.add_argument("--soil-map", type=Path, help='per-episode soil JSON {"episodes": {"<id>": {"cohesion_pa": ...}}}')
275
+ ap.add_argument("--no-isolate", action="store_true", help="run episodes in this process (rigid smoke tests)")
276
+ ap.add_argument("--retry-failed", action="store_true")
277
+ ap.add_argument("--strict", action="store_true")
278
+ ap.add_argument("--python", default=sys.executable)
279
+ args = ap.parse_args(argv)
280
+ args.backend_opt = parse_backend_opt(args.backend_opt)
281
+ args.soil = S.normalize(dict(parse_backend_opt(args.soil)), "--soil")
282
+ soil_map_path = args.soil_map
283
+ args.soil_map, soil_map_sha = S.load_map(soil_map_path)
284
+
285
+ signal.signal(signal.SIGTERM, _on_term)
286
+ plan = load_plan(args.campaign)
287
+ given = Path(args.campaign)
288
+ side = given.parent / f"{plan['campaign']}_arrays.npz" if given.suffix == ".json" else None
289
+ plan_dir = given.parent if (side is not None and side.exists()) else None # arrays next to a plan JSON path
290
+ args.campaign = plan["campaign"]
291
+ args.terrain = args.terrain or plan["category"]
292
+ rows = select(plan, args.shard, args.episodes, args.episode_ids)
293
+ if not rows:
294
+ print(f"no episodes in shard {args.shard} of {args.campaign}", file=sys.stderr)
295
+ return 1
296
+ shard_dir = args.out / f"shard_{args.shard:03d}"
297
+ args.policy = str(Path(args.policy).resolve()) if args.policy else None
298
+ args.policy_sha256 = run_policy_sha256(args)
299
+ mixed = marker_policies(shard_dir, args.policy_sha256, args.default_policy_sha256)
300
+ if mixed and not args.allow_mixed_policy:
301
+ print(f"{shard_dir}: markers of other policies {mixed}; this run's policy is {args.policy_sha256} "
302
+ f"({args.policy or 'default'}). Use another --out or --allow-mixed-policy", file=sys.stderr)
303
+ return 1
304
+ print(f"policy {args.policy or 'default (mjlab policy)'} sha256 {str(args.policy_sha256)[:16]}...", flush=True)
305
+ shard_dir.mkdir(parents=True, exist_ok=True)
306
+ shard_meta = dict(campaign=args.campaign, category=category_of(args.terrain),
307
+ collector=dict(name=COLLECTOR_NAME, version=COLLECTOR_VERSION, code_sha256=code_sha256()))
308
+ if soil_map_path:
309
+ shard_meta["soil_map"] = dict(file=Path(soil_map_path).name, sha256=soil_map_sha)
310
+ if args.terrain == "crm": # fail before any GPU time on a bad soil key / value / plan-map conflict
311
+ backend_soil = S.split_backend_options(dict(args.backend_opt))[1]
312
+ for entry in rows:
313
+ S.resolve(entry, args.soil, args.soil_map.get(int(entry["episode_id"])), backend_soil)
314
+ arrays = PlanArrays(plan) if plan_dir is None else PlanArrays(plan, plan_dir=plan_dir)
315
+ summary_path = shard_dir / "shard.json"
316
+ results = []
317
+ t0 = time.time()
318
+ print(f"{args.campaign} shard {args.shard}: {len(rows)} episodes, terrain {args.terrain}, out {shard_dir}",
319
+ flush=True)
320
+ for entry in rows:
321
+ eid = int(entry["episode_id"])
322
+ marker = shard_dir / f"ep_{eid}.json"
323
+ if marker.exists():
324
+ prev = json.loads(marker.read_text())
325
+ if prev.get("status") in DONE and not (args.retry_failed and prev.get("status") == "failed"):
326
+ results.append(prev)
327
+ continue
328
+ out = run_one(entry, arrays(eid), args, shard_dir, shard_meta)
329
+ if out["status"] == "stopped":
330
+ print(f"SIGTERM: stopped at episode {eid}", flush=True)
331
+ return 143
332
+ results.append(out)
333
+ print(f"[ep {eid}] {out['status']} {out.get('terminal_reason', '')} length {out.get('length')} "
334
+ f"({out['wall_s']:.1f} s)", flush=True)
335
+ write_json(summary_path, dict(campaign=args.campaign, shard=args.shard, terrain=args.terrain,
336
+ selected=len(rows), done=len(results), wall_s=time.time() - t0,
337
+ status={s: sum(r.get("status") == s for r in results) for s in DONE},
338
+ complete=False))
339
+ if _STOP["flag"]:
340
+ return 143
341
+ status = {s: sum(r.get("status") == s for r in results) for s in DONE}
342
+ write_json(summary_path, dict(campaign=args.campaign, shard=args.shard, terrain=args.terrain, selected=len(rows),
343
+ done=len(results), wall_s=time.time() - t0, status=status, complete=True))
344
+ print(f"shard {args.shard} complete: {status}", flush=True)
345
+ return 3 if (args.strict and status["failed"]) else 0
346
+
347
+
348
+ if __name__ == "__main__":
349
+ raise SystemExit(main())
go2_sand_finetune/code/browse/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75/src/go2nrd/collect/chrono/swing_lift.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Structured SWING-LIFT perturbation of the teacher's joint targets (lateral_stuck_20261108, opt-in, default off).
2
+
3
+ New file (lateral_stuck_20261108 track A, 2026-11-08). A plan entry with a ``swing_lift`` block makes the Chrono
4
+ collector (:mod:`go2nrd.collect.chrono.episode`) add, at every control step, an offset to the HighController joint
5
+ target of each leg that is in its SWING phase. The offset folds the leg (extra calf flexion and some thigh
6
+ flexion), so the commanded foot rises. It is added next to the plan's OU target noise (``InjectingLowLevel.injection``,
7
+ motor order), before ``torqueClip`` and the float32 LowCmd rounding, so the recorded ``action`` (the target the PD law
8
+ gets) contains it. Entries without the key run exactly as before (no new arrays, no new meta keys).
9
+
10
+ Swing detection (causal, no future information): the teacher's own gait clock. The mjlab actor observes the phase
11
+ ``[sin, cos](2 pi gp)``, ``gp = fmod(k * 0.02, 0.6) / 0.6`` with ``k`` = the policy step counter of the observation
12
+ (legged_sim_eval ``DeployPolicy._gait_phase``; zero when ``||command|| < 0.1``, then the teacher stands). The leg
13
+ schedule of the trained teacher was measured on the exports rigid_prod_v2 and crm_prod
14
+ (``studies/lateral_stuck_20261108/collect/phase_calibration.json``): a trot, FR + RL off the ground for
15
+ gp 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 in
16
+ swing for ``s = ((gp - LEG_PHASE_OFFSET[j] - swing_start) mod 1) / swing_length`` in [0, 1); the bump is
17
+ ``sin(pi s)^2`` (zero at lift-off and touch-down, peak in mid swing). The default window starts 0.03 earlier than the
18
+ measured lift-off (PD lag of about one control step), so the commanded peak (gp 0.23 / 0.73) leads the natural apex.
19
+
20
+ Offset of leg j at control step c (policy joint order FL FR RL RR x hip thigh calf, rad)::
21
+
22
+ 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)
23
+ thigh += thigh_per_calf * a ; calf -= a (hip unchanged)
24
+
25
+ ``thigh_per_calf`` = 0.5 keeps the foot's x unchanged at the default pose (go2nrd.policy.fk: calf -0.2 rad and
26
+ thigh +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 over
27
+ the control step (both 5 ms ticks of each of its two records), like the OU injection.
28
+
29
+ Block schema (``SWING_LIFT_SCHEMA``)::
30
+
31
+ {"schema": "go2nrd_swing_lift_v1", "holds": [{"start_step": a, "end_step": b, "amp_rad": A}, ...],
32
+ "swing_start": 0.0, "swing_length": 0.46, "thigh_per_calf": 0.5, "ramp_s": 0.3, ...}
33
+
34
+ ``holds`` are control-step ranges [a, b) (20 ms steps of the plan's command grid); an empty list = a control episode
35
+ that carries the block (same physics_config) and gets no offset.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import math
41
+
42
+ import numpy as np
43
+
44
+ SWING_LIFT_SCHEMA = "go2nrd_swing_lift_v1"
45
+ PERIOD_S = 0.6
46
+ STEP_DT = 0.02
47
+ COMMAND_THRESHOLD = 0.1
48
+ LEG_PHASE_OFFSET = (0.5, 0.0, 0.0, 0.5)
49
+ """Phase offset of FL, FR, RL, RR (policy order): FR + RL swing first (gp 0.03-0.50), FL + RR half a period later."""
50
+ DEFAULTS = dict(swing_start=0.0, swing_length=0.46, thigh_per_calf=0.5, ramp_s=0.3)
51
+ MAX_AMP_RAD = 0.5
52
+
53
+
54
+ def validate(block: dict) -> dict:
55
+ """The normalised block (defaults filled in); raises ValueError on a malformed one."""
56
+ if not isinstance(block, dict) or block.get("schema") != SWING_LIFT_SCHEMA:
57
+ raise ValueError(f"swing_lift: schema must be {SWING_LIFT_SCHEMA!r}")
58
+ out = dict(DEFAULTS)
59
+ out.update(block)
60
+ for k in DEFAULTS:
61
+ out[k] = float(out[k])
62
+ if not (0.05 <= out["swing_length"] <= 1.0) or not (0.0 <= out["swing_start"] < 1.0):
63
+ raise ValueError("swing_lift: swing_start in [0, 1), swing_length in [0.05, 1]")
64
+ if not (0.0 <= out["thigh_per_calf"] <= 2.0) or out["ramp_s"] < 0.0:
65
+ raise ValueError("swing_lift: thigh_per_calf in [0, 2], ramp_s >= 0")
66
+ holds = []
67
+ last = -1
68
+ for h in out.get("holds", []):
69
+ a, b, amp = int(h["start_step"]), int(h["end_step"]), float(h["amp_rad"])
70
+ if a < 0 or b <= a or a < last or not (0.0 <= amp <= MAX_AMP_RAD):
71
+ raise ValueError(f"swing_lift: bad hold {h} (ordered, non-overlapping, 0 <= amp <= {MAX_AMP_RAD})")
72
+ holds.append(dict(h, start_step=a, end_step=b, amp_rad=amp))
73
+ last = b
74
+ out["holds"] = holds
75
+ return out
76
+
77
+
78
+ def envelope(block: dict, c: int) -> float:
79
+ """Amplitude (rad) at control step c: the active hold's amp times a smooth (0.5 - 0.5 cos) ramp of ramp_s at
80
+ both ends of the hold; 0 outside the holds."""
81
+ n = max(1, int(round(block["ramp_s"] / STEP_DT)))
82
+ for h in block["holds"]:
83
+ a, b = h["start_step"], h["end_step"]
84
+ if a <= c < b:
85
+ u = min(1.0, (c - a + 0.5) / n, (b - c - 0.5) / n)
86
+ return float(h["amp_rad"]) * (0.5 - 0.5 * math.cos(math.pi * max(0.0, u)))
87
+ return 0.0
88
+
89
+
90
+ def gait_phase(k: int) -> float:
91
+ """gp of the policy observation with step counter k (``DeployPolicy._gait_phase``, double)."""
92
+ return math.fmod(int(k) * STEP_DT, PERIOD_S) / PERIOD_S
93
+
94
+
95
+ def leg_weights(block: dict, k: int) -> np.ndarray:
96
+ """[4] swing bump sin(pi s)^2 of FL FR RL RR at policy step k (0 in stance)."""
97
+ gp = gait_phase(k)
98
+ w = np.zeros(4)
99
+ for j, off in enumerate(LEG_PHASE_OFFSET):
100
+ s = ((gp - off - block["swing_start"]) % 1.0) / block["swing_length"]
101
+ if 0.0 <= s < 1.0:
102
+ w[j] = math.sin(math.pi * s) ** 2
103
+ return w
104
+
105
+
106
+ def moving(command) -> bool:
107
+ """The policy's phase gate: ||command|| >= 0.1 (norm accumulated in double from the float32 components)."""
108
+ sq = 0.0
109
+ for v in np.asarray(command, np.float32).reshape(-1)[:3]:
110
+ sq += float(v) * float(v)
111
+ return math.sqrt(sq) >= COMMAND_THRESHOLD
112
+
113
+
114
+ def offset(block: dict, k: int, command, c: int) -> tuple[np.ndarray, np.ndarray, float]:
115
+ """(offset [12] policy order rad, leg weights [4], envelope rad) at control step c, policy step counter k."""
116
+ out = np.zeros(12)
117
+ env = envelope(block, c) if moving(command) else 0.0
118
+ if env == 0.0:
119
+ return out, np.zeros(4), 0.0
120
+ w = leg_weights(block, k)
121
+ for j in range(4):
122
+ a = env * w[j]
123
+ out[3 * j + 1] = block["thigh_per_calf"] * a
124
+ out[3 * j + 2] = -a
125
+ return out, w, env
126
+
127
+
128
+ def recompute(block: dict, phase_k: np.ndarray, command: np.ndarray) -> np.ndarray:
129
+ """[L, 12] offsets of a recorded episode from its raw ``phase_k`` and ``command`` (audit of the diag/raw arrays;
130
+ record r belongs to control step r // 2, whose offset was computed at its even record; the terminal record L-1
131
+ has no interval of its own and repeats record L-2, like its action)."""
132
+ block = validate(block)
133
+ L = len(phase_k)
134
+ out = np.zeros((L, 12))
135
+ for r in range(0, L, 2):
136
+ out[r] = offset(block, int(phase_k[r]), command[r], r // 2)[0]
137
+ if r + 1 < L:
138
+ out[r + 1] = out[r]
139
+ if L >= 2:
140
+ out[L - 1] = out[L - 2]
141
+ return out
142
+
143
+
144
+ def physics_block() -> dict:
145
+ """Campaign-constant physics_config entry of collections whose entries carry a swing_lift block."""
146
+ return dict(schema=SWING_LIFT_SCHEMA, module="go2nrd.collect.chrono.swing_lift",
147
+ rule=("per control step, if ||command|| >= 0.1 and a plan hold is active: leg j in swing (teacher gait "
148
+ "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, "
149
+ "swing_start + swing_length)) gets calf -= A ramp sin(pi s)^2 and thigh += thigh_per_calf * that; "
150
+ "added to the HighController target with the OU injection, before torqueClip and float32 LowCmd; "
151
+ "recorded action contains it"),
152
+ leg_phase_offset=list(LEG_PHASE_OFFSET), period_s=PERIOD_S, command_threshold=COMMAND_THRESHOLD,
153
+ raw_per_record="swing_lift [L, 12] policy order (rad)",
154
+ diag=["swing_lift_offset", "swing_lift_weight", "swing_lift_env", "swing_lift_k", "injection_applied"])
155
+
156
+
157
+ def summary(block: dict) -> dict:
158
+ """Meta block of an episode."""
159
+ return dict(schema=block["schema"], holds=block["holds"], swing_start=block["swing_start"],
160
+ swing_length=block["swing_length"], thigh_per_calf=block["thigh_per_calf"], ramp_s=block["ramp_s"],
161
+ episode_lift=bool(block.get("episode_lift", bool(block["holds"]))))
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/cluster/train_amd.sbatch ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # lateral_stuck_20261108 nrd_v3: one NRD training arm on one AMD MI350X (mi3501x, 4 h cap; resumable chain).
3
+ # sbatch [-t HH:MM:SS] [--dependency=afterany:JOB] train_amd.sbatch CODE MODE RUNCFG SEED LABEL LIMIT_S [STOP_AT]
4
+ # Env recipe: module pytorch/2.10.0 (ROCm) + venvs/go2nrd, python3.12, PYTHONPATH appended (cluster/amd/common.sh).
5
+ # Output (resumable): /work1/dannegrut/harry/lateral_stuck_20261108/nrd_v3/runs/LABEL
6
+ #SBATCH -J lsn3-nrd
7
+ #SBATCH -A dannegrut
8
+ #SBATCH -p mi3501x
9
+ #SBATCH -N 1
10
+ #SBATCH -t 04:00:00
11
+ #SBATCH --signal=B:USR1@300
12
+ #SBATCH -o /work1/dannegrut/harry/lateral_stuck_20261108/nrd_v3/logs/%x_%j.out
13
+ set -o pipefail
14
+ CODE=${1:?capsule}; MODE=${2:?mode}; RUNCFG=${3:?run config name}; SEED=${4:?seed}; LABEL=${5:?label}
15
+ LIMIT=${6:-13200}; STOPAT=${7:-0}
16
+ ROOT=/work1/dannegrut/harry/lateral_stuck_20261108/nrd_v3
17
+ OUT=$ROOT/runs/$LABEL
18
+ mkdir -p "$OUT" "$ROOT/logs"
19
+ [ ! -f "$ROOT/STOP" ] || { echo "remote STOP present"; exit 0; }
20
+ [ ! -f "$OUT/complete.json" ] || { echo "$LABEL already complete"; exit 0; }
21
+ [ ! -f "$OUT/failure.json" ] || { echo "$LABEL has failure.json; review before retry"; exit 4; }
22
+ source /etc/profile
23
+ module load pytorch/2.10.0 >/dev/null 2>&1 || { echo "module pytorch/2.10.0 failed"; exit 1; }
24
+ source /work1/dannegrut/harry/venvs/go2nrd/bin/activate
25
+ export PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
26
+ python3.12 -B - "$OUT/gpu_preflight_${SLURM_JOB_ID}.json" <<'PY'
27
+ import json, os, pathlib, platform, sys, torch
28
+ assert torch.cuda.is_available()
29
+ x = torch.tensor([2.], device='cuda', requires_grad=True); (x * x).sum().backward(); torch.cuda.synchronize()
30
+ assert float(x.grad.item()) == 4.
31
+ a = torch.randn(256, 256, device='cuda', dtype=torch.float64)
32
+ assert torch.allclose((a @ a).cpu(), a.cpu() @ a.cpu(), atol=1e-9)
33
+ r = dict(job_id=os.environ.get('SLURM_JOB_ID'), host=platform.node(), torch=torch.__version__,
34
+ hip=getattr(torch.version, 'hip', None), device=torch.cuda.get_device_name(0))
35
+ pathlib.Path(sys.argv[1]).write_text(json.dumps(r, indent=2) + '\n'); print(json.dumps(r), flush=True)
36
+ PY
37
+ [ $? = 0 ] || exit 3
38
+ ARGS=(--mode "$MODE" --run-config "$CODE/nrd_v3/configs/$RUNCFG" --source-root "$CODE/src"
39
+ --pins "$CODE/nrd_v3/reference/pins.json" --recipe "$CODE/nrd_v3/reference/full_config.json"
40
+ --data-root "$ROOT/data/root" --output "$OUT" --seed "$SEED" --device cuda --max-wall-seconds "$LIMIT"
41
+ --stop-at-update "$STOPAT" --short-module "$CODE/nrd_v3/reference/short_support.py")
42
+ case "$MODE" in
43
+ parity-*) ARGS+=(--manifest "$CODE/manifests/splits.json") ;;
44
+ *) ARGS+=(--manifest "$CODE/manifests/splits_lateral_v2.json") ;;
45
+ esac
46
+ case "$MODE" in
47
+ cont) ARGS+=(--parent-resume "$ROOT/parents/ref_h50_s61_u13500/resume.pt" --parent-endpoint "$ROOT/parents/ref_h50_s61_u13500/last.pt") ;;
48
+ esac
49
+ printf '%s\n' "$SLURM_JOB_ID $(hostname) $CODE $MODE $RUNCFG $SEED $LABEL $LIMIT $STOPAT $(date -u +%FT%TZ)" >> "$OUT/jobs.txt"
50
+ CHILD=
51
+ trap '[ -z "$CHILD" ] || kill -USR1 "$CHILD" 2>/dev/null || true' USR1 TERM
52
+ cd "$ROOT"
53
+ python3.12 -B "$CODE/nrd_v3/nrd_v3_train.py" "${ARGS[@]}" > "$OUT/train_${SLURM_JOB_ID}.log" 2>&1 &
54
+ CHILD=$!
55
+ (while sleep 60; do [ ! -f "$ROOT/STOP" ] || kill -USR1 "$CHILD" 2>/dev/null || true; kill -0 "$CHILD" 2>/dev/null || exit 0; done) &
56
+ WATCH=$!
57
+ wait "$CHILD"; RC=$?
58
+ if kill -0 "$CHILD" 2>/dev/null; then wait "$CHILD"; RC=$?; fi
59
+ kill "$WATCH" 2>/dev/null
60
+ printf '{"job_id":"%s","trainer_exit":%s,"host":"%s","mode":"%s","seed":%s,"label":"%s","code":"%s","end":"%s"}\n' \
61
+ "$SLURM_JOB_ID" "$RC" "$(hostname)" "$MODE" "$SEED" "$LABEL" "$CODE" "$(date -u +%FT%TZ)" > "$OUT/job_${SLURM_JOB_ID}.json"
62
+ tail -3 "$OUT/train_${SLURM_JOB_ID}.log"
63
+ exit "$RC"
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/configs/fresh_lat_v2.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "arm": "mixed_plus_lat_v2",
3
+ "budget": "matched",
4
+ "val_arm": "mixed",
5
+ "extra_val_arm": "lat_v2",
6
+ "domain_tree": {
7
+ "rigid": [
8
+ 0.5,
9
+ [
10
+ "rigid"
11
+ ]
12
+ ],
13
+ "crm_half": [
14
+ 0.5,
15
+ {
16
+ "crm_prod": [
17
+ 0.5,
18
+ [
19
+ "crm"
20
+ ]
21
+ ],
22
+ "lat_v2": [
23
+ 0.5,
24
+ [
25
+ "crm_lat_v2_hip",
26
+ "crm_lat_v2_cuda"
27
+ ]
28
+ ]
29
+ }
30
+ ]
31
+ },
32
+ "crm_domains": [
33
+ "crm",
34
+ "crm_lat_v2_hip",
35
+ "crm_lat_v2_cuda"
36
+ ],
37
+ "short": {
38
+ "lean_batch": 2,
39
+ "stall_batch": 2,
40
+ "stall_domains": [
41
+ "crm_lat_v2_hip",
42
+ "crm_lat_v2_cuda"
43
+ ],
44
+ "lean_weight": 0.25,
45
+ "stall_weight": 0.25
46
+ },
47
+ "forbidden_directories": [
48
+ "lateral_stuck_20261108_crm_v2_test_hip"
49
+ ],
50
+ "teacher_onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45",
51
+ "kind": "fresh",
52
+ "schedule": "reference A(12000)+B(1000)+C(500)=13500"
53
+ }
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/nrd_v3_train.py ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """nrd_v3 trainer: the reference seed61 H50 u13500 frame+short recipe, new lateral data (lateral_stuck_20261108).
2
+
3
+ One resumable process covers the whole reference schedule with the FROZEN reference code (yaw_correction_v1 src,
4
+ digest 924630...; pinned file hashes are checked before any go2nrd import):
5
+
6
+ stage A updates 1..12000 go2nrd.fixed_base.train_three loop (core 1000, collision 1000, joint 10000 =
7
+ 8000 one-step + 2000 rollout, horizon 10->50, cosine LR 3e-4 -> 3e-5, warmups 200/20)
8
+ stage B updates 12001..13000 frame_short_factorial_v1 'short': H50 rollout from H50-eligible starts + short lean
9
+ auxiliary (2 branches H1..5, weight 0.25), constant LR 3e-5 (fresh short RNG seed+5000)
10
+ stage C updates 13001..13500 horizon100_pilot_v1 'h50': H50 loss from H100-eligible starts + the same auxiliary
11
+ stage D (mode cont) stage-C objective continued from a parent endpoint for --cont-updates updates
12
+
13
+ Modes: fresh (A->B->C from scratch), cont (D from --parent-resume), parity-A / parity-B / parity-C (original
14
+ data, original uniform domain balance and the ORIGINAL ShortCrossingSampler; used only to prove the launcher).
15
+ New-data runs use the samplers.py WeightedWindowSampler (domain tree) and LeanStallShortSampler (adds a
16
+ 'short_stall' term: 2 lateral STALL branches, weight 0.25). Normalization: fresh refits train-only stats on the
17
+ training mixture (frozen initialize_from_train); cont keeps the parent's buffers and scales.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import copy
23
+ import hashlib
24
+ import importlib
25
+ import json
26
+ import math
27
+ import os
28
+ from pathlib import Path
29
+ import shutil
30
+ import signal
31
+ import sys
32
+ import time
33
+ import traceback
34
+
35
+ import numpy as np
36
+ import torch
37
+ from torch.nn import functional as F
38
+
39
+ HERE = Path(__file__).resolve().parent
40
+ STAGE_END = {"A": 12000, "B": 13000, "C": 13500}
41
+
42
+
43
+ def sha(path):
44
+ h = hashlib.sha256()
45
+ with Path(path).open("rb") as f:
46
+ for block in iter(lambda: f.read(8 << 20), b""):
47
+ h.update(block)
48
+ return h.hexdigest()
49
+
50
+
51
+ def digest(value):
52
+ """Same portable semantic hash as the reference continuation drivers."""
53
+ h = hashlib.sha256()
54
+
55
+ def visit(v):
56
+ if torch.is_tensor(v):
57
+ a = v.detach().cpu().contiguous()
58
+ h.update(f"tensor:{a.dtype}:{tuple(a.shape)}:".encode())
59
+ h.update(a.numpy().tobytes())
60
+ elif isinstance(v, dict):
61
+ h.update(b"dict:")
62
+ for k in sorted(v, key=lambda x: (type(x).__name__, str(x))):
63
+ visit(k)
64
+ visit(v[k])
65
+ elif isinstance(v, (list, tuple)):
66
+ h.update(type(v).__name__.encode())
67
+ for x in v:
68
+ visit(x)
69
+ elif isinstance(v, np.ndarray):
70
+ h.update(f"array:{v.dtype}:{v.shape}:".encode())
71
+ h.update(v.tobytes())
72
+ else:
73
+ h.update(f"{type(v).__name__}:{repr(v)};".encode())
74
+ visit(value)
75
+ return h.hexdigest()
76
+
77
+
78
+ def write_json(path, value):
79
+ path = Path(path)
80
+ path.parent.mkdir(parents=True, exist_ok=True)
81
+ tmp = path.with_suffix(path.suffix + ".tmp")
82
+ tmp.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
83
+ tmp.replace(path)
84
+
85
+
86
+ def save_pt(path, value):
87
+ path = Path(path)
88
+ tmp = path.with_suffix(path.suffix + ".tmp")
89
+ torch.save(value, tmp)
90
+ tmp.replace(path)
91
+
92
+
93
+ def load_frozen(root, pins):
94
+ root = Path(root).resolve()
95
+ tree = {str(p.relative_to(root)): sha(p) for p in sorted(root.rglob("*.py"))}
96
+ if tree != pins:
97
+ bad = sorted(set(tree.items()) ^ set(pins.items()))[:5]
98
+ raise ValueError(f"frozen source tree differs from the reference pins: {bad}")
99
+ if any(n == "go2nrd" or n.startswith("go2nrd.") for n in sys.modules):
100
+ raise ValueError("go2nrd imported before frozen source verification")
101
+ sys.path.insert(0, str(root))
102
+ helper = importlib.import_module("go2nrd.fixed_base.three_transformer")
103
+ trainer = importlib.import_module("go2nrd.fixed_base.train_three")
104
+ data = importlib.import_module("go2nrd.fixed_base.data")
105
+ frame = importlib.import_module("go2nrd.fixed_base.yaw_frame")
106
+ for name, module in list(sys.modules.items()):
107
+ if name == "go2nrd" or name.startswith("go2nrd."):
108
+ file = getattr(module, "__file__", None)
109
+ if file and not Path(file).resolve().is_relative_to(root):
110
+ raise ValueError(f"foreign go2nrd import: {name}: {file}")
111
+ return helper, trainer, data, frame, digest(pins)
112
+
113
+
114
+ class TrainingFailure(RuntimeError):
115
+ def __init__(self, message, payload):
116
+ super().__init__(message)
117
+ self.payload = payload
118
+
119
+
120
+ def short_rollout(model, helper, frame, sb, scales):
121
+ sh, so = sb["hist"], sb["ok"]
122
+ h = sb["horizon"]
123
+ loss = 0.
124
+ for t in range(h):
125
+ sf = frame.frame_from_state(sh[:, -1, 0])
126
+ sp, _ = helper.step(model, sh, so, sb["actions"][:, t], sb["ground"])
127
+ error = frame.local_error(sp, sb["targets"][:, t], sf)
128
+ loss = loss + F.huber_loss(error / scales["state_scale"], torch.zeros_like(sp))
129
+ if not torch.isfinite(sp).all():
130
+ break
131
+ sh, so = model.advance(sh, so, sp)
132
+ return loss / h
133
+
134
+
135
+ def joint_update(model, opt, train, scales, cfg, helper, frame, short, short_kind, eligibility, loss_horizon=50,
136
+ aux_weight=.25, stall_weight=.25):
137
+ """Exact reference stage-B/C update (frame_short / horizon100 drivers) + optional short_stall term."""
138
+ n = int(cfg["batch"])
139
+ b = train.sample(n, kind="all")
140
+ h, ok, action, ground = b["hist"], b["ok"], b["actions"][:, 0], b["ground"]
141
+ hc, hf = frame.canonicalize_history(h, ok)
142
+ cur, diff, lag = model.code(hc, ok)
143
+ terms = {}
144
+ logits = model.logits(cur, diff, action, lag, ground=ground)
145
+ terms["collision"] = F.binary_cross_entropy_with_logits(logits, b["gates"][:, 0])
146
+ pred, _ = helper.step(model, h, ok, action, ground, gates=b["gates"][:, 0])
147
+ error = frame.local_error(pred, b["targets"][:, 0], hf)[..., 19:]
148
+ terms["one_step"] = F.huber_loss(error / scales["rate_scale"], torch.zeros_like(error))
149
+ free = train.sample(max(16, n // 4), kind="free")
150
+ fh, ff = frame.canonicalize_history(free["hist"], free["ok"])
151
+ fc, fd, fl = model.code(fh, free["ok"])
152
+ dc = model.run_core(fc, fd, free["actions"][:, 0], fl)
153
+ dy = frame.to_local(free["targets"][:, 0], ff) - fh[:, -1]
154
+ terms["core"] = (((dc - dy)[..., 19:] / scales["rate_scale"]) ** 2).mean()
155
+ rb = train.sample(cfg["rollout_batch"], eligibility)
156
+ rh, ro = rb["hist"], rb["ok"]
157
+ loss = 0.
158
+ for t in range(loss_horizon):
159
+ rf = frame.frame_from_state(rh[:, -1, 0])
160
+ pred, _ = helper.step(model, rh, ro, rb["actions"][:, t], rb["ground"])
161
+ error = frame.local_error(pred, rb["targets"][:, t], rf)
162
+ loss = loss + F.huber_loss(error / scales["state_scale"], torch.zeros_like(pred))
163
+ if not torch.isfinite(pred).all():
164
+ break
165
+ rh, ro = model.advance(rh, ro, pred)
166
+ terms["rollout"] = loss / loss_horizon * cfg["rollout_weight"]
167
+ batches = {"ordinary": b, "free": free, "rollout": rb}
168
+ if short_kind == "original":
169
+ sb = short.sample(2)
170
+ stall = None
171
+ else:
172
+ sb, stall = short.sample()
173
+ terms["short_lean"] = short_rollout(model, helper, frame, sb, scales) * aux_weight
174
+ if stall is not None:
175
+ terms["short_stall"] = short_rollout(model, helper, frame, stall, scales) * stall_weight
176
+ loss = sum(terms.values())
177
+ if not torch.isfinite(loss):
178
+ raise TrainingFailure("nonfinite loss", {"batches": batches, "terms": terms})
179
+ opt.zero_grad(set_to_none=True)
180
+ loss.backward()
181
+ norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.)
182
+ if not torch.isfinite(norm):
183
+ raise TrainingFailure("nonfinite gradient", {"batches": batches, "terms": terms, "gradient_norm": norm})
184
+ opt.step()
185
+ sampled = n + len(free["hist"]) + len(rb["hist"]) + len(sb["hist"]) + (len(stall["hist"]) if stall else 0)
186
+ return {"loss": float(loss.detach()), "terms": {k: float(v.detach()) for k, v in terms.items()},
187
+ "gradient_norm": float(norm), "sampled_windows": sampled,
188
+ "rollout_loss_horizon": loss_horizon, "rollout_start_eligibility_horizon": eligibility,
189
+ "short_horizon": sb["horizon"], "short_choices": sb["choices"],
190
+ "stall_choices": stall["choices"] if stall else [],
191
+ "short_target_states": len(sb["hist"]) * sb["horizon"],
192
+ "stall_target_states": len(stall["hist"]) * stall["horizon"] if stall else 0,
193
+ "batch_identity": {k: {x: v[x].detach().cpu().tolist() for x in ("source", "row", "record")}
194
+ for k, v in batches.items()}}
195
+
196
+
197
+ def stage_a_update(model, opt, train, scales, cfg, helper, frame, update):
198
+ """Exact go2nrd.fixed_base.train_three loop body (framed branch), returning (stage, terms, loss, samples)."""
199
+ counts = [cfg["core_updates"], cfg["collision_updates"], cfg["joint_updates"]]
200
+ stage = "core" if update <= counts[0] else "collision" if update <= sum(counts[:2]) else "joint"
201
+ joint_step = update - sum(counts[:2])
202
+ supervised_joint = cfg.get("joint_one_step_updates", 0)
203
+ rollout_phase = stage == "joint" and joint_step > supervised_joint
204
+ phase_step = update if stage == "core" else update - counts[0] if stage == "collision" else joint_step
205
+ phase_total = counts[0] if stage == "core" else counts[1] if stage == "collision" else counts[2]
206
+ if stage == "joint" and supervised_joint:
207
+ phase_step = joint_step - supervised_joint if rollout_phase else joint_step
208
+ phase_total = counts[2] - supervised_joint if rollout_phase else supervised_joint
209
+ if cfg.get("cosine_schedule"):
210
+ warm = cfg.get("rollout_warmup", 20) if rollout_phase else cfg.get("one_step_warmup", 200)
211
+ warm = min(warm, phase_total)
212
+ frac = max(0., (phase_step - warm) / max(1, phase_total - warm))
213
+ lr = (cfg.get("lr_floor", cfg["lr"] * .1) +
214
+ (cfg["lr"] - cfg.get("lr_floor", cfg["lr"] * .1)) * .5 * (1 + math.cos(math.pi * frac)))
215
+ if phase_step <= warm:
216
+ lr = cfg["lr"] * phase_step / max(1, warm)
217
+ for group in opt.param_groups:
218
+ group["lr"] = lr
219
+ n = int(cfg["batch"])
220
+ samples = 0
221
+ b = train.sample(n, kind="free" if stage == "core" else "all")
222
+ samples += n
223
+ h, ok, action, ground = b["hist"], b["ok"], b["actions"][:, 0], b["ground"]
224
+ hc, fr = frame.canonicalize_history(h, ok)
225
+ local_target = frame.to_local(b["targets"][:, 0], fr)
226
+ cur, diff, lag = model.code(hc, ok)
227
+ terms = {}
228
+ horizon = None
229
+ if stage == "core":
230
+ dc = model.run_core(cur, diff, action, lag)
231
+ target = local_target - hc[:, -1]
232
+ terms["core"] = (((dc - target)[..., 19:] / scales["rate_scale"]) ** 2).mean()
233
+ else:
234
+ logits = model.logits(cur, diff, action, lag, ground=ground)
235
+ terms["collision"] = F.binary_cross_entropy_with_logits(logits, b["gates"][:, 0])
236
+ if stage == "joint":
237
+ pred, _ = helper.step(model, h, ok, action, ground, gates=b["gates"][:, 0])
238
+ error = frame.local_error(pred, b["targets"][:, 0], fr)[..., 19:]
239
+ terms["one_step"] = F.huber_loss(error / scales["rate_scale"], torch.zeros_like(error))
240
+ free = train.sample(max(16, n // 4), kind="free")
241
+ samples += len(free["hist"])
242
+ fh, ff = frame.canonicalize_history(free["hist"], free["ok"])
243
+ dy = frame.to_local(free["targets"][:, 0], ff) - fh[:, -1]
244
+ fc, fd, fl = model.code(fh, free["ok"])
245
+ dc = model.run_core(fc, fd, free["actions"][:, 0], fl)
246
+ terms["core"] = (((dc - dy)[..., 19:] / scales["rate_scale"]) ** 2).mean()
247
+ if rollout_phase and phase_step % cfg["rollout_every"] == 0:
248
+ frac = (joint_step - supervised_joint) / max(1, counts[2] - supervised_joint)
249
+ horizon = max(1, round(cfg["horizon_start"] + (cfg["horizon_max"] - cfg["horizon_start"]) * min(1., frac / .5)))
250
+ rb = train.sample(cfg["rollout_batch"], horizon)
251
+ samples += len(rb["hist"])
252
+ rh, ro = rb["hist"], rb["ok"]
253
+ loss = 0.
254
+ for t in range(horizon):
255
+ rf = frame.frame_from_state(rh[:, -1, 0])
256
+ pred, _ = helper.step(model, rh, ro, rb["actions"][:, t], rb["ground"])
257
+ error = frame.local_error(pred, rb["targets"][:, t], rf)
258
+ loss = loss + F.huber_loss(error / scales["state_scale"], torch.zeros_like(pred))
259
+ if not torch.isfinite(pred).all():
260
+ break
261
+ rh, ro = model.advance(rh, ro, pred)
262
+ terms["rollout"] = loss / horizon * cfg["rollout_weight"]
263
+ loss = sum(terms.values())
264
+ return stage, terms, loss, samples, horizon
265
+
266
+
267
+ def main():
268
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
269
+ p.add_argument("--mode", choices=("fresh", "cont", "parity-A", "parity-B", "parity-C"), required=True)
270
+ p.add_argument("--run-config", type=Path, required=True, help="nrd_v3 run JSON (arm, tree, recipe, caps)")
271
+ p.add_argument("--source-root", type=Path, required=True, help="frozen yaw_correction_v1/src")
272
+ p.add_argument("--pins", type=Path, required=True, help="registration JSON with source_sha256 pins")
273
+ p.add_argument("--recipe", type=Path, required=True, help="reference full_config.json")
274
+ p.add_argument("--manifest", type=Path, required=True)
275
+ p.add_argument("--data-root", type=Path)
276
+ p.add_argument("--parent-resume", type=Path)
277
+ p.add_argument("--parent-endpoint", type=Path)
278
+ p.add_argument("--output", type=Path, required=True)
279
+ p.add_argument("--seed", type=int, required=True)
280
+ p.add_argument("--device", default="cuda")
281
+ p.add_argument("--max-wall-seconds", type=float, default=3300.)
282
+ p.add_argument("--stop-at-update", type=int, default=0, help="parity/smoke: save and stop after this update")
283
+ p.add_argument("--log-every", type=int, default=0, help="0 = reference cadence")
284
+ p.add_argument("--short-module", type=Path, default=HERE / "reference" / "short_support.py")
285
+ args = p.parse_args()
286
+ started = time.monotonic()
287
+ rc = json.loads(args.run_config.read_text())
288
+ pins = json.loads(args.pins.read_text())["source_sha256"]
289
+ helper, trainer, data, frame, source_digest = load_frozen(args.source_root, pins)
290
+ sys.path.insert(0, str(HERE))
291
+ import samplers
292
+ import stall_support
293
+ cfg = json.loads(args.recipe.read_text())
294
+ parity = args.mode.startswith("parity")
295
+ arm, budget = rc["arm"], rc.get("budget", "matched")
296
+ tree = None if parity else rc["domain_tree"]
297
+ crm_domains = tuple(rc.get("crm_domains", ["crm"]))
298
+ use_cuda = str(args.device).startswith("cuda")
299
+
300
+ # ---- identical construction order to train_three.main (torch seed before model build) ----
301
+ torch.set_num_threads(int(cfg.get("cpu_threads", 1)))
302
+ torch.manual_seed(args.seed)
303
+ manifest = json.loads(args.manifest.read_text())
304
+ train_desc = data.load_arm(args.manifest, arm=arm, budget=budget, split="train", data_root=args.data_root)
305
+ val_desc = data.load_arm(args.manifest, arm=rc.get("val_arm", "mixed"), budget=budget, split="val",
306
+ data_root=args.data_root)
307
+ data.verify_sources(train_desc)
308
+ domains = [d["domain"] for d in train_desc]
309
+ for forbidden in rc.get("forbidden_directories", []):
310
+ if any(Path(d["path"]).name == forbidden for d in train_desc + val_desc):
311
+ raise ValueError(f"held-out directory in training/validation descriptors: {forbidden}")
312
+ W = samplers.weighted_sampler_class(helper)
313
+ train = W(train_desc, cfg["history"], args.device, args.seed + 1000, tree=tree, crm_domains=crm_domains)
314
+ val = helper.WindowSampler(val_desc, cfg["history"], args.device, args.seed + 2000)
315
+ extra_val = None
316
+ if rc.get("extra_val_arm"):
317
+ ed = data.load_arm(args.manifest, arm=rc["extra_val_arm"], budget=budget, split="val", data_root=args.data_root)
318
+ extra_val = helper.WindowSampler(ed, cfg["history"], args.device, args.seed + 2500)
319
+ model = helper.build_model(train.system, cfg).to(args.device)
320
+ opt = torch.optim.AdamW(model.parameters(), lr=cfg["lr"], weight_decay=cfg.get("weight_decay", 0.),
321
+ betas=tuple(cfg.get("optimizer_betas", (.9, .999))))
322
+ root = args.output
323
+ root.mkdir(parents=True, exist_ok=True)
324
+ if (root / "failure.json").exists():
325
+ raise ValueError("failed attempt retained; review before any retry")
326
+ resume = root / "resume.pt"
327
+
328
+ # ---- stage plan ----
329
+ if args.mode == "fresh":
330
+ plan = [("A", 1, 12000), ("B", 12001, 13000), ("C", 13001, 13500)]
331
+ elif args.mode == "parity-A":
332
+ plan = [("A", 1, 12000)]
333
+ elif args.mode == "parity-B":
334
+ plan = [("B", 12001, 13000)]
335
+ elif args.mode == "parity-C":
336
+ plan = [("C", 13001, 13500)]
337
+ else:
338
+ plan = None # set from parent update below
339
+ parent = None
340
+ if args.mode in ("cont", "parity-B", "parity-C"):
341
+ if not args.parent_resume:
342
+ raise ValueError("continuation needs --parent-resume")
343
+ parent = torch.load(args.parent_resume, map_location="cpu", weights_only=False)
344
+ if args.parent_endpoint:
345
+ endpoint = torch.load(args.parent_endpoint, map_location="cpu", weights_only=False)
346
+ for key in ("model_config", "system", "masks", "model_state_dict", "update", "runtime"):
347
+ if digest(parent[key]) != digest(endpoint[key]):
348
+ raise ValueError("parent resume differs from its exported endpoint: " + key)
349
+ if digest(model.system) != digest(parent["system"]) or digest(model.config) != digest(parent["model_config"]):
350
+ raise ValueError("model configuration differs from the parent")
351
+ if args.mode == "cont":
352
+ pu = int(parent["update"])
353
+ plan = [("D", pu + 1, pu + int(rc["cont_updates"]))]
354
+ elif int(parent["update"]) != plan[0][1] - 1:
355
+ raise ValueError("parity parent update does not match the stage")
356
+ stall_report = None
357
+ lineage = dict(schema="lateral_stuck_20261108_nrd_v3_train_v1", mode=args.mode, arm=arm, budget=budget,
358
+ seed=args.seed, manifest_sha256=sha(args.manifest), recipe=cfg, recipe_sha256=sha(args.recipe),
359
+ run_config=rc, domains=domains,
360
+ source_sha256={d["domain"]: d["source_sha256"] for d in train_desc},
361
+ frozen_source_digest=source_digest, driver_sha256=sha(__file__),
362
+ samplers_sha256=sha(HERE / "samplers.py"), stall_support_sha256=sha(HERE / "stall_support.py"),
363
+ plan=plan, parent_resume_sha256=sha(args.parent_resume) if args.parent_resume else None,
364
+ parent_endpoint_sha256=sha(args.parent_endpoint) if args.parent_endpoint else None,
365
+ normalization=("parent buffers and scales (no refit)" if parent is not None else
366
+ "fresh train-only refit on the training mixture (frozen initialize_from_train)"),
367
+ architecture="core_collision_contact_three_transformers",
368
+ representation=getattr(model, "state_frame", None),
369
+ short=("reference ShortCrossingSampler" if parity else "LeanStallShortSampler"))
370
+ lineage = json.loads(json.dumps(lineage))
371
+ if (root / "lineage.json").exists() and json.loads((root / "lineage.json").read_text()) != lineage:
372
+ raise ValueError("resume lineage/config changed; use a new output directory")
373
+ write_json(root / "lineage.json", lineage)
374
+
375
+ def make_short(stage):
376
+ """Short sampler for B/C/D; reference class in parity, lean+stall otherwise."""
377
+ nonlocal stall_report
378
+ if parity:
379
+ sys.path.insert(0, str(args.short_module.parent))
380
+ ss = importlib.import_module(args.short_module.stem)
381
+ return ss.ShortCrossingSampler(train, manifest, args.seed + 5000), "original"
382
+ masks, stall_report = stall_support.stall_tables(train.sources, manifest) if rc["short"]["stall_batch"] \
383
+ else ({}, None)
384
+ stall_domains = [d for d in domains if d in rc["short"]["stall_domains"]]
385
+ s = samplers.LeanStallShortSampler(train, manifest, args.seed + 5000, tree, masks, stall_domains,
386
+ rc["short"]["lean_batch"], rc["short"]["stall_batch"])
387
+ write_json(root / "short_support.json", {"short": s.report, "stall": stall_report})
388
+ return s, "lean_stall"
389
+
390
+ # ---- state ----
391
+ short, short_kind = None, None
392
+ total_samples, best, previous_s, last_val = 0, float("inf"), 0., None
393
+ if resume.exists():
394
+ ck = torch.load(resume, map_location=args.device, weights_only=False)
395
+ if ck["lineage"] != lineage:
396
+ raise ValueError("checkpoint lineage differs")
397
+ model.load_state_dict(ck["model_state_dict"])
398
+ opt.load_state_dict(ck["optimizer"])
399
+ scales = ck["scales"]
400
+ train.rng.bit_generator.state = ck["numpy_rng"]
401
+ torch.set_rng_state(ck["torch_rng"].cpu())
402
+ if use_cuda and ck.get("cuda_rng") is not None:
403
+ torch.cuda.set_rng_state_all([x.cpu() for x in ck["cuda_rng"]])
404
+ done = int(ck["update"])
405
+ total_samples, best, previous_s = ck["total_sampled_windows"], ck["best"], ck["elapsed_total_s"]
406
+ last_val = ck.get("validation")
407
+ if ck.get("short_sampler") is not None:
408
+ short, short_kind = make_short(ck["stage"])
409
+ short.load_state_dict(ck["short_sampler"])
410
+ elif parent is not None:
411
+ model.load_state_dict(parent["model_state_dict"])
412
+ opt.load_state_dict(parent["optimizer"])
413
+ if any(abs(g["lr"] - 3e-5) > 1e-12 for g in opt.param_groups):
414
+ raise ValueError("parent optimizer is not at the 3e-5 floor")
415
+ scales = {k: v.to(args.device) if torch.is_tensor(v) else v for k, v in parent["scales"].items()}
416
+ done = int(parent["update"])
417
+ total_samples = int(parent["total_sampled_windows"])
418
+ best = parent.get("best", float("inf"))
419
+ if args.mode != "cont":
420
+ # Parity: the reference drivers restored the parent's numpy/torch/CUDA streams.
421
+ train.rng.bit_generator.state = parent["numpy_rng"]
422
+ torch.set_rng_state(parent["torch_rng"].cpu())
423
+ if use_cuda and parent.get("cuda_rng") is not None:
424
+ torch.cuda.set_rng_state_all([v.cpu() for v in parent["cuda_rng"]])
425
+ short, short_kind = make_short(plan[0][0])
426
+ if args.mode == "parity-C":
427
+ short.load_state_dict(parent["short_sampler"])
428
+ else:
429
+ scales = helper.initialize_from_train(model, train, int(cfg["normalization_samples"]))
430
+ write_json(root / "initialization.json", {**scales["initialization"],
431
+ "mixture_probabilities_all_h1": train.probabilities(1, "all").tolist(), "domains": domains})
432
+ done = 0
433
+ scales = {k: v.to(args.device) if torch.is_tensor(v) else v for k, v in scales.items()}
434
+ model.train()
435
+ halt = [False]
436
+ for s_ in (signal.SIGTERM, signal.SIGINT, signal.SIGUSR1):
437
+ signal.signal(s_, lambda *_: halt.__setitem__(0, True))
438
+ final = plan[-1][2]
439
+ launch = dict(job_id=os.environ.get("SLURM_JOB_ID"), host=os.uname().nodename, resumed_at=done,
440
+ device=args.device, torch=torch.__version__, cuda=torch.version.cuda,
441
+ hip=getattr(torch.version, "hip", None),
442
+ gpu=torch.cuda.get_device_name(0) if use_cuda else None, numpy=np.__version__,
443
+ python=sys.version.split()[0], max_wall_seconds=args.max_wall_seconds,
444
+ stop_at_update=args.stop_at_update, t=time.strftime("%Y-%m-%dT%H:%M:%S"))
445
+ write_json(root / "starts" / f"launch_{time.time_ns()}.json", launch)
446
+ if not (root / "start.json").exists():
447
+ write_json(root / "start.json", launch)
448
+
449
+ def elapsed():
450
+ return previous_s + time.monotonic() - started
451
+
452
+ def stage_of(u):
453
+ for name, a, b in plan:
454
+ if a <= u <= b:
455
+ return name
456
+ return plan[-1][0]
457
+
458
+ def packet(u):
459
+ return dict(model_config=model.config, system=model.system, masks=model.smask.tolist(),
460
+ model_state_dict=model.state_dict(), stage="fixed_base_joint", update=u,
461
+ sigma=[[0.] * 37], runtime=lineage, validation=last_val)
462
+
463
+ def save(u, finished=False):
464
+ ck = {**packet(u), "lineage": lineage, "optimizer": opt.state_dict(), "scales": scales,
465
+ "numpy_rng": copy.deepcopy(train.rng.bit_generator.state), "torch_rng": torch.get_rng_state(),
466
+ "cuda_rng": torch.cuda.get_rng_state_all() if use_cuda else None,
467
+ "short_sampler": short.state_dict() if short is not None else None, "stage": stage_of(max(u, 1)),
468
+ "best": best, "elapsed_total_s": elapsed(), "total_sampled_windows": total_samples}
469
+ save_pt(resume, ck)
470
+ save_pt(root / "last.pt", packet(u))
471
+ write_json(root / "progress.json", dict(update=u, planned_updates=final, finished=finished,
472
+ stage=stage_of(max(u, 1)), elapsed_total_s=elapsed(), total_sampled_windows=total_samples,
473
+ source_draws_this_launch=train.draw_counts,
474
+ short_counts=(dict(short.counts) if short is not None else None),
475
+ checkpoint_sha256=sha(root / "last.pt"), job_id=os.environ.get("SLURM_JOB_ID")))
476
+
477
+ def validate(u):
478
+ nonlocal last_val
479
+ last_val = trainer.validate(model, val, scales, cfg["validation_batch"], tuple(cfg["validation_horizons"]))
480
+ write_json(root / f"validation_{u:07d}.json", last_val)
481
+ if extra_val is not None:
482
+ ev = trainer.validate(model, extra_val, scales, cfg["validation_batch"], tuple(cfg["validation_horizons"]))
483
+ write_json(root / f"validation_lat_{u:07d}.json", ev)
484
+ (root / "checkpoints").mkdir(exist_ok=True)
485
+ save_pt(root / "checkpoints" / f"update_{u:07d}.pt", packet(u))
486
+
487
+ def log(event, every_default):
488
+ every = args.log_every or every_default
489
+ u = event["update"]
490
+ if u % every == 0 or u == 1 or every_default == 1:
491
+ with (root / "train.jsonl").open("a") as f:
492
+ f.write(json.dumps(event, allow_nan=False) + "\n")
493
+ if u % 50 == 0 or u == 1:
494
+ print(json.dumps({k: v for k, v in event.items() if k not in ("batch_identity",)}), flush=True)
495
+
496
+ if done == 0:
497
+ pass
498
+ elif not resume.exists():
499
+ save(done)
500
+ first = done + 1
501
+ u = done
502
+ try:
503
+ for u in range(first, final + 1):
504
+ stage = stage_of(u)
505
+ if stage in ("B", "C", "D") and short is None:
506
+ short, short_kind = make_short(stage) # fresh pipeline enters stage B: new short RNG seed+5000
507
+ if use_cuda:
508
+ torch.cuda.synchronize()
509
+ t0 = time.monotonic()
510
+ if stage == "A":
511
+ sub, terms, loss, ns, horizon = stage_a_update(model, opt, train, scales, cfg, helper, frame, u)
512
+ if not torch.isfinite(loss):
513
+ raise TrainingFailure(f"nonfinite loss at {u}: {sub}", {"terms": terms})
514
+ opt.zero_grad(set_to_none=True)
515
+ loss.backward()
516
+ norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.)
517
+ if not torch.isfinite(norm):
518
+ raise TrainingFailure(f"nonfinite gradient at {u}: {sub}", {"terms": terms})
519
+ opt.step()
520
+ total_samples += ns
521
+ event = dict(update=u, stage=sub, loss=float(loss.detach()),
522
+ terms={k: float(v.detach()) for k, v in terms.items()}, elapsed_s=elapsed(),
523
+ total_sampled_windows=total_samples, lr=opt.param_groups[0]["lr"], horizon=horizon)
524
+ log(event, cfg["log_every"])
525
+ counts = [cfg["core_updates"], cfg["collision_updates"], cfg["joint_updates"]]
526
+ if sub == "joint" and (u % cfg["evaluate_every"] == 0 or u == sum(counts)):
527
+ validate(u)
528
+ if math.isfinite(last_val["selection_score"]) and last_val["selection_score"] < best:
529
+ best = last_val["selection_score"]
530
+ else:
531
+ elig = 50 if stage == "B" else 100
532
+ sw = rc.get("short", {})
533
+ m = joint_update(model, opt, train, scales, cfg, helper, frame, short, short_kind, elig,
534
+ aux_weight=float(sw.get("lean_weight", .25)) if not parity else .25,
535
+ stall_weight=float(sw.get("stall_weight", .25)))
536
+ total_samples += m.pop("sampled_windows")
537
+ if use_cuda:
538
+ torch.cuda.synchronize()
539
+ m.update(update=u, stage=stage, lr=opt.param_groups[0]["lr"], elapsed_s=elapsed(),
540
+ update_wall_s=time.monotonic() - t0, total_sampled_windows=total_samples)
541
+ log(m, 1)
542
+ if u % 250 == 0 or u == final:
543
+ validate(u)
544
+ if u in (STAGE_END["A"], STAGE_END["B"]) and args.mode == "fresh" and u != final:
545
+ (root / "checkpoints").mkdir(exist_ok=True)
546
+ save_pt(root / "checkpoints" / f"update_{u:07d}.pt", packet(u))
547
+ save(u)
548
+ shutil.copy2(resume, root / "checkpoints" / f"resume_stage{stage}_{u:07d}.pt")
549
+ stop = halt[0] or elapsed() - previous_s >= args.max_wall_seconds or u == args.stop_at_update
550
+ if u % cfg["checkpoint_every"] == 0 or stop or u == final:
551
+ save(u, finished=u == final)
552
+ if stop and u < final:
553
+ print(json.dumps({"bounded_stop": True, "update": u, "resume": str(resume)}), flush=True)
554
+ return
555
+ write_json(root / "complete.json", dict(complete=True, update=final, checkpoint_sha256=sha(root / "last.pt"),
556
+ resume_sha256=sha(resume), elapsed_total_s=elapsed(), lineage=lineage,
557
+ short_counts=dict(short.counts) if short is not None else None,
558
+ completion_means="schedule finished, not a research milestone"))
559
+ except Exception as exc:
560
+ failed = {"attempted_update": u, "exception": repr(exc)}
561
+ if isinstance(exc, TrainingFailure):
562
+ failed["failure_payload"] = exc.payload
563
+ save_pt(root / "failed_attempt.pt", failed)
564
+ write_json(root / "failure.json", {"exception": repr(exc), "traceback": traceback.format_exc(),
565
+ "attempted_update": u, "elapsed_s": elapsed(), "no_automatic_resume": True,
566
+ "previous_durable_checkpoint_retained": resume.exists()})
567
+ raise
568
+
569
+
570
+ if __name__ == "__main__":
571
+ main()
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/samplers.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """nrd_v3 samplers: domain-weighted WindowSampler and the lean + stall short-window sampler.
2
+
3
+ Both wrap the FROZEN reference implementation (yaw_correction_v1 src, digest 924630...). With ``tree=None`` the
4
+ window sampler calls the frozen ``sample`` unchanged (bitwise original draw stream). The only other change is that
5
+ CRM-type lateral sources get the same ``crm_free`` rule as domain ``crm`` for free-core windows.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from collections import Counter, defaultdict
10
+ import copy
11
+ import hashlib
12
+ import json
13
+
14
+ import numpy as np
15
+ import torch
16
+
17
+ # Default nrd_v3 domain tree: rigid 50 % of draws; the CRM half split 50/50 between crm_prod and lat_v2, and lat_v2
18
+ # pooled over the HIP and CUDA exports by eligible-window count (uniform over its windows).
19
+ DEFAULT_TREE = {"rigid": [0.5, ["rigid"]],
20
+ "crm_half": [0.5, {"crm_prod": [0.5, ["crm"]],
21
+ "lat_v2": [0.5, ["crm_lat_v2_hip", "crm_lat_v2_cuda"]]}]}
22
+
23
+
24
+ def leaf_probabilities(tree, domains, sizes):
25
+ """Per-source probability from a weight tree; empty branches pass their mass to nonempty siblings."""
26
+ sizes = np.asarray(sizes, float)
27
+ index = {d: i for i, d in enumerate(domains)}
28
+ p = np.zeros(len(domains))
29
+
30
+ def total(node):
31
+ if isinstance(node, list) and node and isinstance(node[0], str):
32
+ return sum(sizes[index[d]] for d in node if d in index)
33
+ return sum(total(child[1]) for child in node.values())
34
+
35
+ def assign(node, mass):
36
+ if isinstance(node, list) and node and isinstance(node[0], str):
37
+ idx = [index[d] for d in node if d in index]
38
+ s = sizes[idx]
39
+ p[idx] += mass * s / s.sum()
40
+ return
41
+ live = {k: v for k, v in node.items() if total(v[1]) > 0}
42
+ w = sum(v[0] for v in live.values())
43
+ for v in live.values():
44
+ assign(v[1], mass * v[0] / w)
45
+
46
+ if total(tree) <= 0:
47
+ raise ValueError("no eligible windows in any weighted domain")
48
+ assign(tree, 1.0)
49
+ listed = set()
50
+
51
+ def leaves(node):
52
+ if isinstance(node, list) and node and isinstance(node[0], str):
53
+ listed.update(node)
54
+ else:
55
+ for v in node.values():
56
+ leaves(v[1])
57
+ leaves(tree)
58
+ if set(domains) - listed:
59
+ raise ValueError(f"domains missing from the weight tree: {sorted(set(domains) - listed)}")
60
+ return p
61
+
62
+
63
+ def weighted_sampler_class(helper):
64
+ """Subclass of the frozen helper.WindowSampler (imported from the verified frozen source)."""
65
+ base = helper.WindowSampler
66
+ averaged = helper.averaged
67
+
68
+ class WeightedWindowSampler(base):
69
+ def __init__(self, descriptors, history=4, device="cpu", seed=0, tree=None, crm_domains=("crm",)):
70
+ super().__init__(descriptors, history, device, seed, balance_domains=True)
71
+ self.tree = copy.deepcopy(tree)
72
+ self.crm_domains = tuple(crm_domains)
73
+ self.domains = [s["desc"]["domain"] for s in self.sources]
74
+ if self.tree is not None:
75
+ leaf_probabilities(self.tree, self.domains, np.ones(len(self.domains))) # coverage check
76
+ self.summary["weight_tree"] = self.tree
77
+ self.summary["crm_free_domains"] = list(self.crm_domains)
78
+
79
+ def _pools(self, horizon, kind):
80
+ if self.crm_domains == ("crm",):
81
+ return super()._pools(horizon, kind)
82
+ key = int(horizon), kind
83
+ if key in self.cache:
84
+ return self.cache[key]
85
+ pools = []
86
+ for src in self.sources:
87
+ a = src["arrays"]
88
+ all_rows, all_records = [], []
89
+ for row in src["rows"]:
90
+ rs = np.arange(2 * self.k, int(a["lengths"][row]) - 2 * horizon, 2, dtype=np.int64)
91
+ if kind != "all" and len(rs):
92
+ labels = np.asarray(a["contacts"][row])[rs[:, None] + np.arange(-2, 2)].any(1)
93
+ count = labels.sum(-1)
94
+ keep = count == 0 if kind == "free" else count == 1 if kind == "single" else count > 0
95
+ if kind == "free":
96
+ keep &= ~np.asarray(a["contacts"][row])[rs - 3].any(-1)
97
+ if src["desc"]["domain"] in self.crm_domains:
98
+ if "crm_free" not in a:
99
+ raise ValueError("CRM free-core windows require crm_free evidence")
100
+ keep &= np.asarray(a["crm_free"][row])[rs[:, None] + np.arange(-2, 2)].all(1)
101
+ rs = rs[keep]
102
+ all_rows.append(np.full(len(rs), row, dtype=np.int64))
103
+ all_records.append(rs)
104
+ pools.append(np.stack((np.concatenate(all_rows), np.concatenate(all_records)), axis=1))
105
+ if sum(map(len, pools)) == 0:
106
+ raise ValueError(f"no {kind} windows with horizon {horizon}")
107
+ self.cache[key] = pools
108
+ return pools
109
+
110
+ def probabilities(self, horizon=1, kind="all"):
111
+ sizes = np.array(list(map(len, self._pools(horizon, kind))), float)
112
+ if self.tree is None:
113
+ prob = (sizes > 0).astype(float)
114
+ return prob / prob.sum()
115
+ return leaf_probabilities(self.tree, self.domains, sizes)
116
+
117
+ def sample(self, batch, horizon=1, kind="all"):
118
+ if self.tree is None:
119
+ return super().sample(batch, horizon, kind) # frozen original stream
120
+ pools = self._pools(horizon, kind)
121
+ prob = self.probabilities(horizon, kind)
122
+ # Same RNG call sequence as the frozen sampler; only the source probabilities differ.
123
+ src_choices = self.rng.choice(len(pools), int(batch), p=prob / prob.sum())
124
+ chunks = []
125
+ for si in np.unique(src_choices):
126
+ n = int((src_choices == si).sum())
127
+ src, pool = self.sources[si], pools[si]
128
+ picks = pool[self.rng.integers(len(pool), size=n)]
129
+ e, r = picks[:, 0], picks[:, 1]
130
+ a = src["arrays"]
131
+ hr = r[:, None] + 2 * np.arange(1 - self.k, 1)[None]
132
+ tr = r[:, None] + 2 * np.arange(1, horizon + 1)[None]
133
+ ar = r[:, None] + 2 * np.arange(horizon)[None]
134
+ d = lambda x, dtype=torch.float64: torch.as_tensor(np.array(x), dtype=dtype, device=self.device)
135
+ hist_raw, hist_prev = d(a["robot"][e[:, None], hr]), d(a["robot"][e[:, None], hr - 2])
136
+ truth_raw, truth_prev = d(a["robot"][e[:, None], tr]), d(a["robot"][e[:, None], tr - 2])
137
+ contact_r = ar[:, :, None] + np.arange(-2, 2)[None, None]
138
+ gate = np.asarray(a["contacts"][e[:, None, None], contact_r]).any(2)
139
+ out = dict(hist=averaged(hist_raw, hist_prev)[:, :, None],
140
+ targets=averaged(truth_raw, truth_prev)[:, :, None],
141
+ actions=d(a["action"][e[:, None], ar])[:, :, None],
142
+ gates=d(gate), ground=d(a["ground_features"][e]),
143
+ instantaneous=hist_raw[:, -1],
144
+ command=d(a["command"][e, r]), phase_k=d(a["phase_k"][e, r], torch.long),
145
+ last_action=d(a["raw_action"][e, r - 2]),
146
+ source=torch.full((n,), int(si), device=self.device),
147
+ row=d(e, torch.long), record=d(r, torch.long))
148
+ out["ok"] = torch.ones((n, self.k), dtype=torch.bool, device=self.device)
149
+ chunks.append(out)
150
+ domain = src["desc"]["domain"]
151
+ self.draw_counts[domain] = self.draw_counts.get(domain, 0) + n
152
+ return {k: torch.cat([c[k] for c in chunks]) for k in chunks[0]}
153
+
154
+ return WeightedWindowSampler
155
+
156
+
157
+ def _digest(value):
158
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
159
+
160
+
161
+ def _tilt(q):
162
+ q = np.asarray(q, np.float64)
163
+ norm = (q * q).sum(-1)
164
+ if not np.isfinite(q).all() or np.any(norm < 1e-12):
165
+ raise ValueError("invalid recorded quaternion")
166
+ return np.rad2deg(np.arccos(np.clip(1 - 2 * (q[..., 1:3] ** 2).sum(-1) / norm, -1, 1)))
167
+
168
+
169
+ class LeanStallShortSampler:
170
+ """Short H1..5 branches: lean (original 45 deg crossing endpoints) + lateral STALL starts. Independent RNG.
171
+
172
+ Lean pools use the exact ShortCrossingSampler eligibility (first <=45 -> >45 crossings on the 20 ms grid,
173
+ history >= 2k, parent action alignment, no earlier severe target). Lean domain choice follows ``tree`` over the
174
+ sources that have support at the drawn horizon, then uniform parent, then uniform start (a pooled leaf such as
175
+ lat_v2 = HIP + CUDA is pooled by parent count, i.e. uniform over its parents).
176
+ Stall pools: TRAIN rows of ``stall_domains``; start r and every branch state r+2, ..., r+2H inside the STALL mask
177
+ (stall_support.py: union of STALLED 1 s lateral windows), same history/alignment/same-piece rules.
178
+ One horizon per update for both; ``lean_batch`` + ``stall_batch`` draws.
179
+ """
180
+
181
+ def __init__(self, base, manifest, seed, tree, stall_masks, stall_domains, lean_batch=2, stall_batch=2):
182
+ if any(s["desc"].get("split") != "train" for s in base.sources):
183
+ raise ValueError("short objective requires explicit TRAIN descriptors")
184
+ self.base, self.rng = base, np.random.default_rng(seed)
185
+ self.tree, self.lean_batch, self.stall_batch = copy.deepcopy(tree), int(lean_batch), int(stall_batch)
186
+ self.domains = [s["desc"]["domain"] for s in base.sources]
187
+ self.stall_domains = tuple(stall_domains)
188
+ self.lean = {h: [] for h in range(1, 6)}
189
+ self.stall = {h: [] for h in range(1, 6)}
190
+ self.counts, self.seen = Counter(), set()
191
+ self.report = dict(history=base.k, split="train", lean_target="first20ms below-to-above45 crossing",
192
+ stall_target="start and all H targets inside a STALLED lateral 1 s window",
193
+ horizons=list(range(1, 6)), lean_batch=self.lean_batch, stall_batch=self.stall_batch,
194
+ tree=self.tree, stall_domains=list(self.stall_domains), domains={},
195
+ no_normalization_fit=True)
196
+ identity = []
197
+ for si, src in enumerate(base.sources):
198
+ domain = src["desc"]["domain"]
199
+ rows = {r["index"]: r for r in manifest["sources"][domain]["rows"]}
200
+ lean = {h: defaultdict(list) for h in range(1, 6)}
201
+ stall = {h: defaultdict(list) for h in range(1, 6)}
202
+ counts = Counter()
203
+ masks = stall_masks.get(si, {}) if domain in self.stall_domains else {}
204
+ for row in src["rows"]:
205
+ row = int(row)
206
+ meta = rows[row]
207
+ if meta["split"] != "train" or int(meta["length"]) != int(src["arrays"]["lengths"][row]):
208
+ raise ValueError("split/length mismatch")
209
+ n = int(meta["length"])
210
+ high = _tilt(src["arrays"]["robot"][row, :n, 3:7]) > 45
211
+ grid = np.arange(0, n, 2)
212
+ events = grid[1:][~high[grid[:-1]] & high[grid[1:]]]
213
+ counts["rows_scanned"] += 1
214
+ counts["new45_events"] += len(events)
215
+ parent = int(meta["parent_id"])
216
+ off = int(meta["record_offset"])
217
+ for h in range(1, 6):
218
+ for endpoint in events:
219
+ start = int(endpoint - 2 * h)
220
+ if start < 2 * base.k:
221
+ counts[f"H{h}/lean_excluded_history"] += 1
222
+ continue
223
+ if (start + off) % 2:
224
+ counts[f"H{h}/lean_excluded_alignment"] += 1
225
+ continue
226
+ if high[start:int(endpoint):2].any():
227
+ counts[f"H{h}/lean_excluded_prior_severe"] += 1
228
+ continue
229
+ lean[h][parent].append((row, start))
230
+ identity.append(("lean", domain, h, parent, row, start))
231
+ counts[f"H{h}/lean_eligible"] += 1
232
+ mask = masks.get(row)
233
+ if mask is None:
234
+ continue
235
+ starts = np.arange(2 * base.k, n, 2, dtype=np.int64)
236
+ starts = starts[(starts + off) % 2 == 0]
237
+ for h in range(1, 6):
238
+ ok = starts[starts + 2 * h < n]
239
+ keep = np.ones(len(ok), bool)
240
+ for j in range(0, h + 1):
241
+ keep &= mask[ok + 2 * j]
242
+ ok = ok[keep & ~high[ok]]
243
+ for start in ok.tolist():
244
+ stall[h][parent].append((row, start))
245
+ if len(ok):
246
+ identity.append(("stall", domain, h, parent, row, int(ok.min()), int(ok.max()), len(ok)))
247
+ counts[f"H{h}/stall_eligible"] += len(ok)
248
+ self.report["domains"][domain] = dict(
249
+ counts=dict(counts),
250
+ lean_parents={str(h): len(lean[h]) for h in lean},
251
+ stall_parents={str(h): len(stall[h]) for h in stall},
252
+ lean_families={str(h): dict(Counter(rows[r]["family"] for w in lean[h].values() for r, _ in w))
253
+ for h in lean})
254
+ for h in range(1, 6):
255
+ self.lean[h].append({p: np.array(v, dtype=np.int64) for p, v in sorted(lean[h].items())})
256
+ self.stall[h].append({p: np.array(v, dtype=np.int64) for p, v in sorted(stall[h].items())})
257
+ for h in range(1, 6):
258
+ if not any(self.lean[h]):
259
+ raise ValueError(f"no lean support at H{h}")
260
+ if self.stall_batch and not any(self.stall[h]):
261
+ raise ValueError(f"no stall support at H{h}")
262
+ self.pool_sha256 = _digest(sorted(map(list, identity)))
263
+ self.report["pool_sha256"] = self.pool_sha256
264
+
265
+ def _source_probabilities(self, pools, restrict=None):
266
+ sizes = np.array([len(p) if (restrict is None or d in restrict) else 0
267
+ for p, d in zip(pools, self.domains)], float)
268
+ if restrict is not None:
269
+ prob = sizes / sizes.sum() # stall: pooled over the lateral exports by parent count
270
+ else:
271
+ prob = leaf_probabilities(self.tree, self.domains, sizes)
272
+ return prob
273
+
274
+ def _draw(self, pools, n, kind, h, restrict=None):
275
+ prob = self._source_probabilities(pools, restrict)
276
+ choices = []
277
+ for _ in range(n):
278
+ si = int(self.rng.choice(len(pools), p=prob))
279
+ parents = list(pools[si])
280
+ parent = int(parents[int(self.rng.integers(len(parents)))])
281
+ pool = pools[si][parent]
282
+ row, start = map(int, pool[int(self.rng.integers(len(pool)))])
283
+ choices.append((si, parent, row, start))
284
+ chunks = []
285
+ average = __import__("go2nrd.fixed_base.three_transformer", fromlist=["averaged"]).averaged
286
+ for si, parent, row, start in choices:
287
+ src = self.base.sources[si]
288
+ a = src["arrays"]
289
+ hr = start + 2 * np.arange(1 - self.base.k, 1)
290
+ tr = start + 2 * np.arange(1, h + 1)
291
+ ar = start + 2 * np.arange(h)
292
+ d = lambda x: torch.as_tensor(np.array(x), dtype=torch.float64, device=self.base.device)
293
+ hist = average(d(a["robot"][row, hr]), d(a["robot"][row, hr - 2]))[None, :, None]
294
+ targets = average(d(a["robot"][row, tr]), d(a["robot"][row, tr - 2]))[None, :, None]
295
+ action = d(a["action"][row, ar])[None, :, None]
296
+ ground = d(a["ground_features"][row])[None]
297
+ if not all(torch.isfinite(v).all() for v in (hist, targets, action, ground)):
298
+ raise ValueError("nonfinite short branch input")
299
+ chunks.append(dict(hist=hist, targets=targets, actions=action, ground=ground,
300
+ ok=torch.ones((1, self.base.k), dtype=torch.bool, device=self.base.device)))
301
+ domain = src["desc"]["domain"]
302
+ self.counts[f"{kind}/{domain}/H{h}"] += 1
303
+ self.counts[f"{kind}/{domain}/parent/{parent}"] += 1
304
+ self.seen.add((kind, domain, h, row, start))
305
+ out = {k: torch.cat([c[k] for c in chunks]) for k in chunks[0]}
306
+ out["choices"] = choices
307
+ out["horizon"] = h
308
+ return out
309
+
310
+ def sample(self):
311
+ h = int(self.rng.integers(1, 6))
312
+ lean = self._draw(self.lean[h], self.lean_batch, "lean", h)
313
+ stall = self._draw(self.stall[h], self.stall_batch, "stall", h, restrict=self.stall_domains) \
314
+ if self.stall_batch else None
315
+ return lean, stall
316
+
317
+ def state_dict(self):
318
+ return dict(pool_sha256=self.pool_sha256, rng=copy.deepcopy(self.rng.bit_generator.state),
319
+ counts=dict(self.counts), seen=sorted(map(list, self.seen)))
320
+
321
+ def load_state_dict(self, value):
322
+ if value["pool_sha256"] != self.pool_sha256:
323
+ raise ValueError("short support differs on resume")
324
+ self.rng.bit_generator.state = value["rng"]
325
+ self.counts = Counter(value["counts"])
326
+ self.seen = set(map(tuple, value["seen"]))
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/nrd_v3/stall_support.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train-only lateral STALL masks on exported pieces (lateral_stuck_20261108, track nrd_v3).
2
+
3
+ Same definition as the track-A QA (collect/scripts/qa_episodes.py), applied inside one exported piece:
4
+
5
+ * command c = exported ``command`` per record; lateral-dominant run: |vy_cmd| >= 0.2 and |vy_cmd| >= |vx_cmd|,
6
+ one constant command run (any change of the 3 command values starts a new run);
7
+ * achieved = world base velocity (robot[:, 19:22], instantaneous) rotated by -yaw, y component, times sign(vy_cmd);
8
+ * 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
9
+ piece start is treated as starting there (conservative: never a window across a cut);
10
+ * ratio = mean(achieved) / |vy_cmd|; STUCK < 0.4, STALLED < 0.2.
11
+
12
+ The per-record STALL mask is the union of all STALLED windows. Numpy only. No labels, no fitting, no held-out data.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+
19
+ import numpy as np
20
+
21
+ DT, WIN, STRIDE, SETTLE = 0.01, 100, 10, 50
22
+ VY_MIN, STALLED, STUCK = 0.2, 0.2, 0.4
23
+
24
+
25
+ def yaw_of(q):
26
+ w, x, y, z = np.asarray(q, np.float64).T
27
+ return np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
28
+
29
+
30
+ def piece_windows(robot, command, length):
31
+ """[(w0, ratio, |vy|)] settled lateral 1 s windows of one piece and the per-record STALL mask."""
32
+ n = int(length)
33
+ st = np.asarray(robot[:n], np.float64)
34
+ cmd = np.asarray(command[:n], np.float64)
35
+ yaw = yaw_of(st[:, 3:7])
36
+ vw = st[:, 19:22]
37
+ v_head_y = -np.sin(yaw) * vw[:, 0] + np.cos(yaw) * vw[:, 1]
38
+ change = np.ones(n, bool)
39
+ change[1:] = np.any(cmd[1:] != cmd[:-1], 1)
40
+ starts = list(np.flatnonzero(change)) + [n]
41
+ wins, mask = [], np.zeros(n, bool)
42
+ for a, b in zip(starts[:-1], starts[1:]):
43
+ c = cmd[a]
44
+ avy, avx = abs(c[1]), abs(c[0])
45
+ if not (avy >= VY_MIN and avy >= avx):
46
+ continue
47
+ along = v_head_y * np.sign(c[1])
48
+ for w0 in range(a + SETTLE, b - WIN + 1, STRIDE):
49
+ r = float(along[w0:w0 + WIN].mean() / avy)
50
+ wins.append((w0, r, avy))
51
+ if r < STALLED:
52
+ mask[w0:w0 + WIN] = True
53
+ return wins, mask
54
+
55
+
56
+ def stall_tables(sources, manifest):
57
+ """Per lateral TRAIN source: {row: STALL mask}; plus a report. ``sources`` = WindowSampler.sources."""
58
+ out, report, identity = {}, {}, []
59
+ for si, src in enumerate(sources):
60
+ d = src["desc"]
61
+ if d.get("split") != "train":
62
+ raise ValueError("stall support is TRAIN only")
63
+ a = src["arrays"]
64
+ rows_meta = {r["index"]: r for r in manifest["sources"][d["domain"]]["rows"]}
65
+ masks, nwin, nstuck, nstalled, ratios = {}, 0, 0, 0, []
66
+ for row in src["rows"]:
67
+ row = int(row)
68
+ meta = rows_meta[row]
69
+ if meta["split"] != "train" or int(meta["length"]) != int(a["lengths"][row]):
70
+ raise ValueError("split/length mismatch in stall support")
71
+ wins, mask = piece_windows(a["robot"][row], a["command"][row], a["lengths"][row])
72
+ nwin += len(wins)
73
+ r = np.array([w[1] for w in wins]) if wins else np.zeros(0)
74
+ nstuck += int((r < STUCK).sum())
75
+ nstalled += int((r < STALLED).sum())
76
+ ratios += r.tolist()
77
+ if mask.any():
78
+ masks[row] = mask
79
+ identity.append((d["domain"], row, hashlib.sha256(np.packbits(mask).tobytes()).hexdigest()))
80
+ out[si] = masks
81
+ report[d["domain"]] = dict(lateral_windows=nwin, stuck=nstuck, stalled=nstalled,
82
+ stuck_share=nstuck / max(1, nwin), stalled_share=nstalled / max(1, nwin),
83
+ median_ratio=float(np.median(ratios)) if ratios else None,
84
+ rows_with_stall=len(masks), stall_records=int(sum(m.sum() for m in masks.values())))
85
+ digest = hashlib.sha256(json.dumps(sorted(identity)).encode()).hexdigest()
86
+ return out, dict(definition=__doc__.strip().splitlines()[0], vy_min=VY_MIN, stalled=STALLED, stuck=STUCK,
87
+ window_s=WIN * DT, stride_s=STRIDE * DT, settle_s=SETTLE * DT, domains=report,
88
+ mask_sha256=digest)
go2_sand_finetune/code/browse/nrd_capsule_c0e07a22e57434cd/src/go2nrd/fixed_base/three_transformer.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed-policy 3NN primitives; retained ContactNRD architecture, audited data views.
2
+
3
+ This is a new training recipe, not the legacy trainer. All fitted quantities use
4
+ the training split, and every model call uses the same xy recentering as PPO.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ import copy
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import torch
15
+
16
+ from go2nrd.contact_nrd.model import ContactNRD, model_config
17
+ from go2nrd.sim.bank import npz_members
18
+ from go2nrd.sim.quat import step_rotvec
19
+
20
+
21
+ def sha256(path):
22
+ h = hashlib.sha256()
23
+ with open(path, "rb") as f:
24
+ for x in iter(lambda: f.read(8 << 20), b""):
25
+ h.update(x)
26
+ return h.hexdigest()
27
+
28
+
29
+ def atomic_json(path, value):
30
+ path = Path(path)
31
+ path.parent.mkdir(parents=True, exist_ok=True)
32
+ tmp = path.with_suffix(path.suffix + ".tmp")
33
+ tmp.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
34
+ tmp.replace(path)
35
+
36
+
37
+ def averaged(raw, previous, dt=0.02):
38
+ out = raw.clone()
39
+ out[..., 19:22] = (raw[..., :3] - previous[..., :3]) / dt
40
+ out[..., 22:25] = step_rotvec(previous[..., 3:7], raw[..., 3:7]) / dt
41
+ out[..., 25:37] = (raw[..., 7:19] - previous[..., 7:19]) / dt
42
+ return out
43
+
44
+
45
+ class WindowSampler:
46
+ """Sample complete 20ms histories and branches within audited episode pieces.
47
+
48
+ `descriptors` comes from fixed_base.data.load_arm. No cached source split is
49
+ used here: only its explicit audited row indices. The first state in a
50
+ history has two preceding records, so all rates are averaged and no history
51
+ crosses a cut. Sampling is balanced by domain when requested; otherwise it
52
+ is uniform over eligible control windows, including probes.
53
+ """
54
+
55
+ def __init__(self, descriptors, history=4, device="cpu", seed=0, balance_domains=True):
56
+ self.sources = []
57
+ self.k, self.device = int(history), torch.device(device)
58
+ self.rng = np.random.default_rng(seed)
59
+ self.balance_domains = balance_domains
60
+ self.cache = {}
61
+ self.draw_counts = {}
62
+ for desc in descriptors:
63
+ p = Path(desc["path"])
64
+ system = json.loads((p / "system.json").read_text())
65
+ if abs(system["record_step_s"] - .01) > 1e-12:
66
+ raise ValueError("WindowSampler requires 10ms source records")
67
+ arrays = npz_members(p / "unified_data.npz")
68
+ rows = np.array(desc["indices"], dtype=np.int64)
69
+ if not len(rows):
70
+ continue
71
+ self.sources.append(dict(desc=desc, arrays=arrays, rows=rows, system=system))
72
+ if not self.sources:
73
+ raise ValueError("no source episodes")
74
+ self.system = self.sources[0]["system"]
75
+ for s in self.sources[1:]:
76
+ for key in ("bodies", "pairs", "record_step_s", "model_step_s"):
77
+ if s["system"][key] != self.system[key]:
78
+ raise ValueError(f"source structure differs: {key}")
79
+ self.summary = {"history": self.k, "representation": "world37_avg20_xy_recentered",
80
+ "rows": {s["desc"]["domain"]: len(s["rows"]) for s in self.sources},
81
+ "balanced_domains": bool(balance_domains), "boundary_history": "full, earliest record >= 2"}
82
+
83
+ def _pools(self, horizon, kind):
84
+ key = int(horizon), kind
85
+ if key in self.cache:
86
+ return self.cache[key]
87
+ pools = []
88
+ for src in self.sources:
89
+ a = src["arrays"]
90
+ all_rows, all_records = [], []
91
+ for row in src["rows"]:
92
+ rs = np.arange(2 * self.k, int(a["lengths"][row]) - 2 * horizon, 2, dtype=np.int64)
93
+ if kind != "all" and len(rs):
94
+ # Averaged-rate target uses current AND previous model interval.
95
+ labels = np.asarray(a["contacts"][row])[rs[:, None] + np.arange(-2, 2)].any(1)
96
+ count = labels.sum(-1)
97
+ keep = count == 0 if kind == "free" else count == 1 if kind == "single" else count > 0
98
+ if kind == "free":
99
+ # Legacy core excludes residual response immediately after a labelled interval.
100
+ keep &= ~np.asarray(a["contacts"][row])[rs - 3].any(-1)
101
+ if src["desc"]["domain"] == "crm":
102
+ if "crm_free" not in a:
103
+ raise ValueError("CRM free-core windows require crm_free evidence")
104
+ keep &= np.asarray(a["crm_free"][row])[rs[:, None] + np.arange(-2, 2)].all(1)
105
+ rs = rs[keep]
106
+ all_rows.append(np.full(len(rs), row, dtype=np.int64))
107
+ all_records.append(rs)
108
+ pools.append(np.stack((np.concatenate(all_rows), np.concatenate(all_records)), axis=1))
109
+ if sum(map(len, pools)) == 0:
110
+ raise ValueError(f"no {kind} windows with horizon {horizon}")
111
+ self.cache[key] = pools
112
+ return pools
113
+
114
+ def sample(self, batch, horizon=1, kind="all"):
115
+ pools = self._pools(horizon, kind)
116
+ sizes = np.array(list(map(len, pools)), float)
117
+ prob = (sizes > 0).astype(float) if self.balance_domains else sizes
118
+ src_choices = self.rng.choice(len(pools), int(batch), p=prob / prob.sum())
119
+ chunks = []
120
+ for si in np.unique(src_choices):
121
+ n = int((src_choices == si).sum())
122
+ src, pool = self.sources[si], pools[si]
123
+ picks = pool[self.rng.integers(len(pool), size=n)]
124
+ e, r = picks[:, 0], picks[:, 1]
125
+ a = src["arrays"]
126
+ hr = r[:, None] + 2 * np.arange(1 - self.k, 1)[None]
127
+ tr = r[:, None] + 2 * np.arange(1, horizon + 1)[None]
128
+ ar = r[:, None] + 2 * np.arange(horizon)[None]
129
+ d = lambda x, dtype=torch.float64: torch.as_tensor(np.array(x), dtype=dtype, device=self.device)
130
+ hist_raw, hist_prev = d(a["robot"][e[:, None], hr]), d(a["robot"][e[:, None], hr - 2])
131
+ truth_raw, truth_prev = d(a["robot"][e[:, None], tr]), d(a["robot"][e[:, None], tr - 2])
132
+ contact_r = ar[:, :, None] + np.arange(-2, 2)[None, None]
133
+ gate = np.asarray(a["contacts"][e[:, None, None], contact_r]).any(2)
134
+ out = dict(hist=averaged(hist_raw, hist_prev)[:, :, None],
135
+ targets=averaged(truth_raw, truth_prev)[:, :, None],
136
+ actions=d(a["action"][e[:, None], ar])[:, :, None],
137
+ gates=d(gate), ground=d(a["ground_features"][e]),
138
+ instantaneous=hist_raw[:, -1],
139
+ command=d(a["command"][e, r]), phase_k=d(a["phase_k"][e, r], torch.long),
140
+ last_action=d(a["raw_action"][e, r - 2]),
141
+ source=torch.full((n,), int(si), device=self.device),
142
+ row=d(e, torch.long), record=d(r, torch.long))
143
+ out["ok"] = torch.ones((n, self.k), dtype=torch.bool, device=self.device)
144
+ chunks.append(out)
145
+ domain = src["desc"]["domain"]
146
+ self.draw_counts[domain] = self.draw_counts.get(domain, 0) + n
147
+ return {k: torch.cat([c[k] for c in chunks]) for k in chunks[0]}
148
+
149
+
150
+ class RareRolloutSampler:
151
+ """Opt-in train-only replacements after an unchanged uniform rollout draw.
152
+
153
+ The independent RNG never touches the base sampler, torch RNG, one-step
154
+ draws, initialization or validation. A rare start has at least one future
155
+ *20ms target pose* above the threshold within its fully available branch.
156
+ Replacements remain in the original domain and sample uniformly over that
157
+ domain's eligible rare windows. Nothing pads or joins exported pieces.
158
+ """
159
+
160
+ def __init__(self, sampler, manifest_path, fraction=.25, tilt_degrees=30., seed=0):
161
+ self.sampler = sampler
162
+ self.fraction, self.tilt_degrees = float(fraction), float(tilt_degrees)
163
+ if not 0 <= self.fraction <= 1 or not 0 < self.tilt_degrees < 180:
164
+ raise ValueError("invalid rare rollout fraction/tilt threshold")
165
+ manifest = json.loads(Path(manifest_path).read_text())
166
+ digest = sha256(manifest_path)
167
+ self.parents = []
168
+ for src in sampler.sources:
169
+ d = src["desc"]
170
+ if d["split"] != "train" or d["manifest_sha256"] != digest:
171
+ raise ValueError("rare rollout sampling requires the pinned training split")
172
+ rows = {r["index"]: r for r in manifest["sources"][d["domain"]]["rows"]}
173
+ train_parents = {rows[int(i)]["parent_id"] for i in src["rows"]}
174
+ if any(r["parent_id"] in train_parents and r["split"] != "train" for r in rows.values()):
175
+ raise ValueError("rare rollout parent crosses the training split")
176
+ self.parents.append({int(i): rows[int(i)]["parent_id"] for i in src["rows"]})
177
+ self.rng = np.random.default_rng(seed)
178
+ self.config = dict(fraction=self.fraction, tilt_degrees=self.tilt_degrees, seed=int(seed),
179
+ manifest_sha256=digest, definition="any future20ms target tilt strictly above threshold")
180
+ self.cache, self.stats, self.prefixes = {}, {}, {}
181
+
182
+ def _pool(self, horizon, si):
183
+ key = int(horizon), int(si)
184
+ if key in self.cache:
185
+ return self.cache[key]
186
+ pool = self.sampler._pools(horizon, "all")[si]
187
+ src = self.sampler.sources[si]
188
+ a, pieces = src["arrays"], []
189
+ cosine = np.cos(np.deg2rad(self.tilt_degrees))
190
+ # Prefix sums avoid a windows x horizon allocation at every curriculum H.
191
+ rows, first, sizes = np.unique(pool[:, 0], return_index=True, return_counts=True)
192
+ for row, begin, size in zip(rows, first, sizes):
193
+ starts = pool[begin:begin + size, 1]
194
+ if (si, int(row)) not in self.prefixes:
195
+ q = np.asarray(a["robot"][row, :int(a["lengths"][row]):2, 3:7], dtype=np.float64)
196
+ cos_tilt = 1 - 2 * (q[:, 1:3] ** 2).sum(-1) / (q ** 2).sum(-1)
197
+ self.prefixes[si, int(row)] = np.r_[0, np.cumsum(cos_tilt < cosine)]
198
+ prefix = self.prefixes[si, int(row)]
199
+ control = starts // 2
200
+ keep = prefix[control + horizon + 1] - prefix[control + 1] > 0
201
+ pieces.append(np.stack((np.full(int(keep.sum()), row, dtype=np.int64), starts[keep]), 1))
202
+ rare = np.concatenate(pieces) if pieces else np.empty((0, 2), dtype=np.int64)
203
+ self.cache[key] = rare
204
+ tag = f"{horizon}/{src['desc']['domain']}"
205
+ available = dict(eligible_uniform_windows=len(pool), eligible_rare_windows=len(rare),
206
+ eligible_rare_parents=len({self.parents[si][int(row)] for row in rare[:, 0]}),
207
+ rare_pool_sha256=hashlib.sha256(rare.astype('<i8', copy=False).tobytes()).hexdigest())
208
+ if tag in self.stats:
209
+ if any(self.stats[tag][k] != v for k, v in available.items()):
210
+ raise ValueError("resumed rare pool differs from checkpoint")
211
+ else:
212
+ self.stats[tag] = {**available, "uniform_draws": 0, "requested_replacements": 0,
213
+ "applied_replacements": 0, "empty_pool_fallbacks": 0, "uniform_rare_draws": 0,
214
+ "returned_rare_draws": 0, "replacement_parent_draws": {}, "replacement_start_draws": {}}
215
+ return rare
216
+
217
+ def _gather(self, si, picks, horizon):
218
+ """Materialize already-audited rare picks without consuming any RNG."""
219
+ src, k = self.sampler.sources[si], self.sampler.k
220
+ a, e, r = src["arrays"], picks[:, 0], picks[:, 1]
221
+ # Explicit boundaries protect against accidental cache/schema changes.
222
+ if not np.isin(e, src["rows"]).all() or not ((r >= 2 * k) & (r % 2 == 0) &
223
+ (r + 2 * horizon < np.asarray(a["lengths"])[e])).all():
224
+ raise ValueError("rare pick violates training row or same-piece history")
225
+ hr = r[:, None] + 2 * np.arange(1 - k, 1)[None]
226
+ tr = r[:, None] + 2 * np.arange(1, horizon + 1)[None]
227
+ ar = r[:, None] + 2 * np.arange(horizon)[None]
228
+ d = lambda x, dtype=torch.float64: torch.as_tensor(np.array(x), dtype=dtype, device=self.sampler.device)
229
+ gate = np.asarray(a["contacts"][e[:, None, None], ar[:, :, None] + np.arange(-2, 2)]).any(2)
230
+ n = len(picks)
231
+ return dict(hist=averaged(d(a["robot"][e[:, None], hr]), d(a["robot"][e[:, None], hr - 2]))[:, :, None],
232
+ targets=averaged(d(a["robot"][e[:, None], tr]), d(a["robot"][e[:, None], tr - 2]))[:, :, None],
233
+ actions=d(a["action"][e[:, None], ar])[:, :, None], gates=d(gate), ground=d(a["ground_features"][e]),
234
+ instantaneous=d(a["robot"][e, r]), command=d(a["command"][e, r]),
235
+ phase_k=d(a["phase_k"][e, r], torch.long), last_action=d(a["raw_action"][e, r - 2]),
236
+ source=torch.full((n,), int(si), device=self.sampler.device), row=d(e, torch.long), record=d(r, torch.long),
237
+ ok=torch.ones((n, k), dtype=torch.bool, device=self.sampler.device))
238
+
239
+ def _is_rare(self, targets):
240
+ q = targets[..., 3:7]
241
+ cosine = 1 - 2 * q[..., 1:3].square().sum(-1) / q.square().sum(-1)
242
+ return (cosine < np.cos(np.deg2rad(self.tilt_degrees))).any((1, 2))
243
+
244
+ def sample(self, batch, horizon):
245
+ b = self.sampler.sample(batch, horizon)
246
+ if self.fraction == 0:
247
+ return b # Exact opt-out, including no independent RNG consumption.
248
+ requested = self.rng.random(int(batch)) < self.fraction
249
+ for si, src in enumerate(self.sampler.sources):
250
+ positions = np.flatnonzero(b["source"].cpu().numpy() == si)
251
+ if not len(positions):
252
+ continue
253
+ rare = self._pool(horizon, si)
254
+ stats = self.stats[f"{horizon}/{src['desc']['domain']}"]
255
+ chosen = positions[requested[positions]]
256
+ stats["uniform_draws"] += len(positions)
257
+ stats["requested_replacements"] += len(chosen)
258
+ stats["uniform_rare_draws"] += int(self._is_rare(b["targets"][positions]).sum())
259
+ if len(rare) and len(chosen):
260
+ picks = rare[self.rng.integers(len(rare), size=len(chosen))]
261
+ replacement = self._gather(si, picks, horizon)
262
+ for key in b:
263
+ b[key][chosen] = replacement[key]
264
+ stats["applied_replacements"] += len(chosen)
265
+ for row, record in picks:
266
+ for key, value in (("replacement_parent_draws", str(self.parents[si][int(row)])),
267
+ ("replacement_start_draws", f"{row}:{record}")):
268
+ stats[key][value] = stats[key].get(value, 0) + 1
269
+ elif len(chosen):
270
+ stats["empty_pool_fallbacks"] += len(chosen)
271
+ stats["returned_rare_draws"] += int(self._is_rare(b["targets"][positions]).sum())
272
+ return b
273
+
274
+ def state_dict(self):
275
+ return copy.deepcopy(dict(config=self.config, rng=self.rng.bit_generator.state, stats=self.stats))
276
+
277
+ def load_state_dict(self, state):
278
+ if state["config"] != self.config:
279
+ raise ValueError("rare rollout checkpoint config differs")
280
+ self.rng.bit_generator.state = copy.deepcopy(state["rng"])
281
+ self.stats = copy.deepcopy(state["stats"])
282
+ self.cache.clear()
283
+
284
+ def report(self, horizon=None):
285
+ def exposure(v):
286
+ parents, starts = v["replacement_parent_draws"], v["replacement_start_draws"]
287
+ return dict(applied_fraction=v["applied_replacements"] / max(1, v["uniform_draws"]),
288
+ returned_rare_fraction=v["returned_rare_draws"] / max(1, v["uniform_draws"]),
289
+ unique_replacement_parents=len(parents), unique_replacement_starts=len(starts),
290
+ maximum_replacement_parent_draws=max(parents.values(), default=0),
291
+ maximum_replacement_start_draws=max(starts.values(), default=0),
292
+ repeated_start_draws=sum(starts.values()) - len(starts))
293
+ counters = ("replacement_parent_draws", "replacement_start_draws")
294
+ rows, totals = {}, {}
295
+ for key, value in self.stats.items():
296
+ if horizon is None or key.startswith(f"{horizon}/"):
297
+ rows[key] = {**{k: v for k, v in value.items() if k not in counters}, **exposure(value)}
298
+ domain = key.split('/', 1)[1]
299
+ total = totals.setdefault(domain, dict(uniform_draws=0, applied_replacements=0, returned_rare_draws=0,
300
+ replacement_parent_draws={}, replacement_start_draws={}))
301
+ for k in ("uniform_draws", "applied_replacements", "returned_rare_draws"):
302
+ total[k] += value[k]
303
+ for k in counters:
304
+ for item, count in value[k].items():
305
+ total[k][item] = total[k].get(item, 0) + count
306
+ return dict(config=self.config, by_horizon_domain=rows,
307
+ cumulative_by_domain={k: {**{n: v for n, v in t.items() if n not in counters}, **exposure(t)}
308
+ for k, t in totals.items()})
309
+
310
+
311
+ def recenter(hist):
312
+ off = hist[:, -1:, :, :2]
313
+ return torch.cat((hist[..., :2] - off, hist[..., 2:]), -1), off[:, 0]
314
+
315
+
316
+ def step(model, hist, ok, action, ground, gates=None):
317
+ """Identical xy convention to Go2NrdSim; optional teacher gates for fitting."""
318
+ if getattr(model, "state_frame", None) is not None:
319
+ return model.world_step(hist, ok, action, ground=ground, gates=gates)
320
+ hc, off = recenter(hist)
321
+ if gates is None:
322
+ nxt, info = model.details(hc, ok, action, ground=ground)
323
+ else:
324
+ cur, diff, lag = model.code(hc, ok)
325
+ core = model.run_core(cur, diff, action, lag)
326
+ logits = model.logits(cur, diff, action, lag, ground=ground)
327
+ change = model.contact_sum(cur, diff, action, lag, gates, ground=ground)
328
+ nxt = model.assemble(cur, core, change)
329
+ info = dict(logits=logits, gates=gates, core=core, contact=change)
330
+ return torch.cat((nxt[..., :2] + off, nxt[..., 2:]), -1), info
331
+
332
+
333
+ def build_model(system, config):
334
+ mc = model_config(.02, config["history"], config["network"], ["articulated"], 3, 32)
335
+ if "state_frame" in config:
336
+ from .yaw_frame import FRAME_VERSION
337
+ from .yaw_frame_adapter import YawFrameContactNRD
338
+ if config["state_frame"] != FRAME_VERSION:
339
+ raise ValueError("Unsupported training state frame")
340
+ mc["state_frame"] = FRAME_VERSION
341
+ return YawFrameContactNRD(mc, system, [[1.] * 37])
342
+ return ContactNRD(mc, system, [[1.] * 37])
343
+
344
+
345
+ @torch.no_grad()
346
+ def initialize_from_train(model, sampler, samples=8192, ridge=.1):
347
+ """Train-only maps; free-motion core ridge, isolated-contact residual ridge.
348
+
349
+ No validation statistics, teacher weights, old NRD weights, or old fitted
350
+ normalization are consumed. Contact supervision stays the stored label.
351
+ """
352
+ if any(s["desc"].get("split", "train") != "train" for s in sampler.sources):
353
+ raise ValueError("normalization sampler must be training only")
354
+ state_frame = getattr(model, "state_frame", None)
355
+ if state_frame is not None:
356
+ from types import SimpleNamespace
357
+ from .yaw_frame import FRAME_VERSION, canonicalize_history, to_local
358
+ if state_frame != FRAME_VERSION:
359
+ raise ValueError("Unsupported normalization state frame")
360
+ original_sampler = sampler
361
+
362
+ def canonical_sample(*args, **kwargs):
363
+ batch = original_sampler.sample(*args, **kwargs)
364
+ history, frame = canonicalize_history(batch["hist"], batch["ok"])
365
+ return {**batch, "hist": history, "targets": to_local(batch["targets"], frame)}
366
+
367
+ # Same three draw calls/order/RNG; every fitted map sees local coordinates.
368
+ sampler = SimpleNamespace(sources=original_sampler.sources, sample=canonical_sample)
369
+ b = sampler.sample(samples)
370
+ h, _ = recenter(b["hist"])
371
+ cur, diff, act = h[:, -1, 0], h[:, 1:, 0] - h[:, :-1, 0], b["actions"][:, 0, 0]
372
+ floor = torch.tensor([.01] * 3 + [.01] * 4 + [.01] * 12 + [.05] * 6 + [.1] * 12, device=cur.device)
373
+ mean, std = cur.mean(0), cur.std(0).clamp_min(floor)
374
+ dstd = diff.flatten(0, 1).std(0).clamp_min(floor * .1)
375
+ amean, astd = act.mean(0), act.std(0).clamp_min(.01)
376
+ for net in (model.core, model.collision, model.contact):
377
+ net.in_mean[:, 0] = mean
378
+ net.in_std[:, 0] = std
379
+ net.diff_std[:, 0] = dstd
380
+ net.act_mean[:, 0] = amean
381
+ net.act_std[:, 0] = astd
382
+ delta = b["targets"][:, 0, 0] - b["hist"][:, -1, 0]
383
+ rate_scale = delta[:, 19:].std(0).clamp_min(torch.tensor([.02] * 6 + [.1] * 12, device=cur.device))
384
+ state_scale = std.clone()
385
+ state_scale[:2] = .2
386
+ state_scale[2] = .05
387
+ state_scale[3:7] = .1
388
+ state_scale[7:19] = state_scale[7:19].clamp_min(.1)
389
+ free = sampler.sample(samples, kind="free")
390
+ fh, _ = recenter(free["hist"])
391
+ fc = fh[:, -1, 0]
392
+ fa = free["actions"][:, 0, 0]
393
+ y = free["targets"][:, 0, 0] - free["hist"][:, -1, 0]
394
+
395
+ def fit(x, y, lam):
396
+ ym = y.mean(0)
397
+ eye = torch.eye(x.shape[1], dtype=x.dtype, device=x.device)
398
+ beta = torch.linalg.solve(x.T @ x + lam * eye, x.T @ (y - ym))
399
+ residual = y - ym - x @ beta
400
+ ys = residual.std(0).clamp_min(1e-4)
401
+ return ym, ys, beta / ys
402
+
403
+ x = torch.cat(((fc - mean) / std, (fa - amean) / astd, torch.ones_like(fc[:, :1])), -1)
404
+ ym, ys, beta = fit(x, y, ridge)
405
+ model.core.out_mean[0] = ym
406
+ model.core.out_std[0] = ys
407
+ model.core.lin[0] = beta
408
+ single = sampler.sample(samples, kind="single")
409
+ sh, _ = recenter(single["hist"])
410
+ sc, sd, sl = model.code(sh, single["ok"])
411
+ sa = single["actions"][:, 0]
412
+ dc = model.run_core(sc, sd, sa, sl)
413
+ residual = single["targets"][:, 0] - single["hist"][:, -1] - dc
414
+ counts = []
415
+ for p in range(4):
416
+ sel = single["gates"][:, 0, p].bool()
417
+ count = int(sel.sum())
418
+ counts.append(count)
419
+ model.contact.out_std[p, :37] = delta.std(0).clamp_min(1e-4)
420
+ if count < 32:
421
+ continue
422
+ cc, aa = sc[sel, 0], sa[sel, 0]
423
+ # Contact TokenNet has 2 role slots; the fixed partner is zero padding.
424
+ x = torch.cat(((cc - mean) / std, torch.zeros_like(cc),
425
+ (aa - amean) / astd, torch.zeros_like(aa), torch.ones_like(cc[:, :1])), -1)
426
+ ym, ys, beta = fit(x, residual[sel, 0], ridge)
427
+ model.contact.out_mean[p, :37] = ym
428
+ model.contact.out_std[p, :37] = ys
429
+ model.contact.lin[p, :, :37] = beta
430
+ initialization = {"samples": samples, "single_contact_counts": counts, "normalization_split": "train",
431
+ "core": "free-window ridge", "contact": "single-pair ridge", "history_noise": "none"}
432
+ if state_frame is not None:
433
+ from .yaw_frame import metadata
434
+ initialization["state_frame"] = metadata()
435
+ initialization["draws"] = "Same ordered general/free/single training draws; no extra sampling"
436
+ return dict(rate_scale=rate_scale, state_scale=state_scale, initialization=initialization)
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/ppo_nrdv3_euler.sbatch ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # 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
3
+ # (loader 501c9b8d) + its train-only CRM OOD reference (overlay_nrdv3_ood.json) on one Euler GPU.
4
+ # sbatch -w NODE ppo_nrdv3_euler.sbatch CODE_SNAPSHOT RECIPE.json SEED LABEL
5
+ # Output (durable, NFS, resumable from last.pt): /srv/home/hzhang699/go2nrd/studies/lateral_stuck_20261108/ppo_nrdv3/runs/LABEL
6
+ #SBATCH -J lsp-ppo-nrdv3
7
+ #SBATCH -p research
8
+ #SBATCH --gres=gpu:1
9
+ #SBATCH -c 8
10
+ #SBATCH --mem=24G
11
+ #SBATCH -t 01:00:00
12
+ #SBATCH --signal=B:USR1@180
13
+ #SBATCH -o /srv/home/hzhang699/go2nrd/studies/lateral_stuck_20261108/ppo_nrdv3/logs/%x_%j.out
14
+ set -eo pipefail
15
+ CODE=${1:?code snapshot}; RECIPE=${2:?recipe json name}; SEED=${3:?seed}; LABEL=${4:?label}
16
+ ROOT=/srv/home/hzhang699/go2nrd/studies/lateral_stuck_20261108
17
+ OUT=$ROOT/ppo_nrdv3/runs/$LABEL
18
+ mkdir -p "$OUT" "$ROOT/ppo_nrdv3/logs"
19
+ for P in /scratch/hzhang699/go2nrd_envs/go2eval/bin/python /scratch/hzhang699/envs/go2eval/bin/python; do
20
+ [ -x "$P" ] && PY=$P && break
21
+ done
22
+ [ -n "$PY" ] || { echo "no go2eval python on $(hostname)"; exit 3; }
23
+ export PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 OMP_NUM_THREADS=8 OPENBLAS_NUM_THREADS=1
24
+ export PYTHONPATH=$ROOT/env/ppo_v3_pydeps:$CODE/src
25
+ "$PY" -B - <<'PY'
26
+ import torch, importlib.metadata as m, rsl_rl, tensordict
27
+ assert torch.__version__.startswith('2.12.') and torch.cuda.is_available(), torch.__version__
28
+ assert m.version('rsl-rl-lib') == '5.0.1' and tensordict.__version__ == '0.14.3', (m.version('rsl-rl-lib'), tensordict.__version__)
29
+ x = torch.tensor([2.], device='cuda', requires_grad=True); (x * x).sum().backward(); torch.cuda.synchronize()
30
+ assert x.grad.item() == 4.
31
+ print('torch', torch.__version__, torch.cuda.get_device_name(0), 'rsl-rl-lib 5.0.1', rsl_rl.__file__, flush=True)
32
+ PY
33
+ CHILD=
34
+ trap '[ -z "$CHILD" ] || kill -USR1 "$CHILD" 2>/dev/null || true' USR1 TERM
35
+ cd "$OUT"
36
+ timeout --signal=USR1 --kill-after=60s 3300 "$PY" -B -m go2nrd.fixed_base.ppo_lateral_v3 \
37
+ --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 \
38
+ --seed "$SEED" --output "$OUT" --device cuda --max-seconds 3000 --track P2_ppo_nrdv3 > "$OUT/train_${SLURM_JOB_ID}.log" 2>&1 &
39
+ CHILD=$!
40
+ set +e
41
+ wait "$CHILD"; RC=$?
42
+ if kill -0 "$CHILD" 2>/dev/null; then wait "$CHILD"; RC=$?; fi
43
+ printf '{"job_id":"%s","exit_code":%s,"host":"%s","recipe":"%s","seed":%s,"label":"%s","code":"%s"}\n' \
44
+ "$SLURM_JOB_ID" "$RC" "$(hostname)" "$RECIPE" "$SEED" "$LABEL" "$CODE" > "$OUT/job_${SLURM_JOB_ID}.json"
45
+ tail -3 "$OUT/train_${SLURM_JOB_ID}.log"
46
+ exit "$RC"
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/recipes/overlay_nrdv3_ood.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "nrdv3_FRESHb_ood_reference_v1",
3
+ "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.",
4
+ "ood": {
5
+ "reference_file": {
6
+ "crm": "@ood_ref_crm"
7
+ }
8
+ }
9
+ }
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/recipes/v2.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "v3_V2",
3
+ "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).",
4
+ "env": {
5
+ "branch_s_lateral": 4.0,
6
+ "commands": {
7
+ "lateral_mix": {
8
+ "lateral": 0.5,
9
+ "diagonal": 0.15,
10
+ "vy": [
11
+ 0.2,
12
+ 0.5
13
+ ],
14
+ "lateral_vx": 0.1,
15
+ "wz": 0.15,
16
+ "diag_vx": [
17
+ 0.2,
18
+ 0.5
19
+ ],
20
+ "diag_forward_fraction": 0.6,
21
+ "sign_from_start": true,
22
+ "sign_min_vy": 0.15
23
+ }
24
+ },
25
+ "start": {
26
+ "groups": {
27
+ "file": "@start_groups",
28
+ "share": {
29
+ "stuck_drag": 0.15,
30
+ "stuck": 0.15,
31
+ "soft": 0.15,
32
+ "other": 0.55
33
+ },
34
+ "grounds": [
35
+ "crm"
36
+ ]
37
+ }
38
+ }
39
+ },
40
+ "rewards": {
41
+ "anchor": {
42
+ "command_scale": {
43
+ "lateral": 0.2,
44
+ "other": 1.0,
45
+ "vy_min": 0.2
46
+ }
47
+ },
48
+ "terms": {
49
+ "ood": {
50
+ "weight": -1.0,
51
+ "dt_scale": false
52
+ }
53
+ },
54
+ "gait_terms": {
55
+ "swing_peak": {
56
+ "weight": -6.0,
57
+ "target_m": 0.08
58
+ },
59
+ "foot_drag": {
60
+ "weight": -20.0
61
+ },
62
+ "lateral_shortfall": {
63
+ "weight": -1.0,
64
+ "vy_min": 0.2
65
+ }
66
+ }
67
+ },
68
+ "ppo": {
69
+ "std_max": 0.2
70
+ }
71
+ }
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/eval/export_onnx.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export an rsl_rl 5.0.1 checkpoint of the mjlab Go2 actor layout into a deploy folder (policy.onnx + config.yaml).
2
+
3
+ New code (judges worker, 2026-10-30). The deploy format is the one of
4
+ ``legged_rl_deploy_push/policies/go2/unitree_rl_mjlab/velocity/policy.onnx`` (mjlab's own export of model_10000.pt,
5
+ sha256 c58a3494...): the actor's observation normaliser ``(obs - mean) / (std + 0.01)`` followed by the
6
+ 47-512-256-128-12 ELU MLP, the deterministic mean as output; input ``obs`` float32 [1, 47], output ``actions`` float32
7
+ [1, 12]; opset 18; static shapes; one file; ops Sub, Div, Gemm, Elu, Gemm, Elu, Gemm, Elu, Gemm; initializers
8
+ ``obs_normalizer._mean``, ``mlp.{0,2,4,6}.{weight,bias}`` and the folded ``std + eps``; mjlab's metadata
9
+ (``run_path``, ``joint_names``, ``joint_stiffness``, ``joint_damping``, ``default_joint_pos``, ``command_names``,
10
+ ``observation_names``, ``action_scale``). Method: the ``state_dict`` path of the reference exporter
11
+ (legged_rl_deploy/policies/go2/unitree_rl_mjlab/velocity/export_onnx.py): rebuild the actor from ``actor_state_dict``
12
+ (strict load into :class:`go2nrd.policy.mjlab_policy.MjlabActor`, the rsl_rl 5.0.1 key layout), ``torch.onnx.export``
13
+ with the same arguments (``dynamo=False``), metadata copied from the reference ONNX with ``run_path`` set to the new
14
+ run's name. None of the copied fields depends on the iteration; the fine-tune keeps the joint order, gains, defaults,
15
+ observation and action scale (the export refuses a checkpoint whose layout differs).
16
+
17
+ Outputs in ``--out``: ``policy.onnx``; ``config.yaml`` = the mjlab deploy config (``--template``) with ``model_path``
18
+ set to the absolute path of the new ONNX and a provenance comment; ``policy_export.json`` (checkpoint sha256 /
19
+ iteration, the ONNX description, the structure check against the reference, the torch-vs-ONNX verification).
20
+
21
+ Run (env ``go2eval``: torch 2.12, onnx 1.22, onnxruntime 1.30; or env ``unitree_rl_mjlab``, then the check uses
22
+ ``onnx.reference``)::
23
+
24
+ PYTHONPATH=/home/harry/go2_sand/nrd/src python -B -m go2nrd.eval.export_onnx --checkpoint RUN/model_X.pt \\
25
+ --out /home/harry/go2_sand/nrd_data/eval/policies/<name> [--run-name NAME]
26
+
27
+ Then ``python -m go2nrd.eval.parity --folder OUT`` (env go2eval) checks it against legged_sim_eval's DeployPolicy on
28
+ recorded observations.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import datetime as _dt
34
+ import hashlib
35
+ import io
36
+ import json
37
+ import os
38
+ import sys
39
+ import tempfile
40
+ from pathlib import Path
41
+
42
+ import numpy as np
43
+
44
+ REFERENCE_ONNX = Path("/home/harry/go2_sand/legged_rl_deploy_push/policies/go2/unitree_rl_mjlab/velocity/policy.onnx")
45
+ REFERENCE_SHA256 = "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45"
46
+ TEMPLATE_CONFIG = Path("/home/harry/go2_sand/legged_rl_deploy/policies/go2/unitree_rl_mjlab/velocity/config.yaml")
47
+ OBS_DIM, ACT_DIM, OPSET = 47, 12, 18
48
+ FIXED_METADATA = ("joint_names", "joint_stiffness", "joint_damping", "default_joint_pos", "command_names",
49
+ "observation_names", "action_scale")
50
+
51
+
52
+ def sha256_bytes(b: bytes) -> str:
53
+ return hashlib.sha256(b).hexdigest()
54
+
55
+
56
+ def load_actor(ckpt_path: Path):
57
+ """(MjlabActor in eval mode on the CPU, checkpoint description). Strict load: the layout must be the mjlab one."""
58
+ import torch
59
+
60
+ from go2nrd.policy.mjlab_policy import MjlabActor
61
+
62
+ data = Path(ckpt_path).read_bytes()
63
+ ckpt = torch.load(io.BytesIO(data), map_location="cpu", weights_only=False)
64
+ if isinstance(ckpt, dict) and "actor_state_dict" not in ckpt and "obs_normalizer._mean" in ckpt:
65
+ ckpt = {"actor_state_dict": ckpt, "iter": -1} # a bare actor state_dict (same keys)
66
+ if not isinstance(ckpt, dict) or "actor_state_dict" not in ckpt:
67
+ raise ValueError(f"{ckpt_path}: not an rsl_rl 5 checkpoint (no actor_state_dict)")
68
+ actor = MjlabActor()
69
+ actor.load_state_dict(ckpt["actor_state_dict"], strict=True)
70
+ actor = actor.float().eval()
71
+ for p in actor.parameters():
72
+ p.requires_grad_(False)
73
+ infos = ckpt.get("infos") or {}
74
+ desc = dict(file=str(Path(ckpt_path).resolve()), sha256=sha256_bytes(data), size_bytes=len(data),
75
+ iteration=int(ckpt.get("iter", -1)),
76
+ common_step_counter=(infos.get("env_state") or {}).get("common_step_counter"),
77
+ actor_normaliser_count=int(ckpt["actor_state_dict"]["obs_normalizer.count"]),
78
+ std=[float(x) for x in ckpt["actor_state_dict"]["distribution.std_param"]])
79
+ return actor, desc
80
+
81
+
82
+ def describe_onnx(path: Path) -> dict:
83
+ import onnx
84
+ from onnx import numpy_helper
85
+
86
+ m = onnx.load(str(path), load_external_data=False)
87
+ 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
88
+ inits = {i.name: list(numpy_helper.to_array(i).shape) for i in m.graph.initializer}
89
+ return dict(file=str(path), sha256=sha256_bytes(Path(path).read_bytes()), size_bytes=Path(path).stat().st_size,
90
+ opset=[int(o.version) for o in m.opset_import if o.domain in ("", "ai.onnx")],
91
+ inputs={i.name: shape(i) for i in m.graph.input}, outputs={o.name: shape(o) for o in m.graph.output},
92
+ ops=[n.op_type for n in m.graph.node], initializers=inits,
93
+ dtypes={i.name: int(i.type.tensor_type.elem_type) for i in [*m.graph.input, *m.graph.output]},
94
+ external_data=any(t.data_location == onnx.TensorProto.EXTERNAL for t in m.graph.initializer),
95
+ metadata={p.key: p.value for p in m.metadata_props}, ir_version=int(m.ir_version))
96
+
97
+
98
+ def structure_check(new: dict, ref: dict) -> dict:
99
+ """The new ONNX has the reference's IO names / shapes / dtypes, opset, op list, initializer shapes (by role)
100
+ and metadata keys (and the fixed metadata values)."""
101
+ shapes_new = sorted(map(tuple, new["initializers"].values()))
102
+ shapes_ref = sorted(map(tuple, ref["initializers"].values()))
103
+ named = [k for k in ref["initializers"] if not k.startswith("onnx::")]
104
+ checks = dict(
105
+ inputs=new["inputs"] == ref["inputs"], outputs=new["outputs"] == ref["outputs"], dtypes=new["dtypes"] == ref["dtypes"],
106
+ opset=new["opset"] == ref["opset"], ops=new["ops"] == ref["ops"], initializer_shapes=shapes_new == shapes_ref,
107
+ initializer_names=all(new["initializers"].get(k) == ref["initializers"][k] for k in named),
108
+ metadata_keys=sorted(new["metadata"]) == sorted(ref["metadata"]),
109
+ metadata_fixed_values=all(new["metadata"].get(k) == ref["metadata"][k] for k in FIXED_METADATA),
110
+ single_file=not new["external_data"])
111
+ return dict(checks=checks, ok=bool(all(checks.values())))
112
+
113
+
114
+ def export(actor, out: Path, metadata: dict) -> None:
115
+ import onnx
116
+ import torch
117
+
118
+ fd, tmp = tempfile.mkstemp(prefix=".policy_", suffix=".onnx", dir=out.parent)
119
+ os.close(fd)
120
+ torch.onnx.export(actor, (torch.zeros(1, OBS_DIM),), tmp, export_params=True, opset_version=OPSET,
121
+ input_names=["obs"], output_names=["actions"], dynamic_axes={}, dynamo=False)
122
+ model = onnx.load(tmp)
123
+ del model.metadata_props[:]
124
+ for k, v in metadata.items():
125
+ e = onnx.StringStringEntryProto()
126
+ e.key, e.value = k, v
127
+ model.metadata_props.append(e)
128
+ onnx.checker.check_model(model)
129
+ onnx.save(model, tmp)
130
+ os.chmod(tmp, 0o644)
131
+ os.replace(tmp, out)
132
+
133
+
134
+ def onnx_runner(path: Path):
135
+ """(fn obs [n, 47] -> [n, 12] row by row (static batch 1, as the deploy), evaluator name)."""
136
+ try:
137
+ import onnxruntime as ort
138
+
139
+ so = ort.SessionOptions()
140
+ so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
141
+ so.intra_op_num_threads = 1
142
+ sess = ort.InferenceSession(str(path), sess_options=so, providers=["CPUExecutionProvider"])
143
+ fn = lambda obs: np.concatenate([sess.run(None, {"obs": r[None]})[0] for r in obs.astype(np.float32)]) # noqa: E731
144
+ return fn, f"onnxruntime {ort.__version__} (CPU, ORT_ENABLE_BASIC, 1 thread)"
145
+ except ImportError:
146
+ import onnx
147
+ from onnx.reference import ReferenceEvaluator
148
+
149
+ ev = ReferenceEvaluator(str(path))
150
+ fn = lambda obs: np.concatenate([ev.run(None, {"obs": r[None]})[0] for r in obs.astype(np.float32)]) # noqa: E731
151
+ return fn, f"onnx.reference {onnx.__version__}"
152
+
153
+
154
+ def verify(path: Path, actor, n: int = 1000, seed: int = 0, extra_obs: np.ndarray | None = None) -> dict:
155
+ """max |ONNX - torch actor| on N(0, 1), normaliser mean + std N(0, 1) and (optional) recorded observations."""
156
+ import torch
157
+
158
+ fn, evaluator = onnx_runner(path)
159
+ rng = np.random.default_rng(seed)
160
+ mean = actor.obs_normalizer._mean.numpy().reshape(-1).astype(np.float64)
161
+ std = actor.obs_normalizer._std.numpy().reshape(-1).astype(np.float64)
162
+ sets = {"random": rng.standard_normal((n, OBS_DIM)).astype(np.float32),
163
+ "realistic": (mean + std * rng.standard_normal((n, OBS_DIM))).astype(np.float32)}
164
+ if extra_obs is not None:
165
+ sets["recorded"] = np.asarray(extra_obs, np.float32)
166
+ res = dict(evaluator=evaluator, n_per_set={k: int(len(v)) for k, v in sets.items()}, seed=seed, max_abs_diff={})
167
+ for name, obs in sets.items():
168
+ with torch.no_grad():
169
+ y_t = actor(torch.from_numpy(obs)).numpy()
170
+ y_o = fn(obs)
171
+ res["max_abs_diff"][name] = float(np.abs(y_o - y_t).max())
172
+ res["max_abs_diff"][f"{name}/max_abs_action"] = float(np.abs(y_o).max())
173
+ res["max_onnx_vs_torch"] = max(v for k, v in res["max_abs_diff"].items() if "/" not in k)
174
+ return res
175
+
176
+
177
+ def config_text(template: Path, model_path: Path, provenance: str) -> str:
178
+ lines = template.read_text().splitlines()
179
+ out, n = [], 0
180
+ for ln in lines:
181
+ if ln.strip().startswith("model_path:"):
182
+ ind = ln[: len(ln) - len(ln.lstrip())]
183
+ out.append(f"{ind}# go2nrd.eval.export_onnx: {provenance}")
184
+ ln = f"{ind}model_path: {model_path}"
185
+ n += 1
186
+ out.append(ln)
187
+ if n != 1:
188
+ raise ValueError(f"{template}: expected one model_path line, found {n}")
189
+ return "\n".join(out) + "\n"
190
+
191
+
192
+ def recorded_obs(n: int = 2048, seed: int = 0) -> np.ndarray | None:
193
+ """Policy observations recorded in mjlab (rigid_test raw shard 0, the mjlab collector), n rows at random."""
194
+ shard = Path("/home/harry/go2_sand/nrd_data/raw/rigid_test/rigid_test_s0000.npz")
195
+ if not shard.exists():
196
+ return None
197
+ from go2nrd.collect.common.contract import load_raw_shard
198
+
199
+ eps, _ = load_raw_shard(shard)
200
+ obs = np.concatenate([e.obs for e in eps])
201
+ obs = obs[np.isfinite(obs).all(1)]
202
+ return obs[np.random.default_rng(seed).choice(len(obs), min(n, len(obs)), replace=False)]
203
+
204
+
205
+ def main(argv=None) -> int:
206
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
207
+ ap.add_argument("--checkpoint", required=True, help="rsl_rl 5.0.1 model_<it>.pt with actor_state_dict")
208
+ ap.add_argument("--out", required=True, help="deploy folder to write (policy.onnx, config.yaml, policy_export.json)")
209
+ ap.add_argument("--run-name", default=None, help="metadata run_path (default: the checkpoint's folder name)")
210
+ ap.add_argument("--reference", default=str(REFERENCE_ONNX), help="reference deploy ONNX (metadata + structure)")
211
+ ap.add_argument("--template", default=str(TEMPLATE_CONFIG), help="deploy config.yaml template")
212
+ ap.add_argument("--atol", type=float, default=1e-4)
213
+ args = ap.parse_args(argv)
214
+ out = Path(args.out).resolve()
215
+ out.mkdir(parents=True, exist_ok=True)
216
+ ref = Path(args.reference)
217
+ ref_desc = describe_onnx(ref)
218
+ actor, ck = load_actor(Path(args.checkpoint))
219
+ run_name = args.run_name or Path(args.checkpoint).resolve().parent.name
220
+ metadata = dict(ref_desc["metadata"])
221
+ metadata["run_path"] = run_name
222
+ onnx_path = out / "policy.onnx"
223
+ export(actor, onnx_path, metadata)
224
+ desc = describe_onnx(onnx_path)
225
+ struct = structure_check(desc, ref_desc)
226
+ check = verify(onnx_path, actor, extra_obs=recorded_obs())
227
+ prov = f"{Path(args.checkpoint).resolve()} (iteration {ck['iteration']}, sha256 {ck['sha256'][:16]}...)"
228
+ (out / "config.yaml").write_text(config_text(Path(args.template), onnx_path, prov))
229
+ import onnx
230
+ import torch
231
+ record = dict(exporter="go2nrd.eval.export_onnx", method="state_dict (MjlabActor strict load, torch.onnx.export "
232
+ "opset 18, dynamo=False, static [1, 47]; metadata copied from the reference, run_path replaced)",
233
+ checkpoint=ck, run_path=run_name, exported_at=_dt.datetime.now().isoformat(timespec="seconds"),
234
+ python=sys.executable, versions=dict(torch=torch.__version__, onnx=onnx.__version__, numpy=np.__version__),
235
+ reference=dict(file=str(ref), sha256=ref_desc["sha256"], is_mjlab_export=ref_desc["sha256"] == REFERENCE_SHA256),
236
+ onnx=desc, structure=struct, verification=check,
237
+ config=dict(file=str(out / "config.yaml"), template=str(args.template),
238
+ template_sha256=sha256_bytes(Path(args.template).read_bytes())))
239
+ (out / "policy_export.json").write_text(json.dumps(record, indent=1) + "\n")
240
+ print(json.dumps(dict(onnx=str(onnx_path), sha256=desc["sha256"], structure=struct, verification=check), indent=1))
241
+ ok = struct["ok"] and check["max_onnx_vs_torch"] <= args.atol
242
+ print(f"[export_onnx] {'OK' if ok else 'FAILED'} -> {out}")
243
+ return 0 if ok else 1
244
+
245
+
246
+ if __name__ == "__main__":
247
+ sys.exit(main())
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/fixed_base/ppo_lateral_v3.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PPO v3 entrypoint (lateral_stuck_20261108 track B): the PPO71/72 recipe in the same frozen NRD with a recipe overlay.
2
+
3
+ Base = the exact executed PPO71 config (runs/fixed_base_20261102/ppo/horizon_h50_u13500_s61_p71_diagnostic_v1/
4
+ config.json: start rows, 1024 envs, rewards, OOD reference, PPO settings). Only paths are remapped to the host
5
+ (data dirs by basename, NRD member, teacher = init checkpoint = anchor reference) and the overlay is deep-merged
6
+ (dicts merged, other values replaced; "@start_groups" -> paths.start_groups). An empty overlay reproduces PPO71's
7
+ recipe (tested against the original runtime capsule: tests in studies/lateral_stuck_20261108/ppo_v3).
8
+
9
+ Checks: NRD sha256 5c33043b... (seed61 H50 u13500 frame+short), teacher sha256 7ee303f9...; NRD weights frozen
10
+ (tensor digest before / after), actor normaliser unchanged, consumed OOD reference unchanged (ppo_study helpers).
11
+ Outputs (RUN): config.json, recipe.json (overlay + lateral_v3 description), start.json, metrics.jsonl, model_*.pt,
12
+ last.pt, complete.json, frozen_audit.json, policy.onnx (runner export). Re-running the same command resumes.
13
+
14
+ python -m go2nrd.fixed_base.ppo_lateral_v3 --base BASE_CONFIG.json --recipe RECIPE.json --paths PATHS.json \
15
+ --seed 81 --output RUN [--device cuda] [--max-seconds S]
16
+
17
+ Track P2 options (lateral_stuck_20261108 ppo_nrdv3; default off, the commands above are unchanged bit for bit):
18
+ --nrd-sha256 SHA the expected sha256 of paths.nrd (default the seed61 NRD 5c33043b...), e.g. the retrained NRD
19
+ nrd_v3 FRESH-b loader export 501c9b8d...; recorded as lineage nrd_sha256.
20
+ --overlay FILE an NRD-arm overlay JSON deep-merged AFTER the recipe ("@key" -> paths[key]), e.g. the train-only
21
+ OOD reference of that NRD (ood.reference_file); recorded as lineage overlay / overlay_sha256.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import copy
27
+ import json
28
+ import os
29
+ import threading
30
+ import time
31
+ from pathlib import Path
32
+
33
+ import torch
34
+
35
+ from .data import sha256_file
36
+ from .ppo_study import TEACHER_SHA, capture_ood_reference, tensor_digest
37
+ from go2nrd.rl.config import strip_comments
38
+ from go2nrd.rl.runner import FineTuneRunner, write_config
39
+
40
+ NRD_SHA = "5c33043b55951658d3bc2ccce0f442124218f2a5c294d8ae6a7f8c0affcd5bbe"
41
+
42
+
43
+ def deep_merge(base, over):
44
+ out = copy.deepcopy(base)
45
+ for k, v in over.items():
46
+ if k.startswith("_"):
47
+ continue
48
+ if isinstance(v, dict) and isinstance(out.get(k), dict):
49
+ out[k] = deep_merge(out[k], v)
50
+ else:
51
+ out[k] = copy.deepcopy(v)
52
+ return out
53
+
54
+
55
+ def substitute(x, table):
56
+ if isinstance(x, dict):
57
+ return {k: substitute(v, table) for k, v in x.items()}
58
+ if isinstance(x, list):
59
+ return [substitute(v, table) for v in x]
60
+ if isinstance(x, str) and x.startswith("@"):
61
+ return table[x[1:]]
62
+ return x
63
+
64
+
65
+ def build_config(base, recipe, paths, seed):
66
+ cfg = copy.deepcopy(base)
67
+ cfg.pop("fixed_base_lineage", None)
68
+ data = paths["data"]
69
+ cfg["data"] = [dict(d, dir=data[Path(d["dir"]).name]) for d in cfg["data"]]
70
+ cfg["nrd"]["members"] = [paths["nrd"]]
71
+ cfg["init_checkpoint"] = paths["teacher"]
72
+ cfg["rewards"]["anchor"]["reference"] = paths["teacher"]
73
+ over = substitute({k: v for k, v in recipe.items() if k not in ("name", "description")}, paths)
74
+ cfg = deep_merge(cfg, over)
75
+ cfg["seed"] = int(seed)
76
+ return strip_comments(cfg)
77
+
78
+
79
+ class V3Runner(FineTuneRunner):
80
+ def _infos(self):
81
+ return dict(super()._infos(), lateral_v3_lineage=self.cfg.get("lateral_v3_lineage"))
82
+
83
+
84
+ def main():
85
+ p = argparse.ArgumentParser(description=__doc__)
86
+ p.add_argument("--base", type=Path, required=True)
87
+ p.add_argument("--recipe", type=Path, required=True)
88
+ p.add_argument("--paths", type=Path, required=True)
89
+ p.add_argument("--seed", type=int, required=True)
90
+ p.add_argument("--output", type=Path, required=True)
91
+ p.add_argument("--device", default="cuda")
92
+ p.add_argument("--max-seconds", type=float, default=None, help="stop (save last.pt) after this many seconds")
93
+ p.add_argument("--skip-sha", action="store_true", help="tests only: do not check NRD / teacher hashes")
94
+ p.add_argument("--max-iterations", type=int, default=None, help="smoke: override runner.max_iterations")
95
+ p.add_argument("--warmup", type=int, default=None, help="smoke: override runner.warmup_iterations")
96
+ p.add_argument("--track", default="B_ppo", help="lineage track label (default B_ppo, the Track B runs)")
97
+ p.add_argument("--nrd-sha256", default=NRD_SHA, help="expected sha256 of paths.nrd (default seed61 5c33043b...)")
98
+ p.add_argument("--overlay", type=Path, default=None, help="NRD-arm overlay JSON merged after the recipe")
99
+ a = p.parse_args()
100
+ base = json.loads(a.base.read_text())
101
+ recipe = json.loads(a.recipe.read_text())
102
+ paths = json.loads(a.paths.read_text())
103
+ if not a.skip_sha:
104
+ if sha256_file(paths["teacher"]) != TEACHER_SHA:
105
+ raise ValueError("teacher checkpoint changed")
106
+ if sha256_file(paths["nrd"]) != a.nrd_sha256:
107
+ raise ValueError(f"NRD checkpoint sha256 is not {a.nrd_sha256[:8]}... (default: seed61 H50 u13500 5c33043b...)")
108
+ cfg = build_config(base, recipe, paths, a.seed)
109
+ overlay = None
110
+ if a.overlay is not None: # Track P2: NRD-arm overlay after the recipe
111
+ overlay = json.loads(a.overlay.read_text())
112
+ cfg = strip_comments(deep_merge(cfg, substitute({k: v for k, v in overlay.items()
113
+ if k not in ("name", "description")}, paths)))
114
+ if a.max_iterations is not None:
115
+ cfg["runner"]["max_iterations"] = a.max_iterations
116
+ if a.warmup is not None:
117
+ cfg["runner"]["warmup_iterations"] = a.warmup
118
+ cfg["lateral_v3_lineage"] = dict(study="lateral_stuck_20261108", track=a.track, recipe=recipe.get("name"),
119
+ recipe_sha256=sha256_file(a.recipe), base_config_sha256=sha256_file(a.base),
120
+ nrd_sha256=a.nrd_sha256, teacher_sha256=TEACHER_SHA, original47_actor=True,
121
+ training="PPO inside frozen NRD", final_eligible=False)
122
+ if overlay is not None:
123
+ cfg["lateral_v3_lineage"].update(overlay=overlay.get("name"), overlay_sha256=sha256_file(a.overlay))
124
+ a.output.mkdir(parents=True, exist_ok=True)
125
+ existing = a.output / "config.json"
126
+ if existing.exists() and json.loads(existing.read_text()) != json.loads(json.dumps(cfg)):
127
+ raise ValueError("resume configuration changed; use a new output directory")
128
+ write_config(cfg, a.output)
129
+ if (a.output / "complete.json").exists():
130
+ print("already complete")
131
+ return
132
+ t0 = time.time()
133
+ runner = V3Runner(cfg, a.output, a.device)
134
+ env = runner.env
135
+ rec = dict(recipe=recipe, v3=env.v3.describe() if env.v3 is not None else None,
136
+ host=os.uname().nodename, torch=torch.__version__,
137
+ gpu=torch.cuda.get_device_name(0) if torch.cuda.is_available() else None)
138
+ (a.output / "recipe.json").write_text(json.dumps(rec, indent=1) + "\n")
139
+ frozen = env.sim.models
140
+ if any(q.requires_grad for m in frozen for q in m.parameters()):
141
+ raise AssertionError("dynamics parameters are not frozen")
142
+ before = tensor_digest(frozen)
143
+ norm_before = {k: v.clone() for k, v in runner.actor.state_dict().items() if k.startswith("obs_normalizer.")}
144
+ ood_before = capture_ood_reference(env, a.output)
145
+ if a.max_seconds:
146
+ def stop_later():
147
+ time.sleep(max(1.0, a.max_seconds - (time.time() - t0)))
148
+ runner._stop = True
149
+ print(f"[max-seconds] {a.max_seconds:.0f} s reached: stop after this iteration", flush=True)
150
+ threading.Thread(target=stop_later, daemon=True).start()
151
+ result = runner.learn()
152
+ after = tensor_digest(frozen)
153
+ norm_ok = all(torch.equal(v, runner.actor.state_dict()[k]) for k, v in norm_before.items())
154
+ audit = dict(reason=result, nrd_before_sha256=before, nrd_after_sha256=after, unchanged=before == after,
155
+ teacher_actor_normalization_unchanged=norm_ok,
156
+ ood_reference=capture_ood_reference(env, a.output), lineage=cfg["lateral_v3_lineage"],
157
+ wall_s=time.time() - t0)
158
+ if audit["ood_reference"] != ood_before:
159
+ raise AssertionError("consumed OOD reference changed")
160
+ (a.output / "frozen_audit.json").write_text(json.dumps(audit, indent=2) + "\n")
161
+ if before != after or not norm_ok:
162
+ raise AssertionError("frozen dynamics or original actor normalization changed")
163
+
164
+
165
+ if __name__ == "__main__":
166
+ main()
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/env.py ADDED
@@ -0,0 +1,898 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Go2NrdVecEnv: the rsl_rl 5.0.1 VecEnv of the fine-tune, around go2nrd.sim (Go2NrdSim + NrdPolicyLoop + StartBank).
2
+
3
+ New code (go2nrd PPO worker, 2026-10-30). One env step = one policy step = one 20 ms NRD step.
4
+
5
+ Starts: recorded K-state NRD histories (20 ms step-average rates; K = the NRD's history, sim.k: 4 for the contract
6
+ models) of the training split (StartBank(history=K), default task families nominal + difficult, k >= K - 1 (env.start
7
+ min_k, raised to K - 1 if lower: 3 for K = 4, as before) so the history is full and the last raw action is the
8
+ recorded one, review D8),
9
+ with the recorded phase counter k, last raw action, collision switches and air time. Environments are split into
10
+ one block per ground present in the data (rigid / CRM: equal shares when both exist), and inside a block into
11
+ sub-blocks per NRD member serving that ground; each block always restarts from its own ground's starts. The ground
12
+ id (and, for a sim that takes them, the per-start continuous ground features) goes to the NRD.
13
+ Commands: per branch, with probability recorded_fraction the recorded command stream of the start's episode
14
+ (command[2 (k0 + t)], held after the recording ends); otherwise uniform in the evaluation envelope (vx [-0.5, 1],
15
+ vy [-0.5, 0.5], wz [-1, 1]) with standing_fraction zero commands, resampled once at a random step of the branch.
16
+ commands.vx_draw "balanced" (reward set C): vx of an envelope draw is forward (U[0, vx_hi]) with probability
17
+ forward_fraction (default 0.5), else backward (U[vx_lo, 0]); vy, wz stay uniform (sample_envelope).
18
+ Branches: branch_s seconds (default 5 s = 250 steps); the first branch of each env has a random length (staggered
19
+ time-outs); time-outs are bootstrapped with V(final observation) (extras["final_obs"], FineTunePPO).
20
+ Terminations (model rules): base z < 0.15 m or tilt > 45 deg, non-finite NRD output; reward term `termination`.
21
+ Observations: TensorDict(actor [n, 47] = go2nrd.policy.obs actor terms + mjlab's training noise (uniform additive,
22
+ env.yaml: gyro 0.2, gravity 0.05, joint pos 0.01, joint vel 1.5; off in eval), critic [n, 74] clean, contact forces
23
+ filled by force_fill (default "contact_mean", build_nrd_step.md section 5)).
24
+ Logging: per-ground sums kept on the device (no host sync per step); pop_log() at the end of an iteration.
25
+ Labels (labels_base, 2026-11-01): the start banks take contact_prev / gate_prev / air time from the config's
26
+ "labels" (top level, or per data entry {"dir": D, "labels": FILE}; a go2nrd.labels override of that data dir; none
27
+ = the stored contacts, as before). check_labels refuses a bank whose label rule_id differs from the training labels
28
+ of the NRD members (env.labels_check false to allow it). The config (with the labels) is saved in RUN/config.json.
29
+
30
+ Round-1 exploitation options (ppo_anchor worker, 2026-10-30; all default off, arms A-D unchanged bit for bit):
31
+ rewards.anchor {weight, grounds ["crm"], mode "centered" | "sample", dt_scale true, reference null}: action anchor
32
+ 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",
33
+ default) or |a - a_ref|^2 ("sample"); a = the raw (sampled) action, mu = the acting policy's mean of this step
34
+ (set by the runner in env.action_mean; a if not given), a_ref = the frozen reference actor's mean (rsl_rl
35
+ MLPModel, weights of `reference` or init_checkpoint) on the SAME noisy actor observation. E[A] = |mu - a_ref|^2
36
+ in both modes; "centered" is exactly 0 while mu = a_ref (iteration 0, critic warm-up) and has no gradient on
37
+ the action std (the "sample" form also pays the exploration noise 12 std^2).
38
+ env.start.crm_bin_share {soft, medium, firm} (or a list in that order): CRM starts drawn by soil bin to these
39
+ shares (bin chosen first, then a uniform start of that bin); bins = the nrdeval rule on the start episode's
40
+ ground features (soft: cohesion < 250 Pa and friction < 0.7; firm: cohesion > 1500 Pa; medium: the rest).
41
+ env.log_soil_bins (default: on when either option above is on): per-soil-bin logs of the CRM block.
42
+ The termination penalty is rewards.terms.termination.weight (x dt; -10 = -0.2 per model-rule termination).
43
+
44
+ Soft-soil robustness options (arm ppo_soft worker, 2026-10-31; nrd/reports/arm_ppo_soft.md; all default off, arms A-E
45
+ unchanged bit for bit):
46
+ env.disturb {grounds, bin_scale, kicks {...}, lean {...}}: (a) Poisson base roll / pitch-rate kicks and (b) sustained
47
+ roll (/ pitch) rate-bias windows of 0.5-3 s ("sinking side") added to the NRD's predicted base angular rate on
48
+ the envs of `grounds` (default CRM), with the quaternion re-integrated by the NRD's own rule (go2nrd.rl.disturb).
49
+ The rewards, terminations and the next NRD step see the disturbed state. Logged per soil bin (crm.disturb).
50
+ ood.threshold {family "nominal", quantile 0.99, scale 1, value null, grounds null}: (c) the out-of-corpus threshold
51
+ of each ground's kNN reference = the quantile of the leave-one-out mean kNN distance of the reference draw's rows
52
+ 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
53
+ fixed value; ood.ground_weight {rigid, crm}: per-ground multiplier of the OOD cost (the term weight stays
54
+ rewards.terms.ood.weight).
55
+ ood.reference_file {ground: npz} (lateral_stuck_20261108 track P2, default off): (d) the kNN reference draw rows of
56
+ that ground come from a precomputed file (feat [M, 45], family [M], family_names) instead of the start pool,
57
+ e.g. the train-only corpus of a retrained NRD; whitening, reference points, stock and family thresholds are then
58
+ computed from these rows by the same code (Go2NrdVecEnv._reference_rows).
59
+ rewards.anchor.ground_weight {rigid, crm}: per-ground multiplier of the anchor weight w on the anchored grounds
60
+ (e.g. grounds ["rigid", "crm"], ground_weight {"rigid": 3}: rigid envs priced 3 w; keeps the gait on rigid-ground
61
+ states near the reference while the CRM envs learn the lean response).
62
+
63
+ Lateral-sand recipe options (lateral_stuck_20261108 track B, "PPO v3"; go2nrd.rl.lateral_v3; all default off,
64
+ every earlier config unchanged bit for bit): env.commands.lateral_mix (lateral / diagonal command draws inside the
65
+ deploy clip), env.branch_s_lateral (longer lateral branches), env.start.groups (start-pool weighting, e.g. toward
66
+ the STUCK CRM starts), rewards.anchor.command_scale (anchor weight by command), rewards.gait_terms (swing_peak,
67
+ foot_drag, lateral_shortfall). See the module docstring of go2nrd.rl.lateral_v3.
68
+
69
+ Everything runs under torch.inference_mode (buffers are inference tensors).
70
+ """
71
+ from __future__ import annotations
72
+
73
+ import inspect
74
+ import io
75
+ import math
76
+ from pathlib import Path
77
+
78
+ import torch
79
+ from tensordict import TensorDict
80
+
81
+ from rsl_rl.env import VecEnv
82
+
83
+ from go2nrd.collect.common import contract as C
84
+ from go2nrd.nrdeval.common import FIRM_COHESION_PA, SOFT_COHESION_PA, SOFT_FRICTION
85
+ from go2nrd.policy.obs import ACTOR
86
+ from go2nrd.rl import lateral_v3
87
+ from go2nrd.rl.disturb import RateDisturbance, apply_rate_perturbation, heading_rates
88
+ from go2nrd.rl.ood import CorpusReference, GroundOOD, ood_features
89
+ from go2nrd.rl.rewards import RewardTerms, tilt_terminated, total_command
90
+ from go2nrd.sim.bank import StartBank
91
+ from go2nrd.sim.loop import NrdPolicyLoop
92
+ from go2nrd.sim.nrd_sim import Go2NrdSim, MemberLayout
93
+
94
+ GROUND_NAMES = {v: k for k, v in C.GROUND_IDS.items()} # 0 rigid, 1 crm
95
+ NOISE_COLS = dict(base_ang_vel=ACTOR["base_ang_vel"], projected_gravity=ACTOR["projected_gravity"],
96
+ joint_pos=ACTOR["joint_pos"], joint_vel=ACTOR["joint_vel"])
97
+ LOG_KEYS = ("steps", "reward", "track_err_vx", "track_err_vy", "track_err_wz", "track_steps", "power_w",
98
+ "tau_sat_frac", "tau_085_frac", "tau_peak_rel", "ood_cost", "ood_active", "ood_knn", "ood_cost_all",
99
+ "terminated",
100
+ "fell", "nonfinite", "time_out", "ends", "contact_duty",
101
+ "roll_abs", "pitch_abs", "roll_abs_lat", "lat_steps")
102
+ LATERAL_VY = 0.2 # "lateral" envs for the in-NRD lean signal (vx_diag.md 1b): |cmd vy| >= 0.2, settled
103
+ SOIL_BINS = ("soft", "medium", "firm")
104
+ BIN_LOG_KEYS = ("steps", "reward", "track_err_vx", "track_err_vy", "track_err_wz", "track_steps", "power_w",
105
+ "terminated", "fell", "anchor", "anchor_dev", "anchor_weighted", "starts")
106
+ DIST_LOG_KEYS = ("steps", "applied", "lean_on", "kick_on", "new_lean", "new_kick", "d_roll_abs", "d_pitch_abs",
107
+ "roll_abs", "pitch_abs", "roll_rate_abs", "pitch_rate_abs", "roll_abs_lean", "fell", "fell_lean",
108
+ "ood_cost")
109
+ DIST_ROWS = ("soft", "medium", "firm", "other")
110
+
111
+
112
+ def soil_bin_index(ground_features):
113
+ """[n] long soil bin of version-B ground features [n, 3]: -1 rigid (is_crm 0), 0 soft, 1 medium, 2 firm (the nrdeval
114
+ 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)."""
115
+ f = torch.nan_to_num(torch.as_tensor(ground_features).to(torch.float64))
116
+ crm = f[:, 0] > 0.5
117
+ c = 250.0 * torch.expm1(f[:, 1] * math.log(17.0))
118
+ mu = 0.6 + 0.3 * f[:, 2]
119
+ b = torch.ones(len(f), dtype=torch.long, device=f.device)
120
+ b = torch.where((c < SOFT_COHESION_PA) & (mu < SOFT_FRICTION), torch.zeros_like(b), b)
121
+ b = torch.where(c > FIRM_COHESION_PA, torch.full_like(b, 2), b)
122
+ return torch.where(crm, b, torch.full_like(b, -1))
123
+
124
+
125
+ def parse_bin_share(share):
126
+ """{soft, medium, firm} dict or a 3-list -> float64 tensor [3] (normalised to sum 1)."""
127
+ if isinstance(share, dict):
128
+ extra = set(share) - set(SOIL_BINS)
129
+ if extra:
130
+ raise ValueError(f"crm_bin_share: unknown bins {sorted(extra)} (soft, medium, firm)")
131
+ v = [float(share.get(b, 0.0)) for b in SOIL_BINS]
132
+ else:
133
+ v = [float(x) for x in share]
134
+ if len(v) != 3:
135
+ raise ValueError("crm_bin_share: 3 values (soft, medium, firm)")
136
+ if min(v) < 0 or sum(v) <= 0:
137
+ raise ValueError(f"crm_bin_share {share}: non-negative, sum > 0")
138
+ t = torch.tensor(v, dtype=torch.float64)
139
+ return t / t.sum()
140
+
141
+
142
+ def sample_envelope(lo, hi, n, gen, standing_fraction=0.1, vx_draw="uniform", forward_fraction=0.5):
143
+ """Envelope commands [n, 3]: u = U[0, 1)^3 (one torch.rand(n, 3) draw), c = lo + (hi - lo) u, then a zero command
144
+ with probability standing_fraction (one torch.rand(n) draw). vx_draw "balanced": vx = hi_x u_x / f if u_x < f else
145
+ lo_x (u_x - f) / (1 - f), f = forward_fraction (needs lo_x < 0 < hi_x): forward U[0, hi_x] with probability f,
146
+ backward U[lo_x, 0] otherwise, from the same uniform (the random stream is the uniform draw's)."""
147
+ u = torch.rand(n, 3, device=lo.device, generator=gen)
148
+ c = lo + (hi - lo) * u
149
+ if vx_draw == "balanced":
150
+ f = float(forward_fraction)
151
+ if not (0.0 < f < 1.0) or not (float(lo[0]) < 0.0 < float(hi[0])):
152
+ raise ValueError(f"balanced vx draw needs 0 < forward_fraction < 1 and vx_lo < 0 < vx_hi ({lo[0]}, {hi[0]})")
153
+ ux = u[:, 0]
154
+ c[:, 0] = torch.where(ux < f, hi[0] * (ux / f), lo[0] * ((ux - f) / (1.0 - f)))
155
+ elif vx_draw != "uniform":
156
+ raise ValueError(f"commands.vx_draw {vx_draw!r}: uniform or balanced")
157
+ stand = torch.rand(n, device=lo.device, generator=gen) < standing_fraction
158
+ return torch.where(stand[:, None], torch.zeros_like(c), c)
159
+
160
+
161
+ def bank_labels(d, cfg):
162
+ """StartBank keyword for the labels of one data entry (go2nrd.labels, 2026-11-01): the entry's "labels", else the
163
+ config's top-level "labels" (a <name>.labels.npz of that data dir); none = the stored contacts (no keyword, the
164
+ bank of before)."""
165
+ spec = d.get("labels", cfg.get("labels"))
166
+ return {} if spec is None or spec == "stored" else {"labels": spec}
167
+
168
+
169
+ def check_labels(banks, sim, enabled=True):
170
+ """The start banks must carry the labels of the NRD they serve ("stored" = the exported contacts): every member's
171
+ training labels (checkpoint runtime) and every bank's labels have one rule (go2nrd.labels.io.rule_key: rule,
172
+ ground and params, numbers as floats; labels_review 2026-11-01: rule_id alone refused 25 vs 25.0). Raises
173
+ ValueError on a mismatch unless env.labels_check is false."""
174
+ if not enabled:
175
+ return
176
+ from go2nrd.labels.io import rule_key
177
+ ids, keys = {}, set()
178
+ who = [(f"NRD {p}", pk.get("labels") or {}) for p, pk in zip(getattr(sim, "paths", []), getattr(sim, "packets", []))]
179
+ who += [(f"bank {b.root}", getattr(b, "labels", None) or {}) for b in banks]
180
+ for name, lab in who:
181
+ ids.setdefault(lab.get("rule_id", "stored"), []).append(name)
182
+ keys.add(rule_key(lab))
183
+ if len(ids) > 1 and len(keys) > 1: # one rule_id, or one canonical rule (numbers as floats): accepted
184
+ raise ValueError(f"labels of the NRD members and the start banks differ (rule_id: who): {ids}; give the bank "
185
+ "the labels file of the NRD's rule for this data dir (config labels / data[i].labels, "
186
+ "rl.train --labels), or set env.labels_check false")
187
+
188
+
189
+ def ground_features_of(start, ground):
190
+ """Version-B continuous ground features f [n, 3] (NRD_PLAN section 10): [is_crm, log1p(cohesion / 250) / log(17),
191
+ (friction - 0.6) / 0.3] for CRM, 0 for rigid. From start["ground_features"] if the bank gives them, else from
192
+ start["soil"] [n, 4] (cohesion, friction, density, E), else is_crm only."""
193
+ if "ground_features" in start:
194
+ return torch.nan_to_num(start["ground_features"].to(torch.float64))
195
+ is_crm = (ground == C.GROUND_IDS["crm"]).to(torch.float64)
196
+ f = torch.zeros(len(ground), 3, dtype=torch.float64, device=ground.device)
197
+ f[:, 0] = is_crm
198
+ if "soil" in start:
199
+ soil = torch.nan_to_num(start["soil"].to(torch.float64))
200
+ f[:, 1] = torch.log1p(soil[:, 0] / 250.0) / math.log(17.0) * is_crm
201
+ f[:, 2] = (soil[:, 1] - 0.6) / 0.3 * is_crm
202
+ return f
203
+
204
+
205
+ def ground_mode(sim):
206
+ """How the sim takes the ground of each env: "kw" (a ground_features= keyword), "features" (ground= [B, F] float
207
+ features: members expose n_ground_features, the continuous version-B code of NRD_PLAN section 10) or "ids"
208
+ (ground= [B] long ids: the discrete code of the first vendored model; version-A members ignore either)."""
209
+ if "ground_features" in inspect.signature(sim.step).parameters:
210
+ return "kw"
211
+ if hasattr(sim, "n_ground_features") or any(hasattr(m, "n_ground_features") for m in getattr(sim, "models", [])):
212
+ return "features"
213
+ return "ids"
214
+
215
+
216
+ class _Loop(NrdPolicyLoop):
217
+ """NrdPolicyLoop whose step passes each env's ground to the sim in the form the sim takes (ground_mode)."""
218
+
219
+ def __init__(self, *a, mode="ids", **kw):
220
+ super().__init__(*a, **kw)
221
+ self.mode = mode
222
+ if not hasattr(self, "ground_features"): # older NrdPolicyLoop (ground ids only)
223
+ self.ground_features = torch.zeros(self.n, 3, dtype=torch.float64, device=self.device)
224
+
225
+ @torch.inference_mode()
226
+ def step(self, raw_action):
227
+ raw = raw_action.to(torch.float32)
228
+ target = self.default + C.ACTION_SCALE * raw.to(torch.float64)
229
+ if self.mode == "kw":
230
+ gk = dict(ground=self.ground, ground_features=self.ground_features)
231
+ elif self.mode == "features":
232
+ gk = dict(ground=self.ground_features)
233
+ else:
234
+ gk = dict(ground=self.ground)
235
+ nxt, g, lg, info = self.sim.step(self.hist, self.ok, target, member=self.layout, **gk)
236
+ self.hist, self.ok = Go2NrdSim.advance(self.hist, self.ok, nxt)
237
+ self.k = self.k + 1
238
+ self.steps = self.steps + 1
239
+ self.last_action = raw
240
+ self.gates = g
241
+ self.air.update(g)
242
+ info["logits"] = lg
243
+ return nxt, g, info
244
+
245
+
246
+ class Go2NrdVecEnv(VecEnv):
247
+ def __init__(self, cfg: dict, device="cuda", train=True, sim=None, banks=None):
248
+ """cfg: the full fine-tune config (keys nrd, data, env, rewards, ood). train=False: no observation noise
249
+ (evaluation). sim / banks: reuse already built objects (tests)."""
250
+ with torch.inference_mode():
251
+ self._build(cfg, device, train, sim, banks)
252
+
253
+ # ---------------------------------------------------------------------------------------------- build
254
+ def _build(self, cfg, device, train, sim, banks):
255
+ self.cfg = cfg
256
+ ec = cfg["env"]
257
+ self.device = torch.device(device)
258
+ self.train = bool(train)
259
+ self.num_envs = n = int(ec["num_envs"])
260
+ self.num_actions = C.ACTION_DIM
261
+ self.dt = C.CONTROL_STEP_S
262
+ self.branch_steps = int(round(float(ec.get("branch_s", 5.0)) / self.dt))
263
+ self.max_episode_length = self.branch_steps
264
+ self.gen = torch.Generator(device=self.device).manual_seed(int(cfg.get("seed", 0)) + 12345)
265
+ nc = cfg["nrd"]
266
+ members = [m if isinstance(m, dict) else {"path": m} for m in nc["members"]]
267
+ if sim is None:
268
+ sim = Go2NrdSim([m["path"] for m in members], self.device, max_batch=nc.get("max_batch", 4096))
269
+ self.sim = sim
270
+ self.ground_arg = ground_mode(sim)
271
+ # banks and per-ground pools
272
+ sc = ec.get("start", {})
273
+ data = [d if isinstance(d, dict) else {"dir": d} for d in cfg["data"]]
274
+ K = int(getattr(sim, "k", 4)) # NRD history length (arm nrd_hist)
275
+ if banks is None:
276
+ banks = [StartBank(d["dir"], splits=tuple(sc.get("splits", (0,))), families=sc.get("families"),
277
+ min_steps_left=int(sc.get("min_steps_left", 1)),
278
+ min_k=max(int(sc.get("min_k", K - 1)), K - 1), device=self.device, history=K,
279
+ rows=d.get("rows"),
280
+ **bank_labels(d, cfg))
281
+ for d in data]
282
+ for bank in banks:
283
+ if int(getattr(bank, "history", 4)) != K:
284
+ raise ValueError(f"start bank with history {getattr(bank, 'history', 4)}, the NRD has history {K}")
285
+ check_labels(banks, sim, ec.get("labels_check", True))
286
+ self.banks = banks
287
+ min_pk = sc.get("min_phase_k", {})
288
+ pools = {} # ground id -> (bank index, start indices)
289
+ for b, bank in enumerate(banks):
290
+ pk = bank.phase_k[bank.start_e, 2 * bank.start_k]
291
+ for g in sorted(set(bank.ground.tolist())):
292
+ m = (bank.ground[bank.start_e] == g) & (pk >= int(min_pk.get(GROUND_NAMES.get(g, str(g)), 0)))
293
+ idx = torch.nonzero(m).flatten()
294
+ if g in pools:
295
+ raise ValueError(f"ground {g} appears in two data dirs; merge them or pass one")
296
+ if len(idx):
297
+ pools[g] = (b, idx)
298
+ want = ec.get("grounds") # optional subset, names or ids
299
+ if want is not None:
300
+ ids = [C.GROUND_IDS[w] if isinstance(w, str) else int(w) for w in want]
301
+ pools = {g: pools[g] for g in ids}
302
+ self.ground_ids = sorted(pools)
303
+ self.ground_names = [GROUND_NAMES.get(g, str(g)) for g in self.ground_ids]
304
+ G = len(self.ground_ids)
305
+ shares = ec.get("ground_share") or [1.0 / G] * G
306
+ sizes = [int(round(n * s / sum(shares))) for s in shares]
307
+ sizes[-1] = n - sum(sizes[:-1])
308
+ # member layout: ground block -> members serving it, even sub-blocks
309
+ parts, a = [], 0
310
+ self.blocks = [] # (ground id, bank index, pool, slice)
311
+ for g, size in zip(self.ground_ids, sizes):
312
+ serving = [i for i, m in enumerate(members)
313
+ if m.get("grounds") is None or g in [C.GROUND_IDS[x] if isinstance(x, str) else int(x)
314
+ for x in m["grounds"]]]
315
+ if not serving:
316
+ raise ValueError(f"no NRD member serves ground {g}")
317
+ base, extra = divmod(size, len(serving))
318
+ for j, mi in enumerate(serving):
319
+ c = base + (j < extra)
320
+ if c:
321
+ parts.append((mi, slice(a, a + c)))
322
+ a += c
323
+ b, pool = pools[g]
324
+ self.blocks.append((g, b, pool, slice(a - size, a)))
325
+ self.layout = MemberLayout(parts, n)
326
+ dev = self.device
327
+ self.ground_idx = torch.zeros(n, dtype=torch.long, device=dev) # index into ground_ids
328
+ ground = torch.zeros(n, dtype=torch.long, device=dev)
329
+ for gi, (g, b, pool, s) in enumerate(self.blocks):
330
+ self.ground_idx[s] = gi
331
+ ground[s] = g
332
+ # soil-weighted CRM starts (env.start.crm_bin_share; off by default)
333
+ self.bin_sampling = {} # block index -> (starts by bin, offsets, counts, share)
334
+ share = sc.get("crm_bin_share")
335
+ if share is not None:
336
+ sh = parse_bin_share(share).to(dev)
337
+ for bi, (g, b, pool, s) in enumerate(self.blocks):
338
+ if GROUND_NAMES.get(g) != "crm":
339
+ continue
340
+ bank = self.banks[b]
341
+ sb = soil_bin_index(bank.ground_features[bank.start_e[pool]])
342
+ subs = [pool[sb == i] for i in range(3)]
343
+ cnt = torch.tensor([len(x) for x in subs], dtype=torch.long, device=dev)
344
+ empty = [SOIL_BINS[i] for i in range(3) if cnt[i] == 0 and sh[i] > 0]
345
+ if empty:
346
+ raise ValueError(f"crm_bin_share: no CRM starts in bin(s) {empty}")
347
+ off = torch.cumsum(cnt, 0) - cnt
348
+ self.bin_sampling[bi] = (torch.cat(subs), off, cnt, sh)
349
+ if not self.bin_sampling:
350
+ raise ValueError("crm_bin_share set but there is no CRM block")
351
+ # policy loop
352
+ critic_mean = None
353
+ fill = ec.get("critic_force_fill", "contact_mean")
354
+ if fill == "mean":
355
+ critic_mean = torch.load(cfg["init_checkpoint"], map_location="cpu", weights_only=False)[
356
+ "critic_state_dict"]["obs_normalizer._mean"]
357
+ self.loop = _Loop(sim, n, layout=self.layout, ground=ground, critic_mean=critic_mean, force_fill=fill,
358
+ mode=self.ground_arg)
359
+ # commands
360
+ cc = ec.get("commands", {})
361
+ env_rng = cc.get("envelope", dict(vx=C.EVALUATION_ENVELOPE["vx"], vy=C.EVALUATION_ENVELOPE["vy"],
362
+ wz=C.EVALUATION_ENVELOPE["wz"]))
363
+ self.cmd_lo = torch.tensor([env_rng["vx"][0], env_rng["vy"][0], env_rng["wz"][0]], device=dev)
364
+ self.cmd_hi = torch.tensor([env_rng["vx"][1], env_rng["vy"][1], env_rng["wz"][1]], device=dev)
365
+ self.recorded_fraction = float(cc.get("recorded_fraction", 0.5))
366
+ self.standing_fraction = float(cc.get("standing_fraction", 0.1))
367
+ self.vx_draw = str(cc.get("vx_draw", "uniform"))
368
+ self.forward_fraction = float(cc.get("forward_fraction", 0.5))
369
+ self.resamples = int(cc.get("resamples", 1))
370
+ if self.resamples not in (0, 1):
371
+ raise ValueError("commands.resamples: 0 or 1")
372
+ # observation noise (mjlab env.yaml actor group, uniform additive)
373
+ nz = ec.get("obs_noise", {})
374
+ self.noise_on = bool(nz.get("enabled", True)) and self.train
375
+ self.noise = torch.zeros(47, device=dev)
376
+ for k, sl in NOISE_COLS.items():
377
+ self.noise[sl] = float(nz.get(k, dict(base_ang_vel=0.2, projected_gravity=0.05, joint_pos=0.01,
378
+ joint_vel=1.5)[k]))
379
+ tc = ec.get("termination", {})
380
+ self.min_z, self.max_tilt = float(tc.get("min_base_z", 0.15)), float(tc.get("max_tilt_deg", 45.0))
381
+ self.settle = int(ec.get("log_settle_steps", 25))
382
+ # rewards and OOD
383
+ self.rewards = RewardTerms(cfg["rewards"], dev)
384
+ oc = cfg.get("ood", {})
385
+ self.ood = self._build_ood(oc) if oc.get("enabled", True) else None
386
+ self.ood_grace = int(oc.get("grace_steps", 25))
387
+ # per-env buffers
388
+ z = lambda *s, dt=torch.float32: torch.zeros(*s, dtype=dt, device=dev)
389
+ self.episode_length_buf = z(n, dt=torch.long) # steps since the branch start
390
+ self.limit = torch.full((n,), self.branch_steps, dtype=torch.long, device=dev)
391
+ self.rec_e, self.rec_k0 = z(n, dt=torch.long), z(n, dt=torch.long)
392
+ self.cmd_mode = z(n, dt=torch.bool) # True = recorded stream
393
+ self.env_cmd, self.resample_at = z(n, 3), z(n, dt=torch.long)
394
+ self.cmd_prev = z(n, 3)
395
+ self.lag_ok = z(n, dt=torch.bool)
396
+ self.env_bin = torch.full((n,), -1, dtype=torch.long, device=dev) # soil bin of each env's start (-1 rigid)
397
+ self.bin_starts = z(3, dt=torch.float64) # starts drawn per soil bin (logged)
398
+ self.log_sums = z(G, len(LOG_KEYS), dt=torch.float64)
399
+ # action anchor (rewards.anchor; off by default)
400
+ self.anchor = self._anchor_cfg(cfg, ground)
401
+ self.action_mean = None # set by the runner before step() (centered anchor)
402
+ self.extra_scales = {"anchor": self.anchor["scale"]} if self.anchor else {}
403
+ lb = ec.get("log_soil_bins")
404
+ self.log_bins = bool(self.anchor is not None or self.bin_sampling) if lb is None else bool(lb)
405
+ # attitude-rate disturbances (env.disturb; off by default)
406
+ self.disturb = None
407
+ dc = ec.get("disturb")
408
+ if dc:
409
+ rd = RateDisturbance(dc, n, ground, dev, seed=int(cfg.get("seed", 0)), dt=self.dt)
410
+ if rd.enabled:
411
+ self.disturb = rd
412
+ self.log_bins = True # env_bin drives the bin scale
413
+ self.dist_sums = z(len(DIST_ROWS), len(DIST_LOG_KEYS), dt=torch.float64)
414
+ self.bin_sums = z(3, len(BIN_LOG_KEYS), dt=torch.float64)
415
+ self.log_terms = {}
416
+ self.log_peak = z(G, dt=torch.float64)
417
+ # lateral-sand recipe (go2nrd.rl.lateral_v3; off by default: no object, no draws)
418
+ self.v3 = lateral_v3.LateralV3(cfg, self) if lateral_v3.enabled(cfg) else None
419
+ if self.v3 is not None:
420
+ self.extra_scales.update(self.v3.scales)
421
+ # first reset: all envs, staggered first branch lengths
422
+ self._reset(torch.ones(n, dtype=torch.bool, device=dev))
423
+ if ec.get("stagger", True):
424
+ self.limit = torch.randint(1, self.branch_steps + 1, (n,), device=dev, generator=self.gen)
425
+ if self.v3 is not None:
426
+ self.v3.after_stagger()
427
+ self._obs_cache = self._observations()
428
+ if self.anchor is not None:
429
+ self.anchor["ref"] = self._build_reference(cfg, self.anchor["reference"])
430
+
431
+ def _anchor_cfg(self, cfg, ground):
432
+ ac = cfg.get("rewards", {}).get("anchor")
433
+ if not ac or float(ac.get("weight", 0.0)) == 0.0:
434
+ return None
435
+ mode = str(ac.get("mode", "centered"))
436
+ if mode not in ("centered", "sample"):
437
+ raise ValueError(f"rewards.anchor.mode {mode!r}: centered or sample")
438
+ names = ac.get("grounds", ["crm"])
439
+ ids = [C.GROUND_IDS[x] if isinstance(x, str) else int(x) for x in names]
440
+ w = float(ac["weight"])
441
+ if w < 0:
442
+ raise ValueError("rewards.anchor.weight is the positive penalty weight w (reward -w x dt x A)")
443
+ dt_scale = bool(ac.get("dt_scale", True)) and bool(cfg["rewards"].get("scale_by_dt", True))
444
+ mask = torch.isin(ground, torch.tensor(ids, dtype=torch.long, device=ground.device))
445
+ gw = ac.get("ground_weight") # per-ground multiplier of w (ppo_soft; off by default)
446
+ if gw:
447
+ extra = set(gw) - set(names)
448
+ if extra:
449
+ raise ValueError(f"rewards.anchor.ground_weight: {sorted(extra)} not in anchor grounds {names}")
450
+ rel = torch.zeros(len(ground), dtype=torch.float32, device=ground.device)
451
+ for nm, gid in zip(names, ids):
452
+ v = float(gw.get(nm, gw.get(str(gid), 1.0)))
453
+ if v < 0:
454
+ raise ValueError("rewards.anchor.ground_weight must be >= 0")
455
+ rel = torch.where(ground == gid, torch.full_like(rel, v), rel)
456
+ mask = rel
457
+ return dict(weight=w, scale=-w * (0.02 if dt_scale else 1.0), mode=mode, grounds=ids, mask=mask,
458
+ reference=ac.get("reference") or cfg["init_checkpoint"])
459
+
460
+ def _build_reference(self, cfg, path):
461
+ """Frozen reference actor: rsl_rl MLPModel of the fine-tune's layout (the runner's actor class), weights of
462
+ `path` (rsl_rl checkpoint); built without touching the global RNG streams."""
463
+ from rsl_rl.models import MLPModel
464
+ from rsl_rl.modules.distribution import GaussianDistribution
465
+ hid = tuple(cfg.get("ppo", {}).get("hidden_dims", (512, 256, 128)))
466
+ with torch.random.fork_rng(devices=[]):
467
+ ref = MLPModel(self._obs_cache, {"actor": ["actor"], "critic": ["critic"]}, "actor", self.num_actions,
468
+ hidden_dims=hid, activation="elu", obs_normalization=True,
469
+ distribution_cfg=dict(class_name=GaussianDistribution, init_std=1.0, std_type="scalar"))
470
+ ck = torch.load(path, map_location="cpu", weights_only=False)
471
+ ref.load_state_dict(ck["actor_state_dict"], strict=True)
472
+ ref = ref.to(self.device).eval()
473
+ for prm in ref.parameters():
474
+ prm.requires_grad_(False)
475
+ ref.obs_normalizer.until = 1
476
+ return ref
477
+
478
+ def _build_ood(self, oc):
479
+ refs = []
480
+ tc = oc.get("threshold") # (c) family threshold (off by default)
481
+ self.ood_thresh_info = {}
482
+ rfile = oc.get("reference_file") or {} # (d) precomputed reference rows (off by default)
483
+ unknown = set(rfile) - set(GROUND_NAMES.get(g, str(g)) for g, *_ in self.blocks)
484
+ if unknown:
485
+ raise ValueError(f"ood.reference_file: grounds {sorted(unknown)} not in the env")
486
+ for g, b, pool, s in self.blocks:
487
+ bank = self.banks[b]
488
+ m = int(oc.get("max_points", 4000))
489
+ name = GROUND_NAMES.get(g, str(g))
490
+ if name in rfile:
491
+ feat, family = self._reference_rows(rfile[name], bank, name)
492
+ else:
493
+ gen = torch.Generator(device=self.device).manual_seed(int(oc.get("seed", 0)))
494
+ take = min(len(pool), 4 * m) # distinct start rows (the S4 draw size)
495
+ idx = pool[torch.randperm(len(pool), device=self.device, generator=gen)[:take]]
496
+ st = bank.draw(idx)
497
+ feat = ood_features(st["hist"][:, -1], st["action"])
498
+ family = st["family"]
499
+ ref = CorpusReference(feat, seed=int(oc.get("seed", 0)), max_points=m, k=int(oc.get("k", 8)),
500
+ quantile=float(oc.get("quantile", 0.99)), device=self.device)
501
+ if tc and (tc.get("grounds") is None or name in tc["grounds"] or g in tc["grounds"]):
502
+ self.ood_thresh_info[name] = self._family_threshold(ref, feat, family, bank, tc)
503
+ refs.append(ref)
504
+ gw = oc.get("ground_weight")
505
+ weights = None
506
+ if gw:
507
+ extra = set(gw) - set(self.ground_names)
508
+ if extra:
509
+ raise ValueError(f"ood.ground_weight: grounds {sorted(extra)} not in the env {self.ground_names}")
510
+ weights = [float(gw.get(nm, 1.0)) for nm in self.ground_names]
511
+ if min(weights) < 0:
512
+ raise ValueError("ood.ground_weight must be >= 0 (the sign is the term weight's)")
513
+ return GroundOOD(refs, weights=weights)
514
+
515
+ def _reference_rows(self, path, bank, name):
516
+ """(d) ood.reference_file {ground: npz}: the reference draw rows of a ground from a file instead of the start
517
+ pool (e.g. the training corpus of another NRD: lateral_stuck_20261108 ppo_nrdv3/build_ood_reference.py).
518
+ npz: feat [M, 45] float64 (ood_features of the recorded state and applied target), family [M] (family ids),
519
+ family_names [F] (must equal the bank's system.json family names). CorpusReference and the family threshold
520
+ then run on these rows exactly as on a pool draw. Recorded in ood_summary (path, sha256, rows)."""
521
+ import hashlib
522
+ import numpy as np
523
+ raw = Path(path).read_bytes()
524
+ z = np.load(io.BytesIO(raw), allow_pickle=False)
525
+ feat = torch.as_tensor(np.asarray(z["feat"], dtype=np.float64), device=self.device)
526
+ family = torch.as_tensor(np.asarray(z["family"]).astype(np.int64), device=self.device)
527
+ names = [str(x) for x in z["family_names"]]
528
+ want = [f["name"] for f in bank.system.get("families", [])]
529
+ if feat.ndim != 2 or feat.shape[1] != 45 or len(family) != len(feat):
530
+ raise ValueError(f"ood.reference_file[{name}]: feat {tuple(feat.shape)}, family {tuple(family.shape)}")
531
+ if names != want:
532
+ raise ValueError(f"ood.reference_file[{name}]: family names {names} != the bank's {want}")
533
+ if not bool(torch.isfinite(feat).all()):
534
+ raise ValueError(f"ood.reference_file[{name}]: non-finite features")
535
+ if not hasattr(self, "ood_reference_files"):
536
+ self.ood_reference_files = {}
537
+ self.ood_reference_files[name] = dict(path=str(path), sha256=hashlib.sha256(raw).hexdigest(), rows=int(len(feat)))
538
+ return feat, family
539
+
540
+ @staticmethod
541
+ def _family_threshold(ref, feat, family, bank, tc):
542
+ """(c): set ref.thresh to the quantile of the leave-one-out mean kNN distance of the draw's rows of one family
543
+ (or to a fixed value); returns the record for the logs / start.json."""
544
+ stock = ref.thresh
545
+ if tc.get("value") is not None:
546
+ ref.thresh = float(tc["value"])
547
+ rec = dict(source="value", thresh=ref.thresh, stock=stock)
548
+ else:
549
+ fam = tc.get("family", "nominal")
550
+ names = [f["name"] for f in bank.system.get("families", [])]
551
+ fid = names.index(fam) if isinstance(fam, str) else int(fam)
552
+ rows = feat[family == fid]
553
+ if len(rows) <= ref.k:
554
+ raise ValueError(f"ood.threshold: {len(rows)} rows of family {fam} in the reference draw")
555
+ d = ref.knn_loo(rows)
556
+ q = float(tc.get("quantile", 0.99))
557
+ base = float(torch.quantile(d.double(), q))
558
+ ref.thresh = base * float(tc.get("scale", 1.0))
559
+ rec = dict(source=f"family {fam}", rows=int(len(rows)), quantile=q, scale=float(tc.get("scale", 1.0)),
560
+ loo_knn_mean=float(d.double().mean()), loo_knn_q=base, thresh=ref.thresh, stock=stock)
561
+ return rec
562
+
563
+ def ood_summary(self):
564
+ if self.ood is None:
565
+ return None
566
+ out = {name: r.summary() for name, r in zip(self.ground_names, self.ood.refs)}
567
+ for name, rec in getattr(self, "ood_thresh_info", {}).items():
568
+ out[name]["family_threshold"] = rec
569
+ for name, rec in getattr(self, "ood_reference_files", {}).items(): # (d), only when ood.reference_file is set
570
+ out[name]["reference_file"] = rec
571
+ if self.ood.weights is not None:
572
+ for name, wgt in zip(self.ground_names, self.ood.weights):
573
+ out[name]["ground_weight"] = wgt
574
+ return out
575
+
576
+ # ---------------------------------------------------------------------------------------------- resets
577
+ def _draw(self):
578
+ """One start per env (each block from its ground's pool), concatenated in env order."""
579
+ outs = []
580
+ for bi, (g, b, pool, s) in enumerate(self.blocks):
581
+ if self.v3 is not None and bi in self.v3.group_sampling:
582
+ st = self.v3.draw_block(bi, b, pool, s.stop - s.start, self.gen)
583
+ elif bi in self.bin_sampling:
584
+ m = s.stop - s.start
585
+ cat, off, cnt, sh = self.bin_sampling[bi]
586
+ k = torch.multinomial(sh, m, replacement=True, generator=self.gen)
587
+ u = torch.rand(m, device=self.device, generator=self.gen)
588
+ j = torch.minimum((u * cnt[k]).long(), cnt[k] - 1)
589
+ st = self.banks[b].draw(cat[off[k] + j])
590
+ else:
591
+ st = self.banks[b].sample(s.stop - s.start, generator=self.gen, pool=pool)
592
+ st["ground_features"] = ground_features_of(st, st["ground"])
593
+ outs.append(st)
594
+ if len(outs) == 1:
595
+ return outs[0]
596
+ return {k: torch.cat([o[k] for o in outs]) for k in outs[0]}
597
+
598
+ def _sample_envelope(self, n):
599
+ return sample_envelope(self.cmd_lo, self.cmd_hi, n, self.gen, self.standing_fraction, self.vx_draw,
600
+ self.forward_fraction)
601
+
602
+ def _recorded_command(self, steps_ahead):
603
+ """Recorded command at control step k0 + steps_ahead of each env's start episode [n, 3]."""
604
+ out = torch.zeros(self.num_envs, 3, device=self.device)
605
+ for g, b, pool, s in self.blocks:
606
+ bank = self.banks[b]
607
+ e = self.rec_e[s]
608
+ r = (2 * (self.rec_k0[s] + steps_ahead[s])).clamp_max(bank.lengths[e] - 1)
609
+ out[s] = bank.command[e, r].float()
610
+ return out
611
+
612
+ def _reset(self, mask, start=None):
613
+ n, dev = self.num_envs, self.device
614
+ start = self._draw() if start is None else start
615
+ m = mask
616
+ self.loop.reset_where(m, start)
617
+ w = lambda new, old: torch.where(m.view(-1, *([1] * (old.dim() - 1))), new.to(old.dtype), old)
618
+ self.loop.ground_features = w(start["ground_features"], self.loop.ground_features)
619
+ if self.log_bins:
620
+ self.env_bin = w(soil_bin_index(start["ground_features"]), self.env_bin)
621
+ self.bin_starts.index_add_(0, self.env_bin.clamp_min(0), (m & (self.env_bin >= 0)).to(torch.float64))
622
+ self.rec_e, self.rec_k0 = w(start["episode"], self.rec_e), w(start["k"], self.rec_k0)
623
+ mode = torch.rand(n, device=dev, generator=self.gen) < self.recorded_fraction
624
+ self.cmd_mode = w(mode, self.cmd_mode)
625
+ self.env_cmd = w(self._sample_envelope(n), self.env_cmd)
626
+ ra = torch.randint(1, max(2, self.branch_steps), (n,), device=dev, generator=self.gen) if self.resamples \
627
+ else torch.full((n,), -1, dtype=torch.long, device=dev)
628
+ self.resample_at = w(ra, self.resample_at)
629
+ self.loop.command = w(torch.where(self.cmd_mode[:, None], start["command"].float(), self.env_cmd),
630
+ self.loop.command)
631
+ self.episode_length_buf = w(torch.zeros_like(self.episode_length_buf), self.episode_length_buf)
632
+ self.limit = w(torch.full_like(self.limit, self.branch_steps), self.limit)
633
+ self.lag_ok = w(torch.zeros_like(self.lag_ok), self.lag_ok)
634
+ self.cmd_prev = w(self.loop.command, self.cmd_prev)
635
+ if self.v3 is not None:
636
+ self.v3.on_reset(m, start)
637
+ if self.disturb is not None:
638
+ self.disturb.reset(m)
639
+
640
+ def set_starts(self, start, cmd_mode, env_cmd, resample_at=None, limit=None):
641
+ """Explicit reset of all envs (evaluation): start dict of n starts, cmd_mode [n] bool (recorded stream),
642
+ env_cmd [n, 3] (envelope command), resample_at [n] (-1 = never), limit [n] branch length."""
643
+ with torch.inference_mode():
644
+ n = self.num_envs
645
+ start = dict(start)
646
+ start.setdefault("ground_features", ground_features_of(start, start["ground"]))
647
+ all_ = torch.ones(n, dtype=torch.bool, device=self.device)
648
+ self.loop.reset_where(all_, start)
649
+ self.loop.ground_features = start["ground_features"].to(self.loop.ground_features.dtype).clone()
650
+ if self.log_bins:
651
+ self.env_bin = soil_bin_index(start["ground_features"])
652
+ self.rec_e, self.rec_k0 = start["episode"].clone(), start["k"].clone()
653
+ self.cmd_mode = cmd_mode.to(self.device).bool().clone()
654
+ self.env_cmd = env_cmd.to(self.device).float().clone()
655
+ self.resample_at = (torch.full((n,), -1, dtype=torch.long, device=self.device) if resample_at is None
656
+ else resample_at.to(self.device).long().clone())
657
+ self.loop.command = torch.where(self.cmd_mode[:, None], start["command"].float(), self.env_cmd)
658
+ self.episode_length_buf = torch.zeros_like(self.episode_length_buf)
659
+ self.limit = (torch.full_like(self.limit, self.branch_steps) if limit is None
660
+ else limit.to(self.device).long().clone())
661
+ self.lag_ok = torch.zeros_like(self.lag_ok)
662
+ self.cmd_prev = self.loop.command.clone()
663
+ if self.v3 is not None: # trackers only (no command / branch draws)
664
+ self.v3.valid = torch.zeros_like(self.v3.valid)
665
+ self.v3.swing_prev = self.v3.clock_swing(self.loop.k)
666
+ if self.disturb is not None:
667
+ self.disturb.reset(all_)
668
+ self._obs_cache = self._observations()
669
+ return self._obs_cache
670
+
671
+ # ---------------------------------------------------------------------------------------------- obs
672
+ def _observations(self, noise=None):
673
+ actor = self.loop.actor_obs()
674
+ if (self.noise_on if noise is None else noise):
675
+ u = torch.rand(actor.shape, device=self.device, generator=self.gen) * 2.0 - 1.0
676
+ actor = actor + u * self.noise
677
+ critic = self.loop.critic_obs()
678
+ return TensorDict({"actor": actor, "critic": critic}, batch_size=[self.num_envs], device=self.device)
679
+
680
+ def get_observations(self) -> TensorDict:
681
+ return self._obs_cache
682
+
683
+ # ---------------------------------------------------------------------------------------------- step
684
+ def step(self, actions):
685
+ with torch.inference_mode():
686
+ return self._step(actions)
687
+
688
+ def _step(self, actions):
689
+ lp = self.loop
690
+ raw = actions.to(self.device, torch.float32)
691
+ s0 = lp.hist[:, -1]
692
+ g0, k0, cmd, raw_prev = lp.gates, lp.k, lp.command, lp.last_action
693
+ target = lp.default + C.ACTION_SCALE * raw.to(torch.float64)
694
+ if self.ood is not None:
695
+ feat = ood_features(s0, target)
696
+ ood_all, knn = self.ood.cost_knn(feat, self.ground_idx)
697
+ # grace: no OOD price in the first grace_steps of a branch (the start transient: a clean action at a
698
+ # recorded noisy state, tests/rl/diag_ood.py), so price and guard see the states the policy produced
699
+ ood = ood_all * (self.episode_length_buf >= self.ood_grace).to(ood_all.dtype)
700
+ else:
701
+ ood = ood_all = knn = torch.zeros(self.num_envs, device=self.device)
702
+ s1, g1, info = lp.step(raw)
703
+ self.episode_length_buf = self.episode_length_buf + 1
704
+ nonfinite = info["nonfinite"]
705
+ if self.disturb is not None: # (a) kicks / (b) lean on the NRD's rates
706
+ d, applied = self.disturb.step(self.env_bin, s0)
707
+ s1 = apply_rate_perturbation(s0, s1, d, applied & ~nonfinite, self.dt)
708
+ lp.hist = torch.cat((lp.hist[:, :-1], s1[:, None]), 1)
709
+ self.last_s1, self.last_nonfinite, self.last_gates = s1, nonfinite, g1 # before any reset
710
+ fell = tilt_terminated(s1, self.min_z, self.max_tilt)
711
+ terminated = fell | nonfinite
712
+ time_out = (self.episode_length_buf >= self.limit) & ~terminated
713
+ rew, terms, rx = self.rewards.compute(s0, s1, raw, raw_prev, target, cmd, self.cmd_prev, k0, g0, g1,
714
+ self.lag_ok, terminated, ood)
715
+ if self.anchor is not None:
716
+ rew, terms = self._apply_anchor(raw, rew, terms, cmd)
717
+ if self.v3 is not None: # gait terms (weight 0 / absent: logged only)
718
+ rew, terms = self.v3.apply(s1, k0, cmd, rew, terms)
719
+ self._accumulate(rew, terms, rx, cmd, ood, ood_all, knn, terminated, fell, nonfinite, time_out)
720
+ if self.v3 is not None:
721
+ self.v3.accumulate(terms, cmd, ood, self.episode_length_buf >= self.settle)
722
+ if self.disturb is not None:
723
+ self._accumulate_disturb(s1, rx, fell, ood)
724
+ # next command (recorded stream / envelope resample)
725
+ rec = self._recorded_command(self.episode_length_buf)
726
+ hit = self.episode_length_buf == self.resample_at
727
+ self.env_cmd = torch.where(hit[:, None], self._sample_envelope(self.num_envs), self.env_cmd)
728
+ self.cmd_prev = cmd
729
+ lp.command = torch.where(self.cmd_mode[:, None], rec, self.env_cmd)
730
+ self.lag_ok = torch.ones_like(self.lag_ok)
731
+ done = terminated | time_out
732
+ final_obs = self._observations(noise=False)
733
+ self._reset(done)
734
+ obs = self._observations()
735
+ self._obs_cache = obs
736
+ extras = {"time_outs": time_out, "final_obs": final_obs, "terminated": terminated}
737
+ return obs, rew, done, extras
738
+
739
+ def _apply_anchor(self, raw, rew, terms, cmd=None):
740
+ """reward += scale A, scale = -w (x dt), on the anchored envs (module docstring); a_ref from the observation the policy acted
741
+ on (self._obs_cache, before this step's reset); env.action_mean is consumed (None afterwards)."""
742
+ an = self.anchor
743
+ a_ref = an["ref"](self._obs_cache).to(torch.float32)
744
+ mu = raw if self.action_mean is None else self.action_mean.to(self.device, torch.float32)
745
+ self.action_mean = None
746
+ d_ref = (raw - a_ref).square().sum(-1)
747
+ A = d_ref - (raw - mu).square().sum(-1) if an["mode"] == "centered" else d_ref
748
+ A = A * an["mask"].to(A.dtype)
749
+ if self.v3 is not None and self.v3.anchor_scale is not None and cmd is not None:
750
+ A = A * self.v3.anchor_factor(cmd).to(A.dtype) # (c) command-conditioned anchor weight
751
+ terms = dict(terms)
752
+ terms["anchor"] = A
753
+ terms["anchor_dev"] = (mu - a_ref).square().sum(-1) * (an["mask"] > 0).to(A.dtype) # logged: |mu - a_ref|^2
754
+ return rew + an["scale"] * A, terms
755
+
756
+ # ---------------------------------------------------------------------------------------------- logging
757
+ def _accumulate(self, rew, terms, rx, cmd, ood, ood_all, knn, terminated, fell, nonfinite, time_out):
758
+ f = torch.float64
759
+ vb, wb = rx["vb"], rx["wb"]
760
+ trk = (self.episode_length_buf >= self.settle).to(f)
761
+ tau_u, eff = rx["tau_u"], self.rewards.effort
762
+ rel = tau_u.abs() / eff
763
+ lat = trk * (cmd[:, 1].abs() >= LATERAL_VY).to(f)
764
+ roll_abs, pitch_abs = rx["roll"].abs().to(f), rx["pitch"].abs().to(f)
765
+ cols = [torch.ones_like(trk), rew.to(f),
766
+ (vb[:, 0] - cmd[:, 0]).abs() * trk, (vb[:, 1] - cmd[:, 1]).abs() * trk,
767
+ (wb[:, 2] - cmd[:, 2]).abs() * trk, trk, rx["power"].to(f),
768
+ (rel >= 1.0).to(f).mean(-1), (rel >= 0.85).to(f).mean(-1), rel.max(-1).values.to(f),
769
+ ood.to(f), (ood > 0).to(f), knn.to(f), ood_all.to(f),
770
+ terminated.to(f), fell.to(f), nonfinite.to(f), time_out.to(f), (terminated | time_out).to(f),
771
+ rx["contact"].to(f).mean(-1),
772
+ roll_abs * trk, pitch_abs * trk, roll_abs * lat, lat]
773
+ x = torch.stack(cols, -1)
774
+ self.log_sums.index_add_(0, self.ground_idx, x)
775
+ for k, v in terms.items():
776
+ w = self.rewards.scales.get(k, self.extra_scales.get(k, 0.0))
777
+ val = torch.stack((v.to(f), (w * v).to(f)), -1)
778
+ if k not in self.log_terms:
779
+ self.log_terms[k] = torch.zeros(len(self.ground_ids), 2, dtype=f, device=self.device)
780
+ self.log_terms[k].index_add_(0, self.ground_idx, val)
781
+ self.log_peak = torch.maximum(self.log_peak, torch.zeros_like(self.log_peak).index_reduce_(
782
+ 0, self.ground_idx, rel.max(-1).values.to(f), "amax", include_self=True))
783
+ if self.log_bins:
784
+ zero = torch.zeros_like(trk)
785
+ an = terms.get("anchor", zero).to(f)
786
+ bc = [torch.ones_like(trk), rew.to(f), (vb[:, 0] - cmd[:, 0]).abs() * trk,
787
+ (vb[:, 1] - cmd[:, 1]).abs() * trk, (wb[:, 2] - cmd[:, 2]).abs() * trk, trk, rx["power"].to(f),
788
+ terminated.to(f), fell.to(f), an, terms.get("anchor_dev", zero).to(f),
789
+ self.extra_scales.get("anchor", 0.0) * an, zero]
790
+ x = torch.stack(bc, -1)
791
+ keep = self.env_bin >= 0
792
+ self.bin_sums.index_add_(0, self.env_bin.clamp_min(0), x * keep.to(f)[:, None])
793
+
794
+ def _accumulate_disturb(self, s1, rx, fell, ood):
795
+ f = torch.float64
796
+ L = self.disturb.last
797
+ rr, pr = heading_rates(s1)
798
+ lean = L["lean"].to(f)
799
+ roll_abs = rx["roll"].abs().to(f)
800
+ cols = [torch.ones_like(lean), L["applied"].to(f), lean, L["kick"].to(f), L["new_lean"].to(f),
801
+ L["new_kick"].to(f), L["d"][:, 0].abs(), L["d"][:, 1].abs(), roll_abs, rx["pitch"].abs().to(f),
802
+ rr.abs(), pr.abs(), roll_abs * lean, fell.to(f), fell.to(f) * lean, ood.to(f)]
803
+ row = torch.where(self.env_bin >= 0, self.env_bin, torch.full_like(self.env_bin, 3))
804
+ self.dist_sums.index_add_(0, row, torch.stack(cols, -1) * self.disturb.mask.to(f)[:, None])
805
+
806
+ def _pop_disturb(self):
807
+ sums = self.dist_sums.cpu().numpy()
808
+ self.dist_sums.zero_()
809
+ K = {k: i for i, k in enumerate(DIST_LOG_KEYS)}
810
+ out = {}
811
+ for i, name in enumerate(DIST_ROWS):
812
+ r = sums[i]
813
+ st = r[K["steps"]]
814
+ if st <= 0:
815
+ continue
816
+ ln = max(r[K["lean_on"]], 1.0)
817
+ out[name] = dict(env_steps=float(st), applied_frac=float(r[K["applied"]] / st),
818
+ lean_frac=float(r[K["lean_on"]] / st), kick_frac=float(r[K["kick_on"]] / st),
819
+ lean_starts_per_s=float(r[K["new_lean"]] / st / self.dt),
820
+ kicks_per_s=float(r[K["new_kick"]] / st / self.dt),
821
+ d_roll_abs=float(r[K["d_roll_abs"]] / st), d_pitch_abs=float(r[K["d_pitch_abs"]] / st),
822
+ roll_abs=float(r[K["roll_abs"]] / st), pitch_abs=float(r[K["pitch_abs"]] / st),
823
+ roll_rate_abs=float(r[K["roll_rate_abs"]] / st),
824
+ pitch_rate_abs=float(r[K["pitch_rate_abs"]] / st),
825
+ roll_abs_in_lean=float(r[K["roll_abs_lean"]] / ln), falls=float(r[K["fell"]]),
826
+ falls_in_lean=float(r[K["fell_lean"]]), falls_per_1k_steps=float(1000.0 * r[K["fell"]] / st),
827
+ ood_cost=float(r[K["ood_cost"]] / st))
828
+ return out
829
+
830
+ def pop_log(self):
831
+ """Per-ground means of the logged quantities since the last call (one host sync); resets the sums."""
832
+ with torch.inference_mode():
833
+ sums = self.log_sums.cpu().numpy()
834
+ terms = {k: v.cpu().numpy() for k, v in self.log_terms.items()}
835
+ peak = self.log_peak.cpu().numpy()
836
+ self.log_sums.zero_()
837
+ for v in self.log_terms.values():
838
+ v.zero_()
839
+ self.log_peak.zero_()
840
+ bins = self.bin_sums.cpu().numpy() if self.log_bins else None
841
+ if bins is not None:
842
+ bins[:, BIN_LOG_KEYS.index("starts")] = self.bin_starts.cpu().numpy()
843
+ self.bin_sums.zero_()
844
+ self.bin_starts.zero_()
845
+ K = {k: i for i, k in enumerate(LOG_KEYS)}
846
+ out = {}
847
+ for gi, name in enumerate(self.ground_names + ["all"]):
848
+ row = sums.sum(0) if name == "all" else sums[gi]
849
+ st = max(row[K["steps"]], 1.0)
850
+ ts = max(row[K["track_steps"]], 1.0)
851
+ ends = row[K["ends"]]
852
+ d = dict(env_steps=float(row[K["steps"]]), reward_per_step=row[K["reward"]] / st,
853
+ track_err=[row[K["track_err_vx"]] / ts, row[K["track_err_vy"]] / ts, row[K["track_err_wz"]] / ts],
854
+ power_w=row[K["power_w"]] / st, tau_sat_frac=row[K["tau_sat_frac"]] / st,
855
+ tau_085_frac=row[K["tau_085_frac"]] / st,
856
+ tau_peak_rel=float(peak.max() if name == "all" else peak[gi]),
857
+ ood_cost=row[K["ood_cost"]] / st, ood_active_frac=row[K["ood_active"]] / st,
858
+ ood_knn=row[K["ood_knn"]] / st, ood_cost_all=row[K["ood_cost_all"]] / st,
859
+ terminations=float(row[K["terminated"]]), falls=float(row[K["fell"]]),
860
+ nonfinite=float(row[K["nonfinite"]]), time_outs=float(row[K["time_out"]]),
861
+ fall_frac_of_ends=float(row[K["fell"]] / ends) if ends > 0 else 0.0,
862
+ falls_per_1k_steps=1000.0 * row[K["fell"]] / st, contact_duty=row[K["contact_duty"]] / st,
863
+ roll_abs=row[K["roll_abs"]] / ts, pitch_abs=row[K["pitch_abs"]] / ts,
864
+ roll_abs_lat=row[K["roll_abs_lat"]] / max(row[K["lat_steps"]], 1.0),
865
+ lat_share=row[K["lat_steps"]] / ts)
866
+ d["terms"] = {k: dict(raw=float((v.sum(0) if name == "all" else v[gi])[0] / st),
867
+ weighted=float((v.sum(0) if name == "all" else v[gi])[1] / st))
868
+ for k, v in terms.items()}
869
+ out[name] = {k: (float(v) if not isinstance(v, (list, dict)) else
870
+ ([float(x) for x in v] if isinstance(v, list) else v)) for k, v in d.items()}
871
+ if bins is not None and "crm" in out:
872
+ B = {k: i for i, k in enumerate(BIN_LOG_KEYS)}
873
+ tot = max(float(bins[:, B["steps"]].sum()), 1.0)
874
+ tot_st = max(float(bins[:, B["starts"]].sum()), 1.0)
875
+ out["crm"]["bins"] = {}
876
+ for i, b in enumerate(SOIL_BINS):
877
+ r = bins[i]
878
+ st, ts = max(r[B["steps"]], 1.0), max(r[B["track_steps"]], 1.0)
879
+ out["crm"]["bins"][b] = dict(
880
+ env_steps=float(r[B["steps"]]), step_share=float(r[B["steps"]] / tot),
881
+ start_share=float(r[B["starts"]] / tot_st), reward_per_step=float(r[B["reward"]] / st),
882
+ track_err=[float(r[B["track_err_vx"]] / ts), float(r[B["track_err_vy"]] / ts),
883
+ float(r[B["track_err_wz"]] / ts)],
884
+ power_w=float(r[B["power_w"]] / st), terminations=float(r[B["terminated"]]),
885
+ falls=float(r[B["fell"]]), falls_per_1k_steps=float(1000.0 * r[B["fell"]] / st),
886
+ anchor=float(r[B["anchor"]] / st), anchor_dev=float(r[B["anchor_dev"]] / st),
887
+ anchor_weighted=float(r[B["anchor_weighted"]] / st))
888
+ if self.disturb is not None:
889
+ with torch.inference_mode():
890
+ out["all"]["disturb"] = self._pop_disturb()
891
+ if self.v3 is not None:
892
+ with torch.inference_mode():
893
+ v3 = self.v3.pop()
894
+ for name in self.ground_names:
895
+ out[name]["v3"] = v3.get(name, {})
896
+ if "start_groups" in v3:
897
+ out["all"]["v3_start_groups"] = v3["start_groups"]
898
+ return out
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/lateral_v3.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lateral-sand PPO recipe options (lateral_stuck_20261108 track B, "PPO v3"). All default off: a config without the
2
+ keys below builds no LateralV3 object and Go2NrdVecEnv runs exactly as before (same random draws, same rewards, same
3
+ logs).
4
+
5
+ Config keys (each optional; any one of them turns the helper on):
6
+ env.commands.lateral_mix {lateral 0.5, diagonal 0.15, vy [0.2, 0.5], lateral_vx 0.1, wz 0.15,
7
+ diag_vx [0.2, 0.5], diag_forward_fraction 0.6, sign_from_start true, sign_min_vy 0.15, grounds null}
8
+ (a) Per branch: with probability `lateral` a lateral-dominant command (vy = s U(vy), vx = U(-lateral_vx,
9
+ lateral_vx), wz = U(-wz, wz)), with probability `diagonal` a diagonal command (vy = s U(vy), vx = +-U(diag_vx),
10
+ forward with diag_forward_fraction, wz = U(-wz, wz)); otherwise the original sampler (recorded stream /
11
+ envelope) is kept. Lateral and diagonal commands are held for the whole branch (no resample). s = the sign of
12
+ the start's recorded vy when |vy_rec| >= sign_min_vy and sign_from_start, else +-1 at random.
13
+ env.branch_s_lateral 4.0
14
+ (f) Branch length (s) of the lateral-dominant command draws (the other draws keep env.branch_s). The first
15
+ (staggered) branch is stretched by the same ratio.
16
+ env.start.groups {file, share {group: share, ..., "soft": s, "other": s}, grounds ["crm"]}
17
+ (b) Start-pool weighting of a ground's block: the npz `file` lists intervals (row = export row, lo / hi =
18
+ record range [lo, hi), group = index into names); a start (row, k) is in a group when 2k is inside one of its
19
+ intervals (first listed group wins). Built-in groups: "soft" (CRM soil bin soft, not in a file group) and
20
+ "other" (the rest). A start is drawn with weight share[g] / count[g].
21
+ rewards.anchor.command_scale {lateral 0.2, other 1.0, vy_min 0.2}
22
+ (c) Per-step multiplier of the anchor weight: `lateral` when |cmd vy| >= vy_min, else `other`.
23
+ rewards.gait_terms {swing_peak {weight, target_m 0.08, dt_scale true}, foot_drag {weight, dt_scale true},
24
+ lateral_shortfall {weight, vy_min 0.2, dt_scale true}}
25
+ (e) Extra reward terms from the NRD-predicted state s1 (FK feet, go2nrd.policy.fk.Go2LegFK; foot-bottom
26
+ height h = foot-sphere centre z - radius (0.022 rigid, 0.025 CRM), z above the nominal surface):
27
+ swing_peak: per foot, the peak h during each gait-clock swing window (phase(k1) >= 0.56, the foot_gait clock,
28
+ k1 = phase counter of s1) is scored when the window ends: sum over ending feet of
29
+ clamp(1 - peak / target_m, 0, 1.5); only windows that started inside the branch; moving commands only.
30
+ foot_drag: sum over feet of relu(-h) |v_foot,xy| (FK foot velocity of s1); moving commands only.
31
+ lateral_shortfall: clamp(1 - v_y,heading sign(cmd vy) / |cmd vy|, 0, 2) when |cmd vy| >= vy_min (v of s1,
32
+ rotated into the heading frame of s1).
33
+ reward += weight (x 0.02 if dt_scale) x term; logged as terms swing_peak / foot_drag / lateral_shortfall.
34
+ Logs (grounds[g]["v3"]): per command category (orig / lateral / diagonal) the settled-step lateral ratio, drag share
35
+ (h < -5 mm and foot speed > 0.1 m/s), mean sinkage, swing peak at window end, anchor deviation, OOD active share,
36
+ and the start-group shares.
37
+
38
+ V3 options (lateral_stuck_20261108 track P "ppo_v3fix"; all default off, a config without them runs as above, bit for
39
+ bit, with the same random draws):
40
+ env.commands.lateral_mix.sign_follow_prob p (default 1.0 = the rule above)
41
+ (2) A lateral / diagonal draw follows the start's recorded vy sign (when |vy_rec| >= sign_min_vy) only with
42
+ probability p; otherwise its sign is +-1 at random. p < 1 draws one extra uniform per env after the command
43
+ draws. With p = 0.5 at least half of all lateral draws have a sign independent of the start state.
44
+ env.start.groups.extra [{dir, file, splits [0], families null, min_steps_left null, min_k null}]
45
+ (1) Extra start sources for the ground block(s) of start.groups (CRM): a StartBank over the rows of `file`
46
+ (npz names / row / lo / hi / group, the same interval format) in data dir `dir`; only starts inside a file
47
+ interval (and with phase_k >= the env's min_phase_k of the ground) can be drawn. Group names of the extra files
48
+ join the share table; a group's count is summed over all its sources, so a start is drawn with weight
49
+ share[g] / count[g] whatever its source. Extra starts always get a lateral-mix command (category lateral;
50
+ their recorded command stream is not in the env's banks, so the env's recorded-stream index is set to 0 for
51
+ them); requires lateral_mix.lateral > 0. Sealed test rows (split 2) are refused by StartBank.
52
+ rewards.gait_terms.wrong_way {weight, vy_min 0.2, cap 2.0, dt_scale true}
53
+ (3) clamp(-v_y,heading sign(cmd vy) / |cmd vy|, 0, cap) when |cmd vy| >= vy_min: the explicit penalty of
54
+ lateral motion against the command (lateral_shortfall saturates at 2 and does not separate "stalled" from
55
+ "wrong way").
56
+ rewards.gait_terms.joint_speed {weight, free_rad_s 4.0, dt_scale true}
57
+ (4) sum over joints of relu(|qd_j(s1)| - free_rad_s)^2 (step-average joint rates of the NRD state s1), all
58
+ commands. With the existing action_rate_l2 / power terms (rewards.terms weights) it is the V3r smoothness /
59
+ energy option.
60
+ Extra logs only when one of these options is on (grounds[g]["v3"][cat]): lat_ratio_pos / lat_ratio_neg (settled
61
+ lateral ratio by command sign), wrong_way_share (settled lateral steps with v_y,heading sign(cmd vy) < -0.05 m/s),
62
+ wrong_way / joint_speed raw terms; all["v3_start_groups"] adds the extra-source share and the reversed-sign share
63
+ of the lateral draws.
64
+ """
65
+ from __future__ import annotations
66
+
67
+ import math
68
+
69
+ import numpy as np
70
+ import torch
71
+
72
+ from go2nrd.collect.common import contract as C
73
+ from go2nrd.policy.fk import Go2LegFK
74
+
75
+ CATS = ("orig", "lateral", "diagonal")
76
+ GAIT_PERIOD_S, GAIT_STANCE = 0.6, 0.56
77
+ GAIT_OFFSETS = (0.0, 0.5, 0.5, 0.0) # FL FR RL RR (rewards.GAIT_OFFSETS_FL_FR_RL_RR)
78
+ FOOT_R = {0: 0.022, 1: 0.025} # ground id -> foot radius (rigid mjlab, CRM)
79
+ LOG_KEYS = ("steps", "lat_steps", "ratio_sum", "drag", "sink", "peak_sum", "peak_n", "anchor_dev", "ood_active",
80
+ "swing_peak", "foot_drag", "lateral_shortfall", "vy_err")
81
+ GAIT_TERMS = ("swing_peak", "foot_drag", "lateral_shortfall")
82
+ FIX_TERMS = ("wrong_way", "joint_speed") # V3 options (track P)
83
+ FIX_LOG_KEYS = ("lat_pos", "ratio_pos", "lat_neg", "ratio_neg", "wrong", "wrong_way", "joint_speed")
84
+ WRONG_WAY_V = 0.05 # m/s against the command = a wrong-way step (logs)
85
+
86
+
87
+ def enabled(cfg):
88
+ ec, rc = cfg.get("env", {}), cfg.get("rewards", {})
89
+ return bool(ec.get("commands", {}).get("lateral_mix") or ec.get("branch_s_lateral") or
90
+ ec.get("start", {}).get("groups") or (rc.get("anchor") or {}).get("command_scale") or
91
+ rc.get("gait_terms"))
92
+
93
+
94
+ def heading_velocity(s):
95
+ """[n, 37] -> [n, 2] base-link velocity (state 19:21, world) in the heading (yaw) frame of the same state."""
96
+ q = s[:, 3:7]
97
+ w, x, y, z = q.unbind(-1)
98
+ yaw = torch.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
99
+ c, sn = torch.cos(yaw), torch.sin(yaw)
100
+ vx, vy = s[:, 19], s[:, 20]
101
+ return torch.stack((c * vx + sn * vy, -sn * vx + c * vy), -1)
102
+
103
+
104
+ class LateralV3:
105
+ def __init__(self, cfg, env):
106
+ ec, rc = cfg["env"], cfg["rewards"]
107
+ self.env = env
108
+ dev = env.device
109
+ n = env.num_envs
110
+ self.n = n
111
+ ground = torch.zeros(n, dtype=torch.long, device=dev)
112
+ for g, b, pool, s in env.blocks:
113
+ ground[s] = g
114
+ self.ground = ground
115
+ self.foot_r = torch.where(ground == C.GROUND_IDS["crm"], FOOT_R[1], FOOT_R[0]).to(torch.float64)
116
+ # (a) commands
117
+ lm = ec.get("commands", {}).get("lateral_mix") or {}
118
+ self.p_lat, self.p_diag = float(lm.get("lateral", 0.0)), float(lm.get("diagonal", 0.0))
119
+ if self.p_lat < 0 or self.p_diag < 0 or self.p_lat + self.p_diag > 1:
120
+ raise ValueError("lateral_mix: 0 <= lateral, diagonal and lateral + diagonal <= 1")
121
+ self.vy = tuple(float(v) for v in lm.get("vy", (0.2, 0.5)))
122
+ self.lat_vx, self.wz = float(lm.get("lateral_vx", 0.1)), float(lm.get("wz", 0.15))
123
+ self.diag_vx = tuple(float(v) for v in lm.get("diag_vx", (0.2, 0.5)))
124
+ self.diag_fwd = float(lm.get("diag_forward_fraction", 0.6))
125
+ self.sign_from_start = bool(lm.get("sign_from_start", True))
126
+ self.sign_min = float(lm.get("sign_min_vy", 0.15))
127
+ self.follow_p = float(lm.get("sign_follow_prob", 1.0)) # (2) V3 option; 1.0 = no extra draw
128
+ if not 0.0 <= self.follow_p <= 1.0:
129
+ raise ValueError("lateral_mix.sign_follow_prob must be in [0, 1]")
130
+ gl = lm.get("grounds")
131
+ self.mix_mask = torch.ones(n, dtype=torch.bool, device=dev) if gl is None else torch.isin(
132
+ ground, torch.tensor([C.GROUND_IDS[x] if isinstance(x, str) else int(x) for x in gl], device=dev))
133
+ self.mix_on = (self.p_lat + self.p_diag) > 0
134
+ # (f) lateral branch length
135
+ bl = ec.get("branch_s_lateral")
136
+ self.lat_steps = int(round(float(bl) / env.dt)) if bl else env.branch_steps
137
+ self.cat = torch.zeros(n, dtype=torch.long, device=dev)
138
+ # (b) start groups
139
+ self.group_sampling = {}
140
+ self.group_names = []
141
+ self.extra_banks = [] # (1) V3 option: extra start sources
142
+ self.drawn_src = torch.zeros(n, dtype=torch.long, device=dev) # source of the last draw: 0 env bank, i + 1 extra i
143
+ self.env_src = torch.zeros(n, dtype=torch.long, device=dev) # source of each env's current start
144
+ self.reversed = torch.zeros(n, dtype=torch.bool, device=dev)
145
+ self.lat_draws = torch.zeros(3, dtype=torch.float64, device=dev) # lateral / diagonal draws, reversed, followed
146
+ gc = ec.get("start", {}).get("groups")
147
+ if gc:
148
+ if getattr(env, "bin_sampling", None):
149
+ raise ValueError("env.start.groups and env.start.crm_bin_share are exclusive")
150
+ self._build_groups(gc)
151
+ G = len(env.ground_ids)
152
+ self.group_starts = torch.zeros(max(len(self.group_names), 1), dtype=torch.float64, device=dev)
153
+ # (c) anchor command scale
154
+ cs = (rc.get("anchor") or {}).get("command_scale")
155
+ self.anchor_scale = None if not cs else dict(lateral=float(cs.get("lateral", 1.0)),
156
+ other=float(cs.get("other", 1.0)),
157
+ vy_min=float(cs.get("vy_min", 0.2)))
158
+ # (e) gait terms
159
+ gt = rc.get("gait_terms") or {}
160
+ sbd = bool(rc.get("scale_by_dt", True))
161
+ self.scales = {}
162
+ self.params = {}
163
+ for name in GAIT_TERMS + FIX_TERMS:
164
+ tc = gt.get(name)
165
+ if tc is None:
166
+ continue
167
+ tc = {"weight": tc} if isinstance(tc, (int, float)) else tc
168
+ w = float(tc["weight"])
169
+ self.scales[name] = w * (C.CONTROL_STEP_S if (bool(tc.get("dt_scale", True)) and sbd) else 1.0)
170
+ self.params[name] = tc
171
+ unknown = set(gt) - set(GAIT_TERMS + FIX_TERMS) - {k for k in gt if k.startswith("_")}
172
+ if unknown:
173
+ raise ValueError(f"rewards.gait_terms: unknown {sorted(unknown)}")
174
+ self.target = float(self.params.get("swing_peak", {}).get("target_m", 0.08))
175
+ self.lat_vy_min = float(self.params.get("lateral_shortfall", {}).get("vy_min", 0.2))
176
+ ww = self.params.get("wrong_way", {})
177
+ self.ww_vy_min, self.ww_cap = float(ww.get("vy_min", 0.2)), float(ww.get("cap", 2.0))
178
+ self.js_free = float(self.params.get("joint_speed", {}).get("free_rad_s", 4.0))
179
+ self.fix_on = bool(self.follow_p < 1.0 or self.extra_banks or any(t in self.params for t in FIX_TERMS))
180
+ if self.extra_banks and not (self.mix_on and self.p_lat > 0):
181
+ raise ValueError("start.groups.extra needs commands.lateral_mix.lateral > 0 (extra starts take lateral "
182
+ "commands)")
183
+ self.fk = Go2LegFK(device=dev)
184
+ self.offsets = torch.tensor(GAIT_OFFSETS, dtype=torch.float64, device=dev)
185
+ self.peak = torch.zeros(n, 4, dtype=torch.float64, device=dev)
186
+ self.valid = torch.zeros(n, 4, dtype=torch.bool, device=dev)
187
+ self.swing_prev = torch.zeros(n, 4, dtype=torch.bool, device=dev)
188
+ self.log_sums = torch.zeros(G * len(CATS), len(LOG_KEYS), dtype=torch.float64, device=dev)
189
+ self.fix_sums = torch.zeros(G * len(CATS), len(FIX_LOG_KEYS), dtype=torch.float64, device=dev) \
190
+ if self.fix_on else None
191
+
192
+ # ------------------------------------------------------------------------------------------------ (b)
193
+ def _build_groups(self, gc):
194
+ env, dev = self.env, self.env.device
195
+ names_file, iv = [], None
196
+ if gc.get("file"):
197
+ z = np.load(gc["file"], allow_pickle=False)
198
+ names_file = [str(x) for x in z["names"]]
199
+ iv = [torch.as_tensor(np.asarray(z[k]), device=dev).long() for k in ("row", "lo", "hi", "group")]
200
+ extras = [self._load_extra(x, i) for i, x in enumerate(gc.get("extra") or [])] # (1) V3 option
201
+ names_x = [nm for x in extras for nm in x["names"] if nm not in names_file]
202
+ names_x = list(dict.fromkeys(names_x))
203
+ names = names_file + names_x + [x for x in ("soft", "other") if x not in names_file + names_x]
204
+ share = gc.get("share", {})
205
+ extra = set(share) - set(names)
206
+ if extra:
207
+ raise ValueError(f"start.groups.share: unknown groups {sorted(extra)} (have {names})")
208
+ sh = torch.tensor([float(share.get(x, 0.0)) for x in names], dtype=torch.float64, device=dev)
209
+ if (sh < 0).any() or sh.sum() <= 0:
210
+ raise ValueError("start.groups.share: non-negative, sum > 0")
211
+ gl = gc.get("grounds", ["crm"])
212
+ ids = [C.GROUND_IDS[x] if isinstance(x, str) else int(x) for x in gl]
213
+ from go2nrd.rl.env import soil_bin_index
214
+ self.group_names = names
215
+ self.group_info = {}
216
+ for bi, (g, b, pool, s) in enumerate(env.blocks):
217
+ if g not in ids:
218
+ continue
219
+ bank = env.banks[b]
220
+ e, k = bank.start_e[pool], bank.start_k[pool]
221
+ row = torch.as_tensor(np.asarray(bank.rows), device=dev).long()[e]
222
+ r0 = 2 * k
223
+ grp = torch.full((len(pool),), -1, dtype=torch.long, device=dev)
224
+ if iv is not None:
225
+ for j in range(len(names_file)):
226
+ sel = iv[3] == j
227
+ m = torch.zeros(len(pool), dtype=torch.bool, device=dev)
228
+ for rr, lo, hi in zip(iv[0][sel].tolist(), iv[1][sel].tolist(), iv[2][sel].tolist()):
229
+ m |= (row == rr) & (r0 >= lo) & (r0 < hi)
230
+ grp = torch.where((grp < 0) & m, torch.full_like(grp, j), grp)
231
+ soft = soil_bin_index(bank.ground_features[e]) == 0
232
+ grp = torch.where((grp < 0) & soft, torch.full_like(grp, names.index("soft")), grp)
233
+ grp = torch.where(grp < 0, torch.full_like(grp, names.index("other")), grp)
234
+ cnt = torch.bincount(grp, minlength=len(names)).to(torch.float64)
235
+ if not extras: # Track B path (unchanged numbers)
236
+ empty = [names[i] for i in range(len(names)) if cnt[i] == 0 and sh[i] > 0]
237
+ if empty:
238
+ raise ValueError(f"start.groups: no starts in group(s) {empty} of ground {g}")
239
+ w = torch.where(cnt[grp] > 0, sh[grp] / cnt[grp].clamp_min(1.0), torch.zeros_like(sh[grp]))
240
+ self.group_sampling[bi] = (w, grp)
241
+ self.group_info[str(g)] = dict(counts={nm: int(c) for nm, c in zip(names, cnt.tolist())},
242
+ share={nm: float(v) for nm, v in zip(names, (sh / sh.sum()).tolist())},
243
+ pool=int(len(pool)))
244
+ continue
245
+ # extra sources of this ground: group index per extra start (-1 = not drawable)
246
+ xg, srcs = [], []
247
+ min_pk = int(env.cfg["env"].get("start", {}).get("min_phase_k", {}).get(
248
+ {v: k for k, v in C.GROUND_IDS.items()}.get(g, str(g)), 0))
249
+ for x in extras:
250
+ xb = x["bank"]
251
+ ok = (xb.ground[xb.start_e] == g) & (xb.phase_k[xb.start_e, 2 * xb.start_k] >= min_pk)
252
+ gx = torch.where(ok & (x["grp"] >= 0), torch.tensor([names.index(nm) for nm in x["names"]],
253
+ device=dev)[x["grp"].clamp_min(0)],
254
+ torch.full_like(x["grp"], -1))
255
+ xg.append(gx)
256
+ srcs.append(dict(name=x["name"], dir=x["dir"], starts=int(xb.n), drawable=int((gx >= 0).sum())))
257
+ cnt_all = cnt.clone()
258
+ for gx in xg:
259
+ cnt_all += torch.bincount(gx[gx >= 0], minlength=len(names)).to(torch.float64)
260
+ empty = [names[i] for i in range(len(names)) if cnt_all[i] == 0 and sh[i] > 0]
261
+ if empty:
262
+ raise ValueError(f"start.groups: no starts in group(s) {empty} of ground {g}")
263
+ wt = lambda gg: torch.where(gg >= 0, sh[gg.clamp_min(0)] / cnt_all[gg.clamp_min(0)].clamp_min(1.0),
264
+ torch.zeros_like(sh[gg.clamp_min(0)]))
265
+ w_all = torch.cat([wt(grp)] + [wt(gx) for gx in xg])
266
+ g_all = torch.cat([grp] + [gx.clamp_min(0) for gx in xg])
267
+ offs, o = [], len(pool)
268
+ for x, gx in zip(extras, xg):
269
+ offs.append((x["bank"], o, len(gx)))
270
+ o += len(gx)
271
+ self.group_sampling[bi] = (w_all, g_all, offs, s)
272
+ per_src = {"env_bank": {nm: int(c) for nm, c in zip(names, cnt.tolist())}}
273
+ for x, gx in zip(extras, xg):
274
+ per_src[x["name"]] = {nm: int((gx == i).sum()) for i, nm in enumerate(names) if int((gx == i).sum())}
275
+ self.group_info[str(g)] = dict(counts={nm: int(c) for nm, c in zip(names, cnt_all.tolist())},
276
+ counts_by_source=per_src,
277
+ share={nm: float(v) for nm, v in zip(names, (sh / sh.sum()).tolist())},
278
+ pool=int(len(pool)), extra_sources=srcs)
279
+ self.extra_banks = [x["bank"] for x in extras]
280
+
281
+ def _load_extra(self, xc, i):
282
+ """(1) One extra start source: StartBank over the interval rows of xc["file"] in xc["dir"] -> dict(bank, grp
283
+ (group index into the file's names per bank start, -1 = outside every interval), names, name, dir)."""
284
+ from go2nrd.sim.bank import StartBank
285
+ env, dev = self.env, self.env.device
286
+ sc = env.cfg["env"].get("start", {})
287
+ z = np.load(xc["file"], allow_pickle=False)
288
+ names = [str(x) for x in z["names"]]
289
+ row, lo, hi, gi = (np.asarray(z[k]).astype(np.int64) for k in ("row", "lo", "hi", "group"))
290
+ rows = np.unique(row)
291
+ if xc.get("rows") is not None:
292
+ if not np.isin(rows, np.asarray(xc["rows"])).all():
293
+ raise ValueError(f"start.groups.extra[{i}]: interval rows outside the given rows")
294
+ K = int(getattr(env.sim, "k", 4))
295
+ bank = StartBank(xc["dir"], splits=tuple(xc.get("splits", (0,))), families=xc.get("families", sc.get("families")),
296
+ min_steps_left=int(xc.get("min_steps_left", sc.get("min_steps_left", 1))),
297
+ min_k=max(int(xc.get("min_k", sc.get("min_k", K - 1))), K - 1), device=dev, history=K,
298
+ rows=rows.tolist())
299
+ e, k = bank.start_e, bank.start_k
300
+ brow = torch.as_tensor(np.asarray(bank.rows), device=dev).long()[e]
301
+ r0 = 2 * k
302
+ grp = torch.full((bank.n,), -1, dtype=torch.long, device=dev)
303
+ for rr, a, b, gg in zip(row.tolist(), lo.tolist(), hi.tolist(), gi.tolist()):
304
+ m = (brow == rr) & (r0 >= a) & (r0 < b) & (grp < 0)
305
+ grp = torch.where(m, torch.full_like(grp, gg), grp)
306
+ return dict(bank=bank, grp=grp, names=names, name=str(xc.get("name", f"extra{i}")), dir=str(xc["dir"]))
307
+
308
+ def draw_block(self, bi, b, pool, m, gen):
309
+ """m starts of block bi (start-group weights) -> bank.draw dict."""
310
+ gs = self.group_sampling[bi]
311
+ w, grp = gs[0], gs[1]
312
+ j = torch.multinomial(w, m, replacement=True, generator=gen)
313
+ self.group_starts.index_add_(0, grp[j], torch.ones(m, dtype=torch.float64, device=w.device))
314
+ if len(gs) == 2: # Track B path
315
+ return self.env.banks[b].draw(pool[j])
316
+ offs, s = gs[2], gs[3]
317
+ main = j < len(pool)
318
+ st = self.env.banks[b].draw(pool[torch.where(main, j, torch.zeros_like(j))])
319
+ src = torch.zeros(m, dtype=torch.long, device=w.device)
320
+ for xi, (xb, off, cnt) in enumerate(offs):
321
+ sel = (j >= off) & (j < off + cnt)
322
+ if not bool(sel.any()):
323
+ continue
324
+ sx = xb.draw(torch.where(sel, j - off, torch.zeros_like(j)))
325
+ for key, v in st.items():
326
+ st[key] = torch.where(sel.view(-1, *([1] * (v.dim() - 1))), sx[key].to(v.dtype), v)
327
+ src = torch.where(sel, torch.full_like(src, xi + 1), src)
328
+ self.drawn_src[s] = src
329
+ return st
330
+
331
+ # ------------------------------------------------------------------------------------------------ (a), (f)
332
+ def on_reset(self, mask, start):
333
+ env, n, dev, gen = self.env, self.n, self.env.device, self.env.gen
334
+ m = mask
335
+ if self.mix_on:
336
+ u = torch.rand(n, device=dev, generator=gen)
337
+ cat = torch.where(u < self.p_lat, 1, torch.where(u < self.p_lat + self.p_diag, 2, 0)).to(torch.long)
338
+ cat = torch.where(self.mix_mask, cat, torch.zeros_like(cat))
339
+ r = torch.rand(n, 6, device=dev, generator=gen)
340
+ if self.extra_banks: # (1) extra starts: always a lateral command
341
+ cat = torch.where(self.drawn_src > 0, torch.ones_like(cat), cat)
342
+ mag = self.vy[0] + (self.vy[1] - self.vy[0]) * r[:, 0]
343
+ rnd_sign = torch.where(r[:, 1] < 0.5, -1.0, 1.0)
344
+ rec_vy = start["command"][:, 1].float()
345
+ follow = (rec_vy.abs() >= self.sign_min) & torch.tensor(self.sign_from_start, device=dev)
346
+ if self.follow_p < 1.0: # (2) V3 option: one extra draw per env
347
+ follow = follow & (torch.rand(n, device=dev, generator=gen) < self.follow_p)
348
+ sign = torch.where(follow, torch.sign(rec_vy), rnd_sign)
349
+ if self.fix_on:
350
+ rev = (rec_vy.abs() >= self.sign_min) & (sign != torch.sign(rec_vy)) & (cat > 0)
351
+ self.reversed = torch.where(m, rev, self.reversed)
352
+ self.lat_draws += torch.stack(((m & (cat > 0)).sum(), (m & rev).sum(),
353
+ (m & (cat > 0) & follow).sum())).to(torch.float64)
354
+ vy = sign * mag
355
+ wz = self.wz * (2 * r[:, 2] - 1)
356
+ vx_lat = self.lat_vx * (2 * r[:, 3] - 1)
357
+ dmag = self.diag_vx[0] + (self.diag_vx[1] - self.diag_vx[0]) * r[:, 4]
358
+ vx_diag = torch.where(r[:, 5] < self.diag_fwd, dmag, -dmag)
359
+ vx = torch.where(cat == 1, vx_lat, vx_diag)
360
+ new_cmd = torch.stack((vx, vy, wz), -1)
361
+ take = m & (cat > 0)
362
+ self.cat = torch.where(m, cat, self.cat)
363
+ env.cmd_mode = torch.where(take, torch.zeros_like(env.cmd_mode), env.cmd_mode)
364
+ env.env_cmd = torch.where(take[:, None], new_cmd, env.env_cmd)
365
+ env.resample_at = torch.where(take, torch.full_like(env.resample_at, -1), env.resample_at)
366
+ env.loop.command = torch.where(take[:, None], new_cmd, env.loop.command)
367
+ env.cmd_prev = torch.where(take[:, None], new_cmd, env.cmd_prev)
368
+ if self.extra_banks: # recorded-stream index of extra starts: unused
369
+ xm = m & (self.drawn_src > 0) # (cmd_mode False), must index the env bank
370
+ self.env_src = torch.where(m, self.drawn_src, self.env_src)
371
+ env.rec_e = torch.where(xm, torch.zeros_like(env.rec_e), env.rec_e)
372
+ env.rec_k0 = torch.where(xm, torch.zeros_like(env.rec_k0), env.rec_k0)
373
+ if self.lat_steps != env.branch_steps:
374
+ lat = m & (self.cat == 1)
375
+ env.limit = torch.where(lat, torch.full_like(env.limit, self.lat_steps), env.limit)
376
+ # gait-clock trackers: a window is scored only if its start is seen inside the branch
377
+ self.valid = torch.where(m[:, None], torch.zeros_like(self.valid), self.valid)
378
+ self.swing_prev = torch.where(m[:, None], self.clock_swing(env.loop.k), self.swing_prev)
379
+
380
+ def after_stagger(self):
381
+ env = self.env
382
+ if self.lat_steps != env.branch_steps:
383
+ lat = self.cat == 1
384
+ stretched = torch.ceil(env.limit.to(torch.float64) * self.lat_steps / env.branch_steps).long()
385
+ env.limit = torch.where(lat, stretched.clamp(1, self.lat_steps), env.limit)
386
+
387
+ def set_category(self, cat):
388
+ """Evaluation: explicit command category of each env (logs only)."""
389
+ self.cat = torch.as_tensor(cat, device=self.env.device).long().clone()
390
+
391
+ # ------------------------------------------------------------------------------------------------ (c)
392
+ def anchor_factor(self, cmd):
393
+ a = self.anchor_scale
394
+ lat = cmd[:, 1].abs() >= a["vy_min"]
395
+ return torch.where(lat, torch.full_like(cmd[:, 1], a["lateral"]), torch.full_like(cmd[:, 1], a["other"]))
396
+
397
+ # ------------------------------------------------------------------------------------------------ (e)
398
+ def clock_swing(self, k):
399
+ ph = (k.to(torch.long).to(torch.float64) * C.CONTROL_STEP_S / GAIT_PERIOD_S)[:, None] + self.offsets
400
+ return (ph % 1.0) >= GAIT_STANCE
401
+
402
+ def gait(self, s1, k0, cmd):
403
+ """Raw gait terms [n] (float32) and per-step foot diagnostics; updates the swing trackers."""
404
+ f64 = torch.float64
405
+ pos = self.fk.foot_positions(s1)
406
+ vel = self.fk.foot_velocities(s1)
407
+ h = pos[..., 2] - self.foot_r[:, None]
408
+ speed = torch.linalg.norm(vel[..., :2], dim=-1)
409
+ moving = (torch.linalg.norm(cmd[:, :2], dim=-1) + cmd[:, 2].abs() > 0.1).to(f64)
410
+ swing = self.clock_swing(k0 + 1)
411
+ starting = swing & ~self.swing_prev
412
+ cont = swing & self.swing_prev
413
+ ending = ~swing & self.swing_prev & self.valid
414
+ self.peak = torch.where(starting, h, torch.where(cont, torch.maximum(self.peak, h), self.peak))
415
+ self.valid = torch.where(starting, torch.ones_like(self.valid), self.valid)
416
+ short = (1.0 - self.peak / self.target).clamp(0.0, 1.5)
417
+ t = {}
418
+ t["swing_peak"] = (short * ending.to(f64)).sum(-1) * moving
419
+ t["foot_drag"] = ((-h).clamp_min(0.0) * speed).sum(-1) * moving
420
+ vh = heading_velocity(s1)
421
+ vy_c = cmd[:, 1].to(f64)
422
+ lat = vy_c.abs() >= self.lat_vy_min
423
+ along = vh[:, 1] * torch.sign(vy_c)
424
+ t["lateral_shortfall"] = torch.where(lat, (1.0 - along / vy_c.abs().clamp_min(1e-6)).clamp(0.0, 2.0),
425
+ torch.zeros_like(along))
426
+ if "wrong_way" in self.params: # (3) V3 option
427
+ ww = vy_c.abs() >= self.ww_vy_min
428
+ t["wrong_way"] = torch.where(ww, (-along / vy_c.abs().clamp_min(1e-6)).clamp(0.0, self.ww_cap),
429
+ torch.zeros_like(along))
430
+ if "joint_speed" in self.params: # (4) V3 option
431
+ t["joint_speed"] = (s1[:, 25:37].abs() - self.js_free).clamp_min(0.0).square().sum(-1)
432
+ diag = dict(h=h, speed=speed, ending=ending, peak=self.peak.clone(), along=along, lat=lat, vh=vh)
433
+ self.valid = torch.where(ending, torch.zeros_like(self.valid), self.valid)
434
+ self.swing_prev = swing
435
+ return {k: v.to(torch.float32) for k, v in t.items()}, diag
436
+
437
+ def apply(self, s1, k0, cmd, rew, terms):
438
+ t, diag = self.gait(s1, k0, cmd)
439
+ terms = dict(terms)
440
+ for name, sc in self.scales.items():
441
+ rew = rew + sc * t[name]
442
+ for name in t:
443
+ terms[name] = t[name]
444
+ self.last_diag = diag
445
+ return rew, terms
446
+
447
+ # ------------------------------------------------------------------------------------------------ logs
448
+ def accumulate(self, terms, cmd, ood, settled):
449
+ env = self.env
450
+ f = torch.float64
451
+ d = getattr(self, "last_diag", None)
452
+ if d is None:
453
+ return
454
+ trk = settled.to(f)
455
+ lat = d["lat"].to(f) * trk
456
+ vy = cmd[:, 1].to(f)
457
+ ratio = torch.where(d["lat"], d["along"] / vy.abs().clamp_min(1e-6), torch.zeros_like(vy))
458
+ drag = ((d["h"] < -0.005) & (d["speed"] > 0.1)).to(f).mean(-1)
459
+ sink = (-d["h"]).clamp_min(0.0).mean(-1)
460
+ end = d["ending"].to(f)
461
+ zero = torch.zeros_like(trk)
462
+ cols = [trk, lat, ratio * lat, drag * trk, sink * trk, (d["peak"] * end).sum(-1) * trk, end.sum(-1) * trk,
463
+ terms.get("anchor_dev", zero).to(f) * trk, (ood > 0).to(f) * trk,
464
+ terms["swing_peak"].to(f) * trk, terms["foot_drag"].to(f) * trk, terms["lateral_shortfall"].to(f) * trk,
465
+ (d["vh"][:, 1] - vy).abs() * lat]
466
+ idx = env.ground_idx * len(CATS) + self.cat
467
+ self.log_sums.index_add_(0, idx, torch.stack(cols, -1))
468
+ if self.fix_sums is not None: # V3 option logs
469
+ pos, neg = lat * (vy > 0).to(f), lat * (vy < 0).to(f)
470
+ fx = [pos, ratio * pos, neg, ratio * neg, lat * (d["along"] < -WRONG_WAY_V).to(f),
471
+ terms.get("wrong_way", zero).to(f) * trk, terms.get("joint_speed", zero).to(f) * trk]
472
+ self.fix_sums.index_add_(0, idx, torch.stack(fx, -1))
473
+
474
+ def pop(self):
475
+ sums = self.log_sums.cpu().numpy()
476
+ self.log_sums.zero_()
477
+ gs = self.group_starts.cpu().numpy()
478
+ self.group_starts.zero_()
479
+ K = {k: i for i, k in enumerate(LOG_KEYS)}
480
+ fsum = None
481
+ if self.fix_sums is not None:
482
+ fsum = self.fix_sums.cpu().numpy()
483
+ self.fix_sums.zero_()
484
+ FK = {k: i for i, k in enumerate(FIX_LOG_KEYS)}
485
+ out = {}
486
+ for gi, name in enumerate(self.env.ground_names):
487
+ o = {}
488
+ for ci, c in enumerate(CATS):
489
+ r = sums[gi * len(CATS) + ci]
490
+ st, ls, pn = r[K["steps"]], r[K["lat_steps"]], r[K["peak_n"]]
491
+ if st <= 0:
492
+ continue
493
+ o[c] = dict(steps=float(st), lat_steps=float(ls),
494
+ lat_ratio=float(r[K["ratio_sum"]] / ls) if ls > 0 else None,
495
+ vy_abs_err=float(r[K["vy_err"]] / ls) if ls > 0 else None,
496
+ drag_frac=float(r[K["drag"]] / st), sink_mean_m=float(r[K["sink"]] / st),
497
+ swing_peak_m=float(r[K["peak_sum"]] / pn) if pn > 0 else None,
498
+ anchor_dev=float(r[K["anchor_dev"]] / st), ood_active=float(r[K["ood_active"]] / st),
499
+ swing_peak=float(r[K["swing_peak"]] / st), foot_drag=float(r[K["foot_drag"]] / st),
500
+ lateral_shortfall=float(r[K["lateral_shortfall"]] / st))
501
+ if fsum is not None:
502
+ q = fsum[gi * len(CATS) + ci]
503
+ rt = lambda a, b: float(q[FK[a]] / q[FK[b]]) if q[FK[b]] > 0 else None
504
+ o[c].update(lat_ratio_pos=rt("ratio_pos", "lat_pos"), lat_ratio_neg=rt("ratio_neg", "lat_neg"),
505
+ wrong_way_share=float(q[FK["wrong"]] / ls) if ls > 0 else None,
506
+ wrong_way=float(q[FK["wrong_way"]] / st), joint_speed=float(q[FK["joint_speed"]] / st))
507
+ out[name] = o
508
+ if self.group_names:
509
+ tot = max(float(gs.sum()), 1.0)
510
+ out["start_groups"] = {nm: float(gs[i] / tot) for i, nm in enumerate(self.group_names)}
511
+ if self.fix_on:
512
+ ld = self.lat_draws.cpu().numpy()
513
+ self.lat_draws.zero_()
514
+ sg = out.setdefault("start_groups", {})
515
+ sg["_reversed_share_of_lateral_draws"] = float(ld[1] / ld[0]) if ld[0] > 0 else None
516
+ sg["_sign_follows_start_share_of_lateral_draws"] = float(ld[2] / ld[0]) if ld[0] > 0 else None
517
+ return out
518
+
519
+ def describe(self):
520
+ return dict(lateral_mix=dict(lateral=self.p_lat, diagonal=self.p_diag, vy=list(self.vy), lateral_vx=self.lat_vx,
521
+ wz=self.wz, diag_vx=list(self.diag_vx), diag_forward_fraction=self.diag_fwd,
522
+ sign_from_start=self.sign_from_start, sign_min_vy=self.sign_min,
523
+ sign_follow_prob=self.follow_p),
524
+ lateral_branch_steps=self.lat_steps, branch_steps=self.env.branch_steps,
525
+ start_groups=getattr(self, "group_info", None), anchor_command_scale=self.anchor_scale,
526
+ gait_terms={k: dict(self.params[k], per_step_scale=v) for k, v in self.scales.items()},
527
+ swing_target_m=self.target, v3fix_options_on=self.fix_on,
528
+ wrong_way=dict(vy_min=self.ww_vy_min, cap=self.ww_cap) if "wrong_way" in self.params else None,
529
+ joint_speed_free_rad_s=self.js_free if "joint_speed" in self.params else None)
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/ppo.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FineTunePPO: rsl_rl 5.0.1 PPO (rsl_rl/algorithms/ppo.py) with the fine-tune changes:
2
+
3
+ - one Adam with three parameter groups: actor MLP (lr actor_lr), action std (std_lr), critic (critic_lr); fixed
4
+ learning rates (no adaptive schedule; KL is still measured and logged);
5
+ - critic warm-up: while actor_frozen, the loss is the value loss only and the actor / std groups have lr 0 (their
6
+ Adam moments are not touched, so the actor starts clean after the warm-up);
7
+ - std bounds: after each optimiser step the scalar std is clamped to [std_min, std_max];
8
+ - time-out bootstrap from the FINAL observation: reward += gamma V(final_obs) on time-outs (extras["final_obs"]),
9
+ instead of rsl_rl's V(obs before the step) (time_out_bootstrap "final"; "before" = rsl_rl's rule; "none");
10
+ - extra loss statistics: KL, clip fraction, explained variance of the value targets.
11
+ Symmetry, RND and multi-GPU are not supported here (not used).
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+
18
+ from rsl_rl.algorithms import PPO
19
+
20
+
21
+ class FineTunePPO(PPO):
22
+ def __init__(self, actor, critic, storage, actor_lr=1e-4, critic_lr=1e-3, std_lr=None, std_min=0.05,
23
+ std_max=0.15, time_out_bootstrap="final", **kw):
24
+ kw.setdefault("schedule", "fixed")
25
+ super().__init__(actor, critic, storage, learning_rate=actor_lr, **kw)
26
+ if self.rnd or self.symmetry or self.is_multi_gpu:
27
+ raise ValueError("FineTunePPO: RND / symmetry / multi-GPU are not supported")
28
+ std_params = [p for n, p in self.actor.named_parameters() if n.startswith("distribution.")]
29
+ mlp_params = [p for n, p in self.actor.named_parameters() if not n.startswith("distribution.")]
30
+ self.lrs = dict(actor=float(actor_lr), std=float(actor_lr if std_lr is None else std_lr),
31
+ critic=float(critic_lr))
32
+ self.optimizer = torch.optim.Adam([dict(params=mlp_params, lr=self.lrs["actor"], name="actor"),
33
+ dict(params=std_params, lr=self.lrs["std"], name="std"),
34
+ dict(params=list(self.critic.parameters()), lr=self.lrs["critic"],
35
+ name="critic")])
36
+ self.std_min, self.std_max = std_min, std_max
37
+ if time_out_bootstrap not in ("final", "before", "none"):
38
+ raise ValueError(f"time_out_bootstrap {time_out_bootstrap!r}")
39
+ self.time_out_bootstrap = time_out_bootstrap
40
+ self.actor_frozen = False
41
+ self.clamp_std()
42
+
43
+ # ------------------------------------------------------------------------------------------------ helpers
44
+ def set_actor_frozen(self, frozen: bool):
45
+ self.actor_frozen = bool(frozen)
46
+ for g in self.optimizer.param_groups:
47
+ if g["name"] in ("actor", "std"):
48
+ g["lr"] = 0.0 if frozen else self.lrs[g["name"]]
49
+ self.learning_rate = 0.0 if frozen else self.lrs["actor"]
50
+
51
+ @torch.no_grad()
52
+ def clamp_std(self):
53
+ d = self.actor.distribution
54
+ if hasattr(d, "std_param") and (self.std_min is not None or self.std_max is not None):
55
+ d.std_param.clamp_(min=self.std_min, max=self.std_max)
56
+
57
+ # ------------------------------------------------------------------------------------------------ rollout
58
+ def process_env_step(self, obs, rewards, dones, extras):
59
+ self.actor.update_normalization(obs) # no-op when the normalisers are frozen
60
+ self.critic.update_normalization(obs)
61
+ self.transition.rewards = rewards.clone()
62
+ self.transition.dones = dones
63
+ if "time_outs" in extras and self.time_out_bootstrap != "none":
64
+ to = extras["time_outs"].to(self.device).float()
65
+ if self.time_out_bootstrap == "final" and "final_obs" in extras:
66
+ v = self.critic(extras["final_obs"].to(self.device)).detach()
67
+ else:
68
+ v = self.transition.values
69
+ self.transition.rewards += self.gamma * (v.squeeze(-1) * to)
70
+ self.storage.add_transition(self.transition)
71
+ self.transition.clear()
72
+ self.actor.reset(dones)
73
+ self.critic.reset(dones)
74
+
75
+ # ------------------------------------------------------------------------------------------------ update
76
+ def update(self):
77
+ stats = dict(value=0.0, surrogate=0.0, entropy=0.0, kl=0.0, clip_frac=0.0)
78
+ generator = self.storage.mini_batch_generator(self.num_mini_batches, self.num_learning_epochs)
79
+ ret = self.storage.returns.flatten()
80
+ val = self.storage.values.flatten()
81
+ ev = float(1.0 - (ret - val).var() / ret.var().clamp_min(1e-12))
82
+ n_up = 0
83
+ for batch in generator:
84
+ if self.normalize_advantage_per_mini_batch:
85
+ with torch.no_grad():
86
+ batch.advantages = (batch.advantages - batch.advantages.mean()) / (batch.advantages.std() + 1e-8)
87
+ self.actor(batch.observations, masks=batch.masks, hidden_state=batch.hidden_states[0],
88
+ stochastic_output=True)
89
+ logp = self.actor.get_output_log_prob(batch.actions)
90
+ values = self.critic(batch.observations, masks=batch.masks, hidden_state=batch.hidden_states[1])
91
+ params = self.actor.output_distribution_params
92
+ entropy = self.actor.output_entropy
93
+ with torch.inference_mode():
94
+ kl = self.actor.get_kl_divergence(batch.old_distribution_params, params).mean()
95
+ ratio = torch.exp(logp - torch.squeeze(batch.old_actions_log_prob))
96
+ adv = torch.squeeze(batch.advantages)
97
+ surrogate = torch.max(-adv * ratio, -adv * torch.clamp(ratio, 1.0 - self.clip_param, 1.0 + self.clip_param)).mean()
98
+ if self.use_clipped_value_loss:
99
+ vc = batch.values + (values - batch.values).clamp(-self.clip_param, self.clip_param)
100
+ value_loss = torch.max((values - batch.returns).pow(2), (vc - batch.returns).pow(2)).mean()
101
+ else:
102
+ value_loss = (batch.returns - values).pow(2).mean()
103
+ if self.actor_frozen:
104
+ loss = self.value_loss_coef * value_loss
105
+ else:
106
+ loss = surrogate + self.value_loss_coef * value_loss - self.entropy_coef * entropy.mean()
107
+ self.optimizer.zero_grad(set_to_none=True)
108
+ loss.backward()
109
+ if not self.actor_frozen:
110
+ nn.utils.clip_grad_norm_(self.actor.parameters(), self.max_grad_norm)
111
+ nn.utils.clip_grad_norm_(self.critic.parameters(), self.max_grad_norm)
112
+ self.optimizer.step()
113
+ self.clamp_std()
114
+ with torch.no_grad():
115
+ cf = ((ratio - 1.0).abs() > self.clip_param).float().mean()
116
+ for k, v in (("value", value_loss), ("surrogate", surrogate), ("entropy", entropy.mean()), ("kl", kl),
117
+ ("clip_frac", cf)):
118
+ stats[k] += float(v)
119
+ n_up += 1
120
+ self.storage.clear()
121
+ out = {k: v / max(n_up, 1) for k, v in stats.items()}
122
+ out["explained_variance"] = ev
123
+ return out
124
+
125
+ def save(self):
126
+ d = super().save()
127
+ d["finetune_ppo"] = dict(lrs=self.lrs, std_min=self.std_min, std_max=self.std_max,
128
+ actor_frozen=self.actor_frozen, time_out_bootstrap=self.time_out_bootstrap)
129
+ return d
go2_sand_finetune/code/browse/ppo_snapshot_8e08e2544f0d/src/go2nrd/rl/runner.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FineTuneRunner: PPO fine-tune of model_10000.pt inside the Go2 NRD (rsl-rl-lib 5.0.1 models, storage and PPO core).
2
+
3
+ - Models: rsl_rl MLPModel actor 47-512-256-128-12 ELU (obs normalisation, Gaussian scalar std) and critic
4
+ 74-512-256-128-1, exactly the layout of the mjlab run (agent.yaml), loaded from the checkpoint with strict=True
5
+ (actor, critic, both normalisers; not the optimiser). Normalisers frozen (until = 1; their count is 9.8e8).
6
+ - Action std = min(checkpoint std, ppo.std_max); learnable, clamped to [ppo.std_min, ppo.std_max] after every step.
7
+ - Critic warm-up: runner.warmup_iterations with the actor frozen (value loss only, actor lr 0); then actor lr
8
+ ppo.actor_lr (1e-4), critic lr ppo.critic_lr (1e-3) throughout.
9
+ - Guard (Study 4 rule, rl_cfg.py / hooks.py RegressionGuard): over a window of `window` post-warm-up iterations,
10
+ stop when more than `spike_fraction` of them had a mean OOD cost above `ood_spike` AND the window-mean reward fell
11
+ more than `reward_drop` (relative) below its best window mean. healthy.pt = the newest checkpoint written while
12
+ the guard was healthy.
13
+ - Checkpoints (rsl_rl layout + "infos"): model_0.pt (the start policy, std capped, before any update),
14
+ model_<it>.pt every save_interval, last.pt every checkpoint_interval and at the end; re-running the same command
15
+ resumes from last.pt; complete.json marks the end (max iterations or guard). SIGTERM / SIGUSR1 / SIGINT: save
16
+ last.pt after the current iteration and exit 0 (the AMD sbatch resubmits).
17
+ - Action anchor (rewards.anchor, go2nrd.rl.env): before each env step the runner hands the policy mean of the
18
+ step to the env (env.action_mean); the env's frozen reference actor is built from the init checkpoint (or
19
+ rewards.anchor.reference), so a resume keeps the same reference.
20
+ - Logging: metrics.jsonl (one row per iteration: losses, lr, std, timing, throughput, per-ground tracking errors,
21
+ power, torque saturation, OOD, falls, per-term rewards), stdout every log_interval.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import math
27
+ import os
28
+ import signal
29
+ import time
30
+ from collections import deque
31
+ from pathlib import Path
32
+
33
+ import torch
34
+
35
+ from rsl_rl.models import MLPModel
36
+ from rsl_rl.modules.distribution import GaussianDistribution
37
+ from rsl_rl.storage import RolloutStorage
38
+
39
+ from go2nrd.rl.config import strip_comments
40
+ from go2nrd.rl.env import Go2NrdVecEnv
41
+ from go2nrd.rl.ppo import FineTunePPO
42
+
43
+ OBS_GROUPS = {"actor": ["actor"], "critic": ["critic"]}
44
+
45
+
46
+ class Guard:
47
+ def __init__(self, window=50, ood_spike=0.005, spike_fraction=0.6, reward_drop=0.25, enabled=True):
48
+ self.window, self.ood_spike = int(window), float(ood_spike)
49
+ self.spike_fraction, self.reward_drop, self.enabled = float(spike_fraction), float(reward_drop), bool(enabled)
50
+ self.spikes, self.rewards = deque(maxlen=self.window), deque(maxlen=self.window)
51
+ self.best = None
52
+ self.last = dict(spike_frac=0.0, drop=0.0, healthy=True, tripped=False)
53
+
54
+ def update(self, ood_mean, reward_mean):
55
+ self.spikes.append(float(ood_mean) > self.ood_spike)
56
+ self.rewards.append(float(reward_mean))
57
+ wmean = sum(self.rewards) / len(self.rewards)
58
+ full = len(self.rewards) == self.window
59
+ if full:
60
+ self.best = wmean if self.best is None else max(self.best, wmean)
61
+ frac = sum(self.spikes) / len(self.spikes)
62
+ drop = (self.best - wmean) / max(abs(self.best), 1e-9) if self.best is not None else 0.0
63
+ tripped = self.enabled and full and frac > self.spike_fraction and drop > self.reward_drop
64
+ self.last = dict(spike_frac=frac, drop=drop, window_reward=wmean, best_window_reward=self.best,
65
+ healthy=not (frac > self.spike_fraction or drop > self.reward_drop), tripped=tripped)
66
+ return tripped
67
+
68
+ def state(self):
69
+ return dict(spikes=list(self.spikes), rewards=list(self.rewards), best=self.best, last=self.last)
70
+
71
+ def load(self, st):
72
+ self.spikes.extend(st.get("spikes", []))
73
+ self.rewards.extend(st.get("rewards", []))
74
+ self.best = st.get("best")
75
+ self.last = st.get("last", self.last)
76
+
77
+
78
+ class FineTuneRunner:
79
+ def __init__(self, cfg: dict, out_dir, device="cuda"):
80
+ self.cfg = cfg
81
+ self.out = Path(out_dir)
82
+ self.out.mkdir(parents=True, exist_ok=True)
83
+ self.device = torch.device(device)
84
+ seed = int(cfg.get("seed", 1))
85
+ torch.manual_seed(seed)
86
+ if cfg.get("nrd", {}).get("tf32", False):
87
+ torch.backends.cuda.matmul.allow_tf32 = True
88
+ t0 = time.time()
89
+ self.env = Go2NrdVecEnv(cfg, self.device, train=True)
90
+ self.build_s = time.time() - t0
91
+ pc, rc = cfg["ppo"], cfg["runner"]
92
+ self.num_steps = int(rc.get("num_steps_per_env", 24))
93
+ obs = self.env.get_observations()
94
+ hid = tuple(pc.get("hidden_dims", (512, 256, 128)))
95
+ self.actor = MLPModel(obs, OBS_GROUPS, "actor", self.env.num_actions, hidden_dims=hid, activation="elu",
96
+ obs_normalization=True,
97
+ distribution_cfg=dict(class_name=GaussianDistribution, init_std=1.0,
98
+ std_type="scalar")).to(self.device)
99
+ self.critic = MLPModel(obs, OBS_GROUPS, "critic", 1, hidden_dims=hid, activation="elu",
100
+ obs_normalization=True).to(self.device)
101
+ # initial weights from the mjlab checkpoint
102
+ ck = torch.load(cfg["init_checkpoint"], map_location=self.device, weights_only=False)
103
+ self.actor.load_state_dict(ck["actor_state_dict"], strict=True)
104
+ self.critic.load_state_dict(ck["critic_state_dict"], strict=True)
105
+ self.checkpoint_std = ck["actor_state_dict"]["distribution.std_param"].tolist()
106
+ self.checkpoint_iter = int(ck.get("iter", -1))
107
+ for m in (self.actor, self.critic):
108
+ if cfg["runner"].get("freeze_normalizers", True):
109
+ m.obs_normalizer.until = 1 # count 9.8e8 >= 1: update() returns at once
110
+ storage = RolloutStorage("rl", self.env.num_envs, self.num_steps, obs, [self.env.num_actions], self.device)
111
+ self.alg = FineTunePPO(
112
+ self.actor, self.critic, storage, actor_lr=pc.get("actor_lr", 1e-4), critic_lr=pc.get("critic_lr", 1e-3),
113
+ std_lr=pc.get("std_lr"), std_min=pc.get("std_min", 0.05), std_max=pc.get("std_max", 0.15),
114
+ time_out_bootstrap=pc.get("time_out_bootstrap", "final"),
115
+ num_learning_epochs=int(pc.get("num_learning_epochs", 5)), num_mini_batches=int(pc.get("num_mini_batches", 4)),
116
+ clip_param=float(pc.get("clip_param", 0.2)), gamma=float(pc.get("gamma", 0.99)), lam=float(pc.get("lam", 0.95)),
117
+ value_loss_coef=float(pc.get("value_loss_coef", 1.0)), entropy_coef=float(pc.get("entropy_coef", 0.0)),
118
+ max_grad_norm=float(pc.get("max_grad_norm", 1.0)),
119
+ use_clipped_value_loss=bool(pc.get("use_clipped_value_loss", False)), desired_kl=None,
120
+ normalize_advantage_per_mini_batch=bool(pc.get("normalize_advantage_per_mini_batch", False)),
121
+ device=str(self.device))
122
+ self.guard = Guard(**{k: v for k, v in cfg.get("guard", {}).items() if not k.startswith("_")})
123
+ self.it = 0 # next iteration to run
124
+ self.healthy = None
125
+ self._stop = False
126
+ self.resumed = self._resume()
127
+
128
+ # ------------------------------------------------------------------------------------------------ io
129
+ def _infos(self):
130
+ return dict(guard=self.guard.state(), healthy=self.healthy, checkpoint_std=self.checkpoint_std,
131
+ init_checkpoint=self.cfg["init_checkpoint"], ood=self.env.ood_summary(),
132
+ rewards=self.env.rewards.describe(), grounds=self.env.ground_names)
133
+
134
+ def save(self, name, it):
135
+ d = self.alg.save()
136
+ d["iter"] = int(it)
137
+ d["infos"] = self._infos()
138
+ tmp = self.out / (name + ".tmp")
139
+ torch.save(d, tmp)
140
+ os.replace(tmp, self.out / name)
141
+
142
+ def _resume(self):
143
+ p = self.out / "last.pt"
144
+ if not p.is_file():
145
+ return False
146
+ d = torch.load(p, map_location=self.device, weights_only=False)
147
+ self.alg.load(d, dict(actor=True, critic=True, optimizer=True), strict=True)
148
+ for m in (self.actor, self.critic):
149
+ if self.cfg["runner"].get("freeze_normalizers", True):
150
+ m.obs_normalizer.until = 1
151
+ self.it = int(d["iter"]) + 1
152
+ inf = d.get("infos") or {}
153
+ self.guard.load(inf.get("guard", {}))
154
+ self.healthy = inf.get("healthy")
155
+ print(f"[resume] {p} iteration {d['iter']} -> continue at {self.it}", flush=True)
156
+ return True
157
+
158
+ def _signal(self, signum, frame):
159
+ print(f"[signal] {signal.Signals(signum).name}: stop after this iteration", flush=True)
160
+ self._stop = True
161
+
162
+ # ------------------------------------------------------------------------------------------------ run
163
+ def learn(self, max_iterations=None):
164
+ rc = self.cfg["runner"]
165
+ max_it = int(max_iterations if max_iterations is not None else rc.get("max_iterations", 1000))
166
+ warm = int(rc.get("warmup_iterations", 50))
167
+ save_every, ck_every = int(rc.get("save_interval", 50)), int(rc.get("checkpoint_interval", 10))
168
+ log_every = int(rc.get("log_interval", 1))
169
+ for s in (signal.SIGTERM, signal.SIGUSR1, signal.SIGINT):
170
+ signal.signal(s, self._signal)
171
+ if not self.resumed:
172
+ self.alg.clamp_std()
173
+ self.save("model_0.pt", -1)
174
+ (self.out / "start.json").write_text(json.dumps(dict(
175
+ checkpoint_std=self.checkpoint_std, std_after_cap=self.actor.distribution.std_param.tolist(),
176
+ checkpoint_iter=self.checkpoint_iter, env_build_s=self.build_s, ood=self.env.ood_summary(),
177
+ rewards=self.env.rewards.describe(), grounds=self.env.ground_names,
178
+ blocks=[dict(ground=g, envs=s.stop - s.start, pool=int(len(p))) for g, b, p, s in self.env.blocks],
179
+ members=self.env.sim.paths, ground_arg=self.env.ground_arg), indent=1))
180
+ metrics = open(self.out / "metrics.jsonl", "a")
181
+ obs = self.env.get_observations().to(self.device)
182
+ self.alg.train_mode()
183
+ reason = "max_iterations"
184
+ while self.it < max_it:
185
+ it = self.it
186
+ frozen = it < warm
187
+ self.alg.set_actor_frozen(frozen)
188
+ if self.device.type == "cuda":
189
+ torch.cuda.synchronize()
190
+ t0 = time.time()
191
+ bad = torch.zeros((), dtype=torch.bool, device=self.device)
192
+ with torch.inference_mode():
193
+ anchored = self.env.anchor is not None
194
+ for _ in range(self.num_steps):
195
+ actions = self.alg.act(obs)
196
+ if anchored: # the policy mean of this step (centered anchor)
197
+ self.env.action_mean = self.alg.transition.distribution_params[0]
198
+ obs, rew, dones, extras = self.env.step(actions)
199
+ bad = bad | ~torch.isfinite(rew).all() | ~torch.isfinite(obs["actor"]).all() | \
200
+ ~torch.isfinite(obs["critic"]).all()
201
+ self.alg.process_env_step(obs, rew, dones, extras)
202
+ self.alg.compute_returns(obs)
203
+ if bool(bad):
204
+ raise FloatingPointError(f"iteration {it}: non-finite reward or observation from the env")
205
+ t1 = time.time()
206
+ loss = self.alg.update()
207
+ if self.device.type == "cuda":
208
+ torch.cuda.synchronize()
209
+ t2 = time.time()
210
+ log = self.env.pop_log()
211
+ allg = log["all"]
212
+ tripped = False
213
+ if not frozen:
214
+ tripped = self.guard.update(allg["ood_cost"], allg["reward_per_step"])
215
+ samples = self.env.num_envs * self.num_steps
216
+ row = dict(iteration=it, warmup=frozen, time=time.time(), collect_s=t1 - t0, learn_s=t2 - t1,
217
+ env_steps_per_s=samples / max(t2 - t0, 1e-9), collect_steps_per_s=samples / max(t1 - t0, 1e-9),
218
+ loss=loss, lr={g["name"]: g["lr"] for g in self.alg.optimizer.param_groups},
219
+ std=self.actor.distribution.std_param.tolist(), guard=self.guard.last, grounds=log,
220
+ gpu_peak_alloc_gb=(torch.cuda.max_memory_allocated(self.device) / 1e9
221
+ if self.device.type == "cuda" else None))
222
+ metrics.write(json.dumps(row) + "\n")
223
+ metrics.flush()
224
+ if it % log_every == 0 or it == max_it - 1:
225
+ te = allg["track_err"]
226
+ print(f"it {it:5d}{' W' if frozen else ' '} rew/step {allg['reward_per_step']:+.4f} "
227
+ f"vloss {loss['value']:.4g} ev {loss['explained_variance']:+.3f} kl {loss['kl']:.2e} "
228
+ f"trk {te[0]:.3f}/{te[1]:.3f}/{te[2]:.3f} P {allg['power_w']:.1f}W "
229
+ f"sat {allg['tau_sat_frac']:.1e} ood {allg['ood_cost']:.2e} ({allg['ood_active_frac']:.3f}) "
230
+ f"falls {allg['falls']:.0f} |roll| {allg['roll_abs']:.3f} lat {allg['roll_abs_lat']:.3f} "
231
+ f"std {sum(row['std']) / 12:.3f} "
232
+ f"{row['env_steps_per_s']:.0f} st/s", flush=True)
233
+ if tripped:
234
+ reason = "guard"
235
+ self.save("last.pt", it)
236
+ (self.out / "guard.json").write_text(json.dumps(dict(iteration=it, guard=self.guard.last,
237
+ healthy=self.healthy), indent=1))
238
+ print(f"[guard] tripped at iteration {it}: {self.guard.last}; last healthy {self.healthy}", flush=True)
239
+ self.it = it + 1
240
+ break
241
+ if save_every and it % save_every == 0 and it > 0:
242
+ self.save(f"model_{it}.pt", it)
243
+ if self.guard.last.get("healthy", True):
244
+ self.save("healthy.pt", it)
245
+ self.healthy = it
246
+ if (ck_every and it % ck_every == 0) or self._stop:
247
+ self.save("last.pt", it)
248
+ self.it = it + 1
249
+ if self._stop:
250
+ metrics.close()
251
+ print(f"[stop] saved last.pt at iteration {it}", flush=True)
252
+ return "signal"
253
+ metrics.close()
254
+ self.save("last.pt", self.it - 1)
255
+ self.save(f"model_{self.it - 1}.pt", self.it - 1)
256
+ (self.out / "complete.json").write_text(json.dumps(dict(
257
+ reason=reason, iterations=self.it, last=f"model_{self.it - 1}.pt", healthy=self.healthy,
258
+ guard=self.guard.last), indent=1))
259
+ self.export_onnx()
260
+ return reason
261
+
262
+ def export_onnx(self):
263
+ try:
264
+ export_actor_onnx(self.actor.state_dict(), self.out / "policy.onnx")
265
+ print(f"[export] {self.out / 'policy.onnx'}", flush=True)
266
+ except Exception as ex: # optional (needs onnx)
267
+ print(f"[export] ONNX export skipped: {type(ex).__name__}: {ex}", flush=True)
268
+
269
+
270
+ def export_actor_onnx(actor_state_dict, path, opset=17):
271
+ """Actor mean with the normaliser inside, one self-contained ONNX file [batch, 47] 'obs' -> [batch, 12]
272
+ 'actions' (the deploy contract of mjlab's policy.onnx; metadata not copied). TorchScript exporter (dynamo=False),
273
+ so the weights stay inside the file."""
274
+ from go2nrd.policy.mjlab_policy import MjlabActor
275
+ a = MjlabActor()
276
+ a.load_state_dict({k: v.detach().cpu() for k, v in actor_state_dict.items()}, strict=True)
277
+ a.eval()
278
+ torch.onnx.export(a, torch.zeros(1, 47), str(path), input_names=["obs"], output_names=["actions"],
279
+ opset_version=opset, dynamic_axes={"obs": {0: "batch"}, "actions": {0: "batch"}}, dynamo=False)
280
+ return path
281
+
282
+
283
+ def write_config(cfg, out):
284
+ p = Path(out) / "config.json"
285
+ p.write_text(json.dumps(strip_comments(cfg), indent=1))
286
+ return p
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/helpers_src/go2nrd/eval/parity.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parity of an exported deploy folder: ONNX vs the torch actor, vs the reference ONNX, and through legged_sim_eval's
2
+ DeployPolicy (the deploy's observation assembly + onnxruntime) on observations recorded in mjlab.
3
+
4
+ New code (judges worker, 2026-10-30). Env ``go2eval`` (torch, onnxruntime, legged_sim_eval)::
5
+
6
+ PYTHONPATH=/home/harry/go2_sand/nrd/src:/home/harry/go2_sand/legged_rl_deploy/sim_eval \\
7
+ python -B -m go2nrd.eval.parity --folder /home/harry/go2_sand/nrd_data/eval/policies/<name> [--rows 4000]
8
+
9
+ Recorded rows: the policy steps (even records with a finite observation and a command inside the deploy config's
10
+ clip box, since the collector commands up to vx 1.25 / vy 1 / wz 1.5) of the mjlab raw shard rigid_test_s0000
11
+ (the collector's states with instantaneous rates, the command, phase counter k and the observation the mjlab policy
12
+ saw, and its raw action). For each row a ``RobotState`` is rebuilt the way the DDS bridge publishes it (IMU quaternion
13
+ w >= 0, gyro = R^T w_world, q / dq in motor order through ``joint_ids_map``, float32), the sticks are set by
14
+ legged_sim_eval's ``DirectCommand`` for the command, ``policy_steps`` = k and ``last_action`` = the observation's
15
+ previous action; ``DeployPolicy.update`` then packs the observation and runs the folder's ONNX (``OrtRunner``, the
16
+ deploy runtime). Reported (max abs): rebuilt deploy observation vs the recorded one (per term), DeployPolicy action vs
17
+ the torch actor of the checkpoint on the recorded observation, vs the folder's ONNX called directly, vs the reference
18
+ ONNX (mjlab's own export of model_10000) and vs the recorded raw action (equal only for model_10000).
19
+ Written to ``<folder>/parity.json``.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ import numpy as np
29
+
30
+ from go2nrd.eval.export_onnx import REFERENCE_ONNX, load_actor, onnx_runner
31
+ from go2nrd.eval.smooth import JMAP, quat_to_rot
32
+
33
+ SHARD = Path("/home/harry/go2_sand/nrd_data/raw/rigid_test/rigid_test_s0000.npz")
34
+ CLIP_LO, CLIP_HI = np.array([-0.5, -0.5, -1.0]), np.array([1.0, 0.5, 1.0]) # config.yaml commands.base_velocity
35
+ TERMS = dict(base_ang_vel=slice(0, 3), projected_gravity=slice(3, 6), command=slice(6, 9), phase=slice(9, 11),
36
+ joint_pos=slice(11, 23), joint_vel=slice(23, 35), last_action=slice(35, 47))
37
+
38
+
39
+ def recorded_rows(shard: Path, n: int, seed: int = 0) -> dict:
40
+ from go2nrd.collect.common.contract import load_raw_shard
41
+
42
+ eps, _ = load_raw_shard(shard)
43
+ cols = dict(state=[], command=[], k=[], obs=[], raw=[], family=[])
44
+ for e in eps:
45
+ ok = np.isfinite(e.obs).all(1) & np.isfinite(e.raw_action).all(1)
46
+ ok &= ((e.command >= CLIP_LO) & (e.command <= CLIP_HI)).all(1) # the deploy config clips commands
47
+ idx = np.flatnonzero(ok)
48
+ cols["state"].append(e.state[idx])
49
+ cols["command"].append(e.command[idx])
50
+ cols["k"].append(e.phase_k[idx])
51
+ cols["obs"].append(e.obs[idx])
52
+ cols["raw"].append(e.raw_action[idx])
53
+ cols["family"] += [e.family] * len(idx)
54
+ out = {k: (np.concatenate(v) if k != "family" else np.array(v)) for k, v in cols.items()}
55
+ pick = np.sort(np.random.default_rng(seed).choice(len(out["obs"]), min(n, len(out["obs"])), replace=False))
56
+ return {k: v[pick] for k, v in out.items()}
57
+
58
+
59
+ def deploy_actions(config: Path, rows: dict) -> tuple[np.ndarray, np.ndarray]:
60
+ """(packed observations [n, 47], raw actions [n, 12]) of legged_sim_eval's DeployPolicy on the rebuilt states."""
61
+ from legged_sim_eval.config import load_deploy_config
62
+ from legged_sim_eval.lowlevel import DirectCommand
63
+ from legged_sim_eval.policy import DeployPolicy
64
+ from legged_sim_eval.robot import RobotState
65
+
66
+ cfg = load_deploy_config(str(config))
67
+ pol = DeployPolicy(cfg)
68
+ src = DirectCommand(pol)
69
+ jm = np.asarray(cfg.policy["joint_ids_map"], np.intp)
70
+ if not np.array_equal(jm, JMAP):
71
+ raise ValueError(f"joint_ids_map {jm} differs from {JMAP}")
72
+ obs_out, act_out = [], []
73
+ for s, c, k, o in zip(rows["state"], rows["command"], rows["k"], rows["obs"]):
74
+ quat = s[3:7] / np.linalg.norm(s[3:7])
75
+ R = quat_to_rot(quat)
76
+ gyro = R.T @ s[22:25]
77
+ q = np.zeros(12)
78
+ dq = np.zeros(12)
79
+ q[JMAP] = s[7:19]
80
+ dq[JMAP] = s[25:37]
81
+ st = RobotState.from_sensors(quat, gyro, q, dq, np.zeros(12), base_rot=R)
82
+ pad = src.update(c)
83
+ pol.policy_steps = int(k)
84
+ pol.last_action = np.asarray(o[35:47], np.float32).copy()
85
+ if not pol.update(st, pad, 0):
86
+ raise RuntimeError("policy did not run at loop_cnt 0")
87
+ obs_out.append(pol.last_input.copy())
88
+ act_out.append(pol.last_raw.copy())
89
+ return np.asarray(obs_out, np.float64), np.asarray(act_out, np.float64)
90
+
91
+
92
+ def main(argv=None) -> int:
93
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
94
+ ap.add_argument("--folder", required=True, help="deploy folder (policy.onnx, config.yaml, policy_export.json)")
95
+ ap.add_argument("--checkpoint", default=None, help="default: policy_export.json checkpoint.file")
96
+ ap.add_argument("--rows", type=int, default=4000)
97
+ ap.add_argument("--shard", default=str(SHARD))
98
+ ap.add_argument("--atol", type=float, default=1e-4)
99
+ args = ap.parse_args(argv)
100
+ import torch
101
+
102
+ folder = Path(args.folder)
103
+ ckpt = args.checkpoint or json.loads((folder / "policy_export.json").read_text())["checkpoint"]["file"]
104
+ actor, ck = load_actor(Path(ckpt))
105
+ rows = recorded_rows(Path(args.shard), args.rows)
106
+ obs = rows["obs"].astype(np.float32)
107
+ with torch.no_grad():
108
+ y_torch = actor(torch.from_numpy(obs)).numpy().astype(np.float64)
109
+ run_new, ev = onnx_runner(folder / "policy.onnx")
110
+ run_ref, _ = onnx_runner(REFERENCE_ONNX)
111
+ y_onnx = run_new(obs).astype(np.float64)
112
+ y_ref = run_ref(obs).astype(np.float64)
113
+ obs_dep, y_dep = deploy_actions(folder / "config.yaml", rows)
114
+ d_obs = np.abs(obs_dep - rows["obs"])
115
+ res = dict(folder=str(folder), checkpoint=ck, shard=str(args.shard), rows=int(len(obs)), evaluator=ev,
116
+ families={f: int((rows["family"] == f).sum()) for f in np.unique(rows["family"])},
117
+ obs_rebuilt_vs_recorded={t: float(d_obs[:, s].max()) for t, s in TERMS.items()},
118
+ max_abs=dict(onnx_vs_torch=float(np.abs(y_onnx - y_torch).max()),
119
+ deploy_vs_torch_on_recorded_obs=float(np.abs(y_dep - y_torch).max()),
120
+ deploy_vs_onnx_on_recorded_obs=float(np.abs(y_dep - y_onnx).max()),
121
+ onnx_vs_reference_onnx=float(np.abs(y_onnx - y_ref).max()),
122
+ deploy_vs_recorded_raw=float(np.abs(y_dep - rows["raw"]).max()),
123
+ torch_vs_recorded_raw=float(np.abs(y_torch - rows["raw"]).max())),
124
+ action_abs_max=float(np.abs(y_dep).max()))
125
+ obs_ok = max(v for k, v in res["obs_rebuilt_vs_recorded"].items()) < 1e-4
126
+ res["ok"] = bool(obs_ok and res["max_abs"]["onnx_vs_torch"] < args.atol
127
+ and res["max_abs"]["deploy_vs_torch_on_recorded_obs"] < args.atol)
128
+ (folder / "parity.json").write_text(json.dumps(res, indent=1) + "\n")
129
+ print(json.dumps(res, indent=1))
130
+ return 0 if res["ok"] else 1
131
+
132
+
133
+ if __name__ == "__main__":
134
+ sys.exit(main())
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/nrd_v3/train/export_loader.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Loader-compatible export of an nrd_v3 endpoint (weights unchanged).
2
+
3
+ The nrd_v3 driver wrote its own lineage as the packet 'runtime'. contact_nrd.model.load_model (Go2NrdSim / PPO)
4
+ also needs, for the fused-heading frame, runtime['state_frame'] (yaw_frame.metadata()) and
5
+ runtime['frame_source_sha256'] (sha256 of yaw_frame.py / yaw_frame_adapter.py). This script copies the endpoint,
6
+ adds exactly those two fields (from the FROZEN reference source, digest 924630...) plus the train_three-style
7
+ 'config' alias of the recipe, and checks:
8
+ 1. model_state_dict / model_config / system / masks / update bitwise equal to the input endpoint;
9
+ 2. the export loads with the working-tree load_model and Go2NrdSim;
10
+ 3. one Go2NrdSim-equivalent model step on VAL histories equals the frozen-source model step bitwise.
11
+ python export_loader.py --src LAST.pt --out EXPORT.pt --frozen-src SRC --manifest M --data-root D
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import copy
17
+ import hashlib
18
+ import json
19
+ import subprocess
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ import torch
24
+
25
+ HERE = Path(__file__).resolve().parent
26
+ W = Path("/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102")
27
+
28
+
29
+ def sha(p):
30
+ return hashlib.sha256(Path(p).read_bytes()).hexdigest()
31
+
32
+
33
+ CHECK = r'''
34
+ import json, sys, torch, numpy as np
35
+ sys.path.insert(0, sys.argv[1]) # working-tree src (the PPO / Go2NrdSim code path)
36
+ from go2nrd.contact_nrd.model import load_model
37
+ from go2nrd.sim.nrd_sim import Go2NrdSim
38
+ m, pk = load_model(sys.argv[2], "cpu")
39
+ sim = Go2NrdSim(sys.argv[2], device="cpu")
40
+ b = torch.load(sys.argv[3], weights_only=False)
41
+ with torch.no_grad():
42
+ out, _ = m.world_step(b["hist"], b["ok"], b["act"], ground=b["ground"])
43
+ torch.save(out, sys.argv[4])
44
+ print(json.dumps({"load_model": True, "go2nrdsim_members": sim.n_members, "state_frame": m.state_frame,
45
+ "n_ground_features": int(m.n_ground_features)}))
46
+ '''
47
+
48
+
49
+ def main():
50
+ p = argparse.ArgumentParser()
51
+ p.add_argument("--src", type=Path, required=True)
52
+ p.add_argument("--out", type=Path, required=True)
53
+ p.add_argument("--frozen-src", type=Path, required=True)
54
+ p.add_argument("--manifest", type=Path, required=True)
55
+ p.add_argument("--data-root", type=Path, required=True)
56
+ a = p.parse_args()
57
+ sys.path.insert(0, str(HERE))
58
+ from nrd_v3_train import load_frozen, digest
59
+ helper, trainer, data, frame, _ = load_frozen(a.frozen_src, json.loads((HERE / "reference/pins.json").read_text())["source_sha256"])
60
+ pk = torch.load(a.src, map_location="cpu", weights_only=False)
61
+ ex = copy.deepcopy(pk)
62
+ rt = dict(ex["runtime"])
63
+ rt["state_frame"] = frame.metadata()
64
+ rt["frame_source_sha256"] = {n: sha(a.frozen_src / "go2nrd/fixed_base" / n) for n in ("yaw_frame.py", "yaw_frame_adapter.py")}
65
+ rt["config"] = rt["recipe"]
66
+ rt["export"] = dict(schema="lateral_stuck_20261108_nrd_v3_loader_export_v1", source_endpoint=str(a.src),
67
+ source_endpoint_sha256=sha(a.src), added=["state_frame", "frame_source_sha256", "config", "export"],
68
+ weights_changed=False)
69
+ ex["runtime"] = rt
70
+ a.out.parent.mkdir(parents=True, exist_ok=True)
71
+ torch.save(ex, a.out)
72
+ same = {k: digest(pk[k]) == digest(ex[k]) for k in ("model_state_dict", "model_config", "system", "masks", "update")}
73
+ # fixed VAL histories (lat_v2 VAL, frozen sampler, seed 8671)
74
+ cfg = json.loads((HERE / "reference/full_config.json").read_text())
75
+ smp = helper.WindowSampler(data.load_arm(a.manifest, "lat_v2", "matched", "val", a.data_root), cfg["history"], "cpu", 0)
76
+ import numpy as np
77
+ smp.rng = np.random.default_rng(8671)
78
+ b = smp.sample(64, 1)
79
+ batch = dict(hist=b["hist"], ok=b["ok"], act=b["actions"][:, 0], ground=b["ground"])
80
+ tmp = a.out.with_suffix(".check_batch.pt")
81
+ torch.save(batch, tmp)
82
+ model = helper.build_model(pk["system"], cfg)
83
+ model.load_state_dict(pk["model_state_dict"])
84
+ model.eval()
85
+ with torch.no_grad():
86
+ ref_out, _ = model.world_step(batch["hist"], batch["ok"], batch["act"], ground=batch["ground"])
87
+ out_pt = a.out.with_suffix(".check_out.pt")
88
+ r = subprocess.run([sys.executable, "-B", "-c", CHECK, str(W / "src"), str(a.out), str(tmp), str(out_pt)],
89
+ capture_output=True, text=True, env={"PATH": "/usr/bin:/bin", "OMP_NUM_THREADS": "1"})
90
+ if r.returncode:
91
+ raise SystemExit(r.stderr[-3000:])
92
+ info = json.loads(r.stdout.strip().splitlines()[-1])
93
+ wt = torch.load(out_pt, weights_only=False)
94
+ info.update(packet_fields_equal=same, step_bitwise_equal_frozen=bool(torch.equal(wt, ref_out)),
95
+ export=str(a.out), export_sha256=sha(a.out), source_sha256=sha(a.src))
96
+ tmp.unlink()
97
+ out_pt.unlink()
98
+ print(json.dumps(info))
99
+
100
+
101
+ if __name__ == "__main__":
102
+ main()
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_nrdv3/build_ood_reference.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train-only kNN OOD reference of the CRM ground for PPO in the retrained NRD nrd_v3 FRESH-b (track P2, ppo_nrdv3).
2
+
3
+ Why: the OOD price / guard of the PPO env compares (state, applied target) features with a reference corpus. For
4
+ the seed61 NRD the env drew that corpus from the PPO start pool (crm_prod: the 141 PPO71 training rows), which is
5
+ inside the seed61 training data. FRESH-b was trained on crm_prod TRAIN + the lateral v2 TRAIN exports (HIP + CUDA
6
+ builds; arm mixed_plus_lat_v2, matched; draw shares in the CRM half: crm_prod 50 %, lateral 50 %). The features are
7
+ physical (no NRD normalisation), so only the corpus changes. Same procedure as before:
8
+
9
+ old (env, seed61 runs): pool = CRM starts of the PPO start pool (split 0, families nominal + difficult, k >= 4,
10
+ >= 100 steps left, phase_k >= 50); draw = first min(|pool|, 16000) of torch.randperm(|pool|, cuda generator
11
+ seed 0); CorpusReference(seed 0, 4000 points, k 8): whitening by the draw, stock threshold = p99 of each
12
+ reference point's k-th neighbour distance; recipe V2s/V3: nominal-family p99 of the leave-one-out kNN mean.
13
+ new (this file, FRESH-b runs): the same 16000-row draw size and the same code, but the rows are
14
+ 8000 = the first 8000 of the SAME crm_prod permutation (a subset of the old draw) and
15
+ 8000 = the first 8000 of torch.randperm over the union of lateral v2 TRAIN starts (HIP + CUDA, the same start
16
+ filter; cuda generator seed 0), i.e. the FRESH-b CRM training mixture 50 / 50; HIP / CUDA by start count
17
+ (FRESH-b shared the lateral draws by window count).
18
+ Rigid: unchanged (FRESH-b rigid TRAIN = rigid_prod_v2 TRAIN, the old reference is already its train-only pool).
19
+ No validation or test row is read (asserted: all rows split 0 and in the FRESH-b train lists).
20
+
21
+ Checks: (1) the replicated old draw gives the env's old CRM reference bit for bit (reference points, mean, scale,
22
+ thresholds); (2) the written file loaded by the env (ood.reference_file) gives the same CorpusReference as built here.
23
+
24
+ PYTHONPATH=<wt>/src python build_ood_reference.py --out assets/ood_ref_crm_freshb_v1.npz
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import hashlib
30
+ import json
31
+ import sys
32
+ from pathlib import Path
33
+
34
+ import numpy as np
35
+ import torch
36
+
37
+ HERE = Path(__file__).resolve().parent
38
+ S = HERE.parent
39
+ WT = S.parents[1]
40
+ EXPORT = Path("/home/harry/go2_sand/nrd_data/export")
41
+ LAT = {"crm_lat_v2_hip": EXPORT / "lateral_stuck_20261108_crm_v2_hip",
42
+ "crm_lat_v2_cuda": EXPORT / "lateral_stuck_20261108_crm_v2_cuda"}
43
+
44
+
45
+ def sha(p):
46
+ h = hashlib.sha256()
47
+ with open(p, "rb") as f:
48
+ for b in iter(lambda: f.read(1 << 20), b""):
49
+ h.update(b)
50
+ return h.hexdigest()
51
+
52
+
53
+ def pool_of(bank, min_pk=50):
54
+ pk = bank.phase_k[bank.start_e, 2 * bank.start_k]
55
+ return torch.nonzero((bank.ground[bank.start_e] == 1) & (pk >= min_pk)).flatten()
56
+
57
+
58
+ def main():
59
+ ap = argparse.ArgumentParser()
60
+ ap.add_argument("--out", type=Path, required=True)
61
+ ap.add_argument("--device", default="cuda")
62
+ a = ap.parse_args()
63
+ dev = torch.device(a.device)
64
+ sys.path.insert(0, str(WT / "src"))
65
+ from go2nrd.fixed_base.ppo_lateral_v3 import build_config
66
+ from go2nrd.rl.env import Go2NrdVecEnv
67
+ from go2nrd.rl.ood import CorpusReference, ood_features
68
+ from go2nrd.sim.bank import StartBank
69
+
70
+ base = json.loads((HERE / "recipes/base_ppo71_config.json").read_text())
71
+ recipe = json.loads((HERE / "recipes/v3.json").read_text())
72
+ paths = json.loads((HERE / "recipes/paths_local_seed61.json").read_text())
73
+ cfg = build_config(base, recipe, paths, 91)
74
+ cfg["env"]["num_envs"] = 64
75
+ sc = cfg["env"]["start"]
76
+ oc = cfg["ood"]
77
+ m = int(oc.get("max_points", 4000))
78
+ # ---- (1) old env reference (seed61 runs) and its replication
79
+ env = Go2NrdVecEnv(cfg, a.device, train=True)
80
+ gi = env.ground_names.index("crm")
81
+ g, b, pool, s_ = env.blocks[gi]
82
+ bank = env.banks[b]
83
+ gen = torch.Generator(device=dev).manual_seed(int(oc.get("seed", 0)))
84
+ perm = torch.randperm(len(pool), device=dev, generator=gen)
85
+ take = min(len(pool), 4 * m)
86
+ st_old = bank.draw(pool[perm[:take]])
87
+ feat_old = ood_features(st_old["hist"][:, -1], st_old["action"])
88
+ ref_old = CorpusReference(feat_old, seed=int(oc.get("seed", 0)), max_points=m, k=int(oc["k"]),
89
+ quantile=float(oc["quantile"]), device=a.device)
90
+ rec_old = env._family_threshold(ref_old, feat_old, st_old["family"], bank, oc["threshold"])
91
+ env_ref = env.ood.refs[gi]
92
+ same = (torch.equal(env_ref.ref, ref_old.ref) and torch.equal(env_ref._mu, ref_old._mu)
93
+ and torch.equal(env_ref._sd, ref_old._sd) and env_ref.thresh == ref_old.thresh)
94
+ if not same:
95
+ raise AssertionError("replicated old CRM draw differs from the env reference")
96
+ old_rigid = env.ood_summary()["rigid"]
97
+ old_crm = env.ood_summary()["crm"]
98
+ # ---- (2) new rows
99
+ half = take // 2
100
+ st_c = bank.draw(pool[perm[:half]])
101
+ sp = json.loads((S / "collect/splits_lateral_v2.json").read_text())
102
+ tr = sp["arms"]["matched"]["mixed_plus_lat_v2"]["train"]
103
+ if not set(np.asarray(bank.rows).tolist()) <= set(tr["crm"]):
104
+ raise AssertionError("crm_prod pool rows not inside the FRESH-b train list")
105
+ lat_banks, lat_pools, src_info = [], [], {}
106
+ K = int(env.sim.k)
107
+ for key, d in LAT.items():
108
+ lb = StartBank(d, splits=tuple(sc.get("splits", (0,))), families=sc.get("families"),
109
+ min_steps_left=int(sc.get("min_steps_left", 1)), min_k=max(int(sc.get("min_k", K - 1)), K - 1),
110
+ device=a.device, history=K, rows=tr[key])
111
+ if not set(np.asarray(lb.rows).tolist()) <= set(tr[key]):
112
+ raise AssertionError(f"{key}: rows outside the FRESH-b train list")
113
+ lp = pool_of(lb, int(sc.get("min_phase_k", {}).get("crm", 0)))
114
+ lat_banks.append(lb); lat_pools.append(lp)
115
+ src_info[key] = dict(dir=str(d), unified_sha256=sha(d / "unified_data.npz"), episodes=int(len(lb.rows)),
116
+ starts=int(len(lp)))
117
+ nl = [len(p) for p in lat_pools]
118
+ gen2 = torch.Generator(device=dev).manual_seed(int(oc.get("seed", 0)))
119
+ lperm = torch.randperm(sum(nl), device=dev, generator=gen2)[:take - half]
120
+ feats, fams = [ood_features(st_c["hist"][:, -1], st_c["action"])], [st_c["family"]]
121
+ off = 0
122
+ for lb, lp, n in zip(lat_banks, lat_pools, nl):
123
+ sel = lperm[(lperm >= off) & (lperm < off + n)] - off
124
+ if len(sel):
125
+ st = lb.draw(lp[sel])
126
+ feats.append(ood_features(st["hist"][:, -1], st["action"])); fams.append(st["family"])
127
+ src_info[list(LAT)[lat_banks.index(lb)]]["drawn"] = int(len(sel))
128
+ off += n
129
+ # keep the draw order (crm_prod rows first, then lateral rows in permutation order per source)
130
+ feat = torch.cat(feats)
131
+ family = torch.cat(fams)
132
+ names = [f["name"] for f in bank.system["families"]]
133
+ for lb in lat_banks:
134
+ if [f["name"] for f in lb.system["families"]] != names:
135
+ raise AssertionError("family names differ between crm_prod and lateral v2")
136
+ ref_new = CorpusReference(feat, seed=int(oc.get("seed", 0)), max_points=m, k=int(oc["k"]),
137
+ quantile=float(oc["quantile"]), device=a.device)
138
+ stock_new = ref_new.thresh
139
+ rec_new = env._family_threshold(ref_new, feat, family, bank, oc["threshold"])
140
+ prov = dict(schema="ppo_nrdv3_ood_reference_v1", ground="crm", nrd="nrd_v3 FRESH-b loader 501c9b8d",
141
+ splits_manifest_sha256=sha(S / "collect/splits_lateral_v2.json"), arm="mixed_plus_lat_v2 matched train",
142
+ rows_total=int(len(feat)), crm_prod=dict(pool_starts=int(len(pool)), drawn=int(half),
143
+ rule="first half of the old env permutation (seed 0)",
144
+ unified_sha256=sha(Path(cfg["data"][0]["dir"]) / "unified_data.npz")),
145
+ lateral_v2=src_info, start_filter=dict(splits=sc.get("splits"), families=sc.get("families"),
146
+ min_steps_left=sc.get("min_steps_left"), min_k=4, min_phase_k_crm=50),
147
+ family_counts={nm: int((family == i).sum()) for i, nm in enumerate(names)},
148
+ old=dict(stock=rec_old["stock"], nominal_p99=rec_old["thresh"], rows=old_crm["rows"],
149
+ env_crm_family_threshold=old_crm.get("family_threshold"),
150
+ rigid_stock=old_rigid["family_threshold"]["stock"], rigid_nominal_p99=old_rigid["family_threshold"]["thresh"]),
151
+ new=dict(stock=stock_new, nominal_p99=rec_new["thresh"], nominal_rows=rec_new["rows"],
152
+ loo_knn_mean=rec_new["loo_knn_mean"]))
153
+ a.out.parent.mkdir(parents=True, exist_ok=True)
154
+ np.savez(a.out, feat=feat.double().cpu().numpy(), family=family.long().cpu().numpy(),
155
+ family_names=np.asarray(names), provenance=np.asarray(json.dumps(prov)))
156
+ # ---- (3) the env path reads the file to the same reference
157
+ f2, fam2 = env._reference_rows(a.out, bank, "crm")
158
+ r2 = CorpusReference(f2, seed=int(oc.get("seed", 0)), max_points=m, k=int(oc["k"]), quantile=float(oc["quantile"]),
159
+ device=a.device)
160
+ if not (torch.equal(r2.ref, ref_new.ref) and r2.thresh == stock_new):
161
+ raise AssertionError("file round trip changed the reference")
162
+ prov["file_sha256"] = sha(a.out)
163
+ prov["checks"] = dict(old_replication_bitwise=True, file_roundtrip_bitwise=True)
164
+ a.out.with_suffix(".json").write_text(json.dumps(prov, indent=1) + "\n")
165
+ print(json.dumps(prov, indent=1))
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_nrdv3/export_nrdv3.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Track P2 (ppo_nrdv3) copy of ppo_v3fix/export_v3fix.py (paths changed: exports under runs/.../ppo_nrdv3/; the NRD check is
2
+ the 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.
3
+
4
+ Per candidate (RUN = a finished local copy of a run; endpoint model_299.pt):
5
+ 1. checks: complete.json reason max_iterations, frozen_audit unchanged NRD + unchanged actor normaliser, NRD sha.
6
+ 2. python -m go2nrd.eval.export_onnx --checkpoint RUN/model_299.pt --out EXPORTS/<name>_i299
7
+ --reference legged_rl_deploy/.../velocity/policy.onnx --template .../velocity/config.yaml
8
+ (unchanged exporter, sha256 5e418e4c...: opset 18, static [1, 47], metadata copied, run_path = the run name;
9
+ its verification includes 2048 recorded mjlab observations).
10
+ 3. python -m go2nrd.eval.parity --folder EXPORTS/<name>_i299 --rows 4000 (legged_sim_eval DeployPolicy path on
11
+ recorded mjlab rows: deploy observation assembly + onnxruntime vs the torch actor of the .pt).
12
+ 4. extra parity on 4000 recorded Chrono CRM observations (VAL split states of crm_prod with their recorded
13
+ command / phase / previous action through go2nrd.policy.obs.ObsBuilder): onnxruntime vs the .pt actor.
14
+ 5. portable copy EXPORTS_EULER/<name>_i299 (identical policy.onnx; config.yaml model_path = the Euler path).
15
+ Writes EXPORTS/<name>_i299/v3_export_record.json and prints a summary.
16
+
17
+ python export_v3.py NAME=RUN_DIR [NAME=RUN_DIR ...]
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import os
24
+ import subprocess
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ import numpy as np
29
+
30
+ WT = Path("/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102")
31
+ EXPORTS = WT / "runs/lateral_stuck_20261108/ppo_nrdv3/exports"
32
+ EXPORTS_EULER = WT / "runs/lateral_stuck_20261108/ppo_nrdv3/exports_portable_euler"
33
+ EXPORTS_AMD = WT / "runs/lateral_stuck_20261108/ppo_nrdv3/exports_portable_amd"
34
+ AMD_EXPORTS = "/work1/dannegrut/harry/lateral_stuck_20261108/ppo_nrdv3/exports"
35
+ EULER_EXPORTS = "/srv/home/hzhang699/go2nrd/studies/lateral_stuck_20261108/ppo_nrdv3/exports"
36
+ ORIGINAL = Path("/home/harry/go2_sand/legged_rl_deploy/policies/go2/unitree_rl_mjlab/velocity")
37
+ NRD_SHA = "501c9b8da022caf9594ad9cd7c50a7eda1e00424e5d4c9c7c8add65ee788848c" # nrd_v3 FRESH-b loader
38
+ OVERLAY_SHA = "17d563ae2b18a0a14a6c843d399ef91da22efb16e7f2ab3e5e1d6294318e5a9f" # recipes/overlay_nrdv3_ood.json
39
+ EXPORTER_SHA = "5e418e4c0efa9dd36f1514cde9429e04050a1edb5686a9443f99d98f7d85ee83"
40
+
41
+
42
+ def sha(p):
43
+ return hashlib.sha256(Path(p).read_bytes()).hexdigest()
44
+
45
+
46
+ def crm_obs(n=4000, seed=0):
47
+ import torch
48
+ from go2nrd.policy.obs import ObsBuilder
49
+ from go2nrd.sim.bank import StartBank
50
+ bank = StartBank("/home/harry/go2_sand/nrd_data/export/crm_prod", splits=(1,), families=("nominal", "difficult"),
51
+ min_k=4, device="cpu", history=4)
52
+ g = torch.Generator().manual_seed(seed)
53
+ st = bank.draw(torch.randint(bank.n, (n,), generator=g))
54
+ ob = ObsBuilder(device="cpu", force_fill="zero")
55
+ # the recorded instantaneous state is what the policy saw in Chrono
56
+ return ob.actor(st["state_inst"], st["command"].float(), st["phase_k"], st["last_action"]).numpy().astype(np.float32)
57
+
58
+
59
+ def main():
60
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="", OMP_NUM_THREADS="1", OPENBLAS_NUM_THREADS="1",
61
+ PYTHONDONTWRITEBYTECODE="1",
62
+ PYTHONPATH=f"{WT / 'src'}:/home/harry/go2_sand/unitree_rl_mjlab:/home/harry/go2_sand/legged_rl_deploy/sim_eval")
63
+ assert sha(WT / "src/go2nrd/eval/export_onnx.py") == EXPORTER_SHA
64
+ assert sha(ORIGINAL / "policy.onnx") == "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45"
65
+ sys.path.insert(0, str(WT / "src"))
66
+ from go2nrd.eval.export_onnx import load_actor, onnx_runner
67
+ import torch
68
+ obs_crm = crm_obs()
69
+ out = {}
70
+ for spec in sys.argv[1:]:
71
+ name, run = spec.split("=", 1)
72
+ run = Path(run)
73
+ comp = json.loads((run / "complete.json").read_text())
74
+ audit = json.loads((run / "frozen_audit.json").read_text())
75
+ cfg = json.loads((run / "config.json").read_text())
76
+ assert comp["reason"] == "max_iterations" and comp["last"] == "model_299.pt", comp
77
+ assert audit["unchanged"] and audit["teacher_actor_normalization_unchanged"], audit
78
+ assert cfg["lateral_v3_lineage"]["nrd_sha256"] == NRD_SHA
79
+ assert cfg["lateral_v3_lineage"].get("overlay_sha256") == OVERLAY_SHA
80
+ ck = run / "model_299.pt"
81
+ folder = EXPORTS / f"{name}_i299"
82
+ if not (folder / "policy_export.json").exists():
83
+ folder.parent.mkdir(parents=True, exist_ok=True)
84
+ with open(EXPORTS / f"{name}_i299_export.log", "w") as log:
85
+ subprocess.run([sys.executable, "-B", "-m", "go2nrd.eval.export_onnx", "--checkpoint", str(ck), "--out",
86
+ str(folder), "--run-name", name, "--reference", str(ORIGINAL / "policy.onnx"),
87
+ "--template", str(ORIGINAL / "config.yaml")], cwd=WT, env=env, stdout=log,
88
+ stderr=subprocess.STDOUT, check=True, timeout=300)
89
+ if not (folder / "parity.json").exists():
90
+ with open(EXPORTS / f"{name}_i299_parity.log", "w") as log:
91
+ subprocess.run([sys.executable, "-B", "-m", "go2nrd.eval.parity", "--folder", str(folder), "--rows", "4000"],
92
+ cwd=WT, env=env, stdout=log, stderr=subprocess.STDOUT, check=True, timeout=600)
93
+ desc = json.loads((folder / "policy_export.json").read_text())
94
+ par = json.loads((folder / "parity.json").read_text())
95
+ actor, ckd = load_actor(ck)
96
+ fn, evaluator = onnx_runner(folder / "policy.onnx")
97
+ with torch.no_grad():
98
+ y_t = actor(torch.from_numpy(obs_crm)).numpy()
99
+ y_o = fn(obs_crm)
100
+ crm_diff = float(np.abs(y_o - y_t).max())
101
+ # portable Euler copy
102
+ pf = EXPORTS_EULER / f"{name}_i299"
103
+ pf.mkdir(parents=True, exist_ok=True)
104
+ (pf / "policy.onnx").write_bytes((folder / "policy.onnx").read_bytes())
105
+ txt = (folder / "config.yaml").read_text().splitlines()
106
+ txt = [(ln.split("model_path:")[0] + f"model_path: {EULER_EXPORTS}/{name}_i299/policy.onnx")
107
+ if ln.strip().startswith("model_path:") else ln for ln in txt]
108
+ (pf / "config.yaml").write_text("\n".join(txt) + "\n")
109
+ for f in ("policy_export.json", "parity.json"):
110
+ (pf / f).write_bytes((folder / f).read_bytes())
111
+ pa = EXPORTS_AMD / f"{name}_i299" # portable AMD copy (track P)
112
+ pa.mkdir(parents=True, exist_ok=True)
113
+ (pa / "policy.onnx").write_bytes((folder / "policy.onnx").read_bytes())
114
+ txa = [(ln.split("model_path:")[0] + f"model_path: {AMD_EXPORTS}/{name}_i299/policy.onnx")
115
+ if ln.strip().startswith("model_path:") else ln for ln in (folder / "config.yaml").read_text().splitlines()]
116
+ (pa / "config.yaml").write_text("\n".join(txa) + "\n")
117
+ for f in ("policy_export.json", "parity.json"):
118
+ (pa / f).write_bytes((folder / f).read_bytes())
119
+ rec = dict(name=name, run=str(run), checkpoint=str(ck), checkpoint_sha256=sha(ck), iteration=ckd["iteration"],
120
+ onnx=str(folder / "policy.onnx"), onnx_sha256=sha(folder / "policy.onnx"),
121
+ onnx_portable_euler=f"{EULER_EXPORTS}/{name}_i299/policy.onnx",
122
+ config_yaml=str(folder / "config.yaml"), config_yaml_portable_euler=f"{EULER_EXPORTS}/{name}_i299/config.yaml",
123
+ onnx_portable_amd=f"{AMD_EXPORTS}/{name}_i299/policy.onnx",
124
+ config_yaml_portable_amd=f"{AMD_EXPORTS}/{name}_i299/config.yaml",
125
+ structure_ok=desc["structure"]["ok"], exporter_verification=desc["verification"],
126
+ parity_deploy=par, parity_crm_recorded=dict(n=int(len(obs_crm)), evaluator=evaluator,
127
+ max_abs_onnx_vs_pt=crm_diff,
128
+ max_abs_action=float(np.abs(y_o).max())),
129
+ exporter_sha256=EXPORTER_SHA, nrd_sha256=NRD_SHA, recipe=cfg["lateral_v3_lineage"]["recipe"],
130
+ seed=cfg["seed"], overlay_sha256=cfg["lateral_v3_lineage"]["overlay_sha256"],
131
+ ood_reference_file=cfg["ood"].get("reference_file"))
132
+ (folder / "v3_export_record.json").write_text(json.dumps(rec, indent=1) + "\n")
133
+ (pf / "v3_export_record.json").write_text(json.dumps(rec, indent=1) + "\n")
134
+ (pa / "v3_export_record.json").write_text(json.dumps(rec, indent=1) + "\n")
135
+ out[name] = rec
136
+ print(name, rec["onnx_sha256"][:16], "structure", rec["structure_ok"], "exporter max", desc["verification"]["max_onnx_vs_torch"],
137
+ "crm max", crm_diff, flush=True)
138
+ 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))
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
go2_sand_finetune/code/browse/study_scripts_lateral_stuck_20261108/studies/lateral_stuck_20261108/ppo_v3/build_start_groups.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Start-group intervals for env.start.groups (go2nrd.rl.lateral_v3): the CRM STUCK lateral intervals of phase 1.
2
+
3
+ Source: diag/crm_coverage/lateral_windows.json "stuck" (domain crm), the same list the phase-1 critic used (S6:
4
+ 1,579 of 29,445 PPO71 CRM starts inside STUCK, 512 inside drag-like). Groups (first match wins in the env):
5
+ stuck_drag : drag-like STUCK interval (critic rule: swing clearance median < 3 cm or stance max sinkage median > 2 cm)
6
+ stuck : other STUCK interval
7
+ Interval = export row piece_index, records [start_record, end_record) (cut at the row end when the window crosses
8
+ a chunk edge, as critic S6). Also counts the PPO71 CRM pool starts per group (critic S6 enumeration).
9
+
10
+ python3 build_start_groups.py -> start_groups_crm_stuck_v1.npz, start_groups_crm_stuck_v1.json
11
+ """
12
+ import json
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ WT = Path("/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102")
18
+ HERE = WT / "studies/lateral_stuck_20261108/ppo_v3"
19
+ LW = WT / "studies/lateral_stuck_20261108/diag/crm_coverage/lateral_windows.json"
20
+ PPO71 = WT / "runs/fixed_base_20261102/ppo/horizon_h50_u13500_s61_p71_diagnostic_v1"
21
+ EXPORT = Path("/home/harry/go2_sand/nrd_data/export/crm_prod")
22
+
23
+
24
+ def drag_like(w):
25
+ return (w.get("swing_clearance_median_m") is not None and w["swing_clearance_median_m"] < 0.03) or \
26
+ (w.get("stance_max_sinkage_median_m") is not None and w["stance_max_sinkage_median_m"] > 0.02)
27
+
28
+
29
+ def main():
30
+ import sys
31
+ sys.path.insert(0, str(WT / "src"))
32
+ from go2nrd.sim.bank import npz_members
33
+ arr = npz_members(EXPORT / "unified_data.npz")
34
+ L = np.asarray(arr["lengths"])
35
+ st = [w for w in json.loads(LW.read_text())["stuck"] if w["domain"] == "crm"]
36
+ names = ["stuck_drag", "stuck"]
37
+ rows, lo, hi, grp, meta = [], [], [], [], []
38
+ for w in st:
39
+ e = int(w["piece_index"])
40
+ end = int(w["end_record"]) if int(w.get("piece_index_end", e)) == e else int(L[e])
41
+ g = 0 if drag_like(w) else 1
42
+ rows.append(e); lo.append(int(w["start_record"])); hi.append(end); grp.append(g)
43
+ meta.append(dict(row=e, lo=int(w["start_record"]), hi=end, group=names[g], parent=w["parent"],
44
+ split=w["split"], family=w["family"], vy_cmd=w["vy_cmd"], vx_cmd=w["vx_cmd"],
45
+ soil_cohesion_pa=w["soil_cohesion_pa"], soil_friction=w["soil_friction"],
46
+ min_window_ratio=w["min_window_ratio"]))
47
+ out = HERE / "start_groups_crm_stuck_v1.npz"
48
+ np.savez(out, names=np.array(names), row=np.array(rows, np.int64), lo=np.array(lo, np.int64),
49
+ hi=np.array(hi, np.int64), group=np.array(grp, np.int64))
50
+ # PPO71 CRM pool enumeration (critic S6 rule) and group counts
51
+ cfg = json.loads((PPO71 / "config.json").read_text())
52
+ sc = cfg["env"]["start"]
53
+ entry = [d for d in cfg["data"] if Path(d["dir"]).name == "crm_prod"][0]
54
+ prow = np.asarray(entry["rows"], int)
55
+ spl, fam = np.asarray(arr["splits"]), np.asarray(arr["family"])
56
+ sel = prow[np.isin(spl[prow], sc["splits"]) & np.isin(fam[prow], [0, 1])]
57
+ min_k, msl, min_pk = max(int(sc["min_k"]), 3), int(sc["min_steps_left"]), int(sc["min_phase_k"]["crm"])
58
+ counts = {n: 0 for n in names}
59
+ total = 0
60
+ par = np.asarray(arr["parent_episode_id"])
61
+ parents = {n: set() for n in names}
62
+ lat_vy = {n: [] for n in names}
63
+ for e in sel:
64
+ n = int(L[e]); kmax = (n - 1 - 2 * msl) // 2
65
+ if kmax < min_k:
66
+ continue
67
+ k = np.arange(min_k, kmax + 1)
68
+ k = k[np.asarray(arr["phase_k"][e, :n])[2 * k] >= min_pk]
69
+ total += len(k)
70
+ r0 = 2 * k
71
+ got = np.full(len(k), -1)
72
+ for rr, a, b, g in zip(rows, lo, hi, grp):
73
+ if rr == e:
74
+ got = np.where((got < 0) & (r0 >= a) & (r0 < b), g, got)
75
+ for g, nm in enumerate(names):
76
+ c = int((got == g).sum()); counts[nm] += c
77
+ if c:
78
+ parents[nm].add(int(par[e]))
79
+ lat_vy[nm] += np.asarray(arr["command"][e, :n])[r0[got == g], 1].tolist()
80
+ rec = dict(file=str(out), source=str(LW), intervals=len(rows), names=names,
81
+ intervals_per_group={nm: int(sum(g == i for g in grp)) for i, nm in enumerate(names)},
82
+ ppo71_crm_pool_starts=total, pool_starts_per_group=counts,
83
+ pool_parents_per_group={k: sorted(v) for k, v in parents.items()},
84
+ pool_vy_abs_median={k: float(np.median(np.abs(v))) if v else None for k, v in lat_vy.items()},
85
+ pool_vy_pos_share={k: float(np.mean(np.asarray(v) > 0)) if v else None for k, v in lat_vy.items()},
86
+ intervals_detail=meta)
87
+ (HERE / "start_groups_crm_stuck_v1.json").write_text(json.dumps(rec, indent=1) + "\n")
88
+ print(json.dumps({k: v for k, v in rec.items() if k != "intervals_detail"}, indent=1))
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
go2_sand_finetune/code/collector_crm_code_lateral_stuck_20261108_v2_698933cdce75.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:528b37f1d97f17c4c2e655b82d371012da6944a82e0e97dafcd04e82c77127ee
3
+ size 48929838
go2_sand_finetune/code/collector_crm_code_v1_d8ef2fc8d989.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c8e6b75bb94e834f4e237b320945c297ec3b2288c5d12b7950d785379151f66
3
+ size 60475430
go2_sand_finetune/code/collector_rigid_mjlab_nrd_3a9155b.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca870a86a87c5c1bd853048de81e4c83182f841b01ec04a87d70efcd7f537af0
3
+ size 7046472
go2_sand_finetune/code/eval_capsule_runtime_eval_v1_30417413.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81a3e27e7b4f8635dd583cd1bfaa71013bba6fe8805cc1a803ebe13b00954e72
3
+ size 6793278
go2_sand_finetune/code/eval_chrono_suite_v1_p2nrd_699bc991a430.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1671c771c4c55a9ad8ae9a1be84eef361134e45533ca93ad7a7e5e4399e012d8
3
+ size 681098
go2_sand_finetune/code/eval_chrono_suite_v2_q1_d407c6940ef1.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:853a24cff65412a1e9a4becc078e615b8d7d24c76f98c26268dffe2c7c662539
3
+ size 673647
go2_sand_finetune/code/go2nrd_worktree_snapshot.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bfb2ee245691196798f28fc695c6fb558e851a835e26094f138e52a2a939028c
3
+ size 12163621
go2_sand_finetune/code/nrd_capsule_c0e07a22e57434cd.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b533c22cb13131f7c6b9e38deccae3c97f8797ae3285ef4d80e64813a8ba02a
3
+ size 1695346
go2_sand_finetune/code/ppo_snapshot_8e08e2544f0d.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e54474044a6bc37ab6b4260629c2b2d695a7368384996eaef2d90103242520ff
3
+ size 595152
go2_sand_finetune/code/source_manifest.json ADDED
The diff for this file is too large to render. See raw diff
 
go2_sand_finetune/code/study_scripts_lateral_stuck_20261108.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ba3b8c4330110b089f7d2639527b1f1a56b74d05367ef953bbe9e7eb6d587d4
3
+ size 13016731
go2_sand_finetune/data/EXPORT_NAMES.json ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "go2_sand_finetune_export_names_v1",
3
+ "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'.",
4
+ "split_manifests": {
5
+ "go2_sand_finetune/data/splits/splits_fixed_base_20261102.json": {
6
+ "original_path": "/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102/studies/fixed_base_20261102/data/splits.json",
7
+ "sha256": "f1d264dde8e4398607d09a3c4013c2dfe624e8fcef873596880b5ce63376b3f0"
8
+ },
9
+ "go2_sand_finetune/data/splits/splits_lateral_v2.json": {
10
+ "original_path": "/home/harry/.t3/worktrees/nrd/study-fixed-base-mjlab-20261102/studies/lateral_stuck_20261108/collect/splits_lateral_v2.json",
11
+ "sha256": "9ba6dce9f4b7e29ad385da61d1209d71f5f7478c7863b4dba23c9519047bee4f",
12
+ "used_by": "NRD FRESH-b (arm mixed_plus_lat_v2, budget matched, seed 62; lineage.json manifest_sha256)"
13
+ }
14
+ },
15
+ "exports": {
16
+ "rigid_prod_v2": {
17
+ "release_folder": "go2_sand_finetune/data/rigid_prod_v2/",
18
+ "original_folder": "/home/harry/go2_sand/nrd_data/export/rigid_prod_v2",
19
+ "campaign": "rigid_prod",
20
+ "plan": "go2_sand_finetune/data/plans/rigid_prod.json",
21
+ "master_seed": 645913208,
22
+ "plan_episodes": 8700,
23
+ "plan_missing_episodes_in_this_export": 0,
24
+ "created_utc": "2026-10-30T06:27:55Z",
25
+ "export_code": "6e5c729e28c3bd6c03bd34e715d9827a80d0cd3e",
26
+ "export_code_dirty": true,
27
+ "pieces": 10443,
28
+ "valid_records": 3271292,
29
+ "hours": 9.057913888888889,
30
+ "split_counts": {
31
+ "0": 9391,
32
+ "1": 1052,
33
+ "2": 0
34
+ },
35
+ "raw_shards": 39,
36
+ "platform": "local workstation, RTX 5090, mjlab / MuJoCo Warp (raw shards 2026-10-29 22:27 CDT)",
37
+ "simulation": {
38
+ "simulator": "mjlab (MuJoCo Warp)",
39
+ "packages": {
40
+ "mjlab": "1.2.0",
41
+ "mujoco": "3.5.0",
42
+ "mujoco-warp": "3.5.0",
43
+ "warp-lang": "1.12.1",
44
+ "torch": "2.14.1"
45
+ },
46
+ "task": "Unitree-Go2-Flat"
47
+ },
48
+ "generating_policy": {
49
+ "kind": "mjlab checkpoint (deterministic mean action)",
50
+ "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",
51
+ "checkpoint_sha256": "7ee303f98c48044d792c884edeeedacb58142aece8af56de6f0ba58fb6c9723c",
52
+ "iteration": 10000,
53
+ "source": "manifest.json collectors[0].policy and every shard_meta"
54
+ },
55
+ "used_by": {
56
+ "nrd_fresh_b": "yes, source key 'rigid' (domain weight 0.5)",
57
+ "ppo_v2n_s81": "yes, start states (Euler copy, same sha256)"
58
+ },
59
+ "sha256": {
60
+ "unified_data.npz": "b02c0c50b185a4e3851d1e948b20ea6ba88f9402009655313310ab621806ac78",
61
+ "manifest.json": "68df3247d3e6e9ffd9099671cc877eb6d7b6b6052d2ff724d925902870e94ce5",
62
+ "system.json": "e1a7de656a46b9493e1021e37d459198480c90e712c179039fe4c9cc94761309"
63
+ }
64
+ },
65
+ "crm_prod": {
66
+ "release_folder": "go2_sand_finetune/data/crm_prod/",
67
+ "original_folder": "/home/harry/go2_sand/nrd_data/export/crm_prod",
68
+ "campaign": "crm_prod",
69
+ "plan": "go2_sand_finetune/data/plans/crm_prod.json",
70
+ "master_seed": 481062795,
71
+ "plan_episodes": 2000,
72
+ "plan_missing_episodes_in_this_export": 0,
73
+ "created_utc": "2026-10-30T11:03:53Z",
74
+ "export_code": "1346b2cfcc264fd150442e08fcbe4d096b9e62a4",
75
+ "export_code_dirty": false,
76
+ "pieces": 3489,
77
+ "valid_records": 2141261,
78
+ "hours": 5.938255555555556,
79
+ "split_counts": {
80
+ "0": 3138,
81
+ "1": 351,
82
+ "2": 0
83
+ },
84
+ "raw_shards": 2000,
85
+ "platform": "AMD HPC Fund, MI210 (mi2101x), Chrono CRM HIP build, array job 487049, launched 2026-10-30 01:57 CDT",
86
+ "simulation": {
87
+ "simulator": "Chrono (pychrono)",
88
+ "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e",
89
+ "pychrono_core_md5": "600414ef1296c505"
90
+ },
91
+ "generating_policy": {
92
+ "kind": "legged_rl_deploy ONNX (teacher)",
93
+ "onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45",
94
+ "deploy_config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2",
95
+ "per_shard_policy_sha256": null,
96
+ "shards_with_policy_field": 0,
97
+ "shards": 2000,
98
+ "source": "system.json physics_config.crm.deploy; shard_meta has no policy field"
99
+ },
100
+ "used_by": {
101
+ "nrd_fresh_b": "yes, source key 'crm' (crm_half/crm_prod, weight 0.25)",
102
+ "ppo_v2n_s81": "yes, start states (Euler copy, same sha256)"
103
+ },
104
+ "sha256": {
105
+ "unified_data.npz": "35b73ce2d8bd1c28f7de88c92347dd6f76ee7b3c509635d900565027f24f0271",
106
+ "manifest.json": "d4600689fa41cd42f09f931c868b24670f7401ff5e5d074728697468388eba04",
107
+ "system.json": "9e895fe65b13f0f7056f4c62979f8692379c5ae65449de9986d980ef8c77fa2a"
108
+ }
109
+ },
110
+ "lateral_crm_v2_hip": {
111
+ "release_folder": "go2_sand_finetune/data/lateral_crm_v2_hip/",
112
+ "original_folder": "/home/harry/go2_sand/nrd_data/export/lateral_stuck_20261108_crm_v2_hip",
113
+ "campaign": "lateral_stuck_20261108_crm_v2",
114
+ "plan": "go2_sand_finetune/data/plans/lateral_stuck_20261108_crm_v2.json",
115
+ "master_seed": 2026110803,
116
+ "plan_episodes": 480,
117
+ "plan_missing_episodes_in_this_export": 80,
118
+ "created_utc": "2026-11-09T05:42:02Z",
119
+ "export_code": null,
120
+ "export_code_dirty": false,
121
+ "pieces": 730,
122
+ "valid_records": 663634,
123
+ "hours": 1.8413999999999997,
124
+ "split_counts": {
125
+ "0": 657,
126
+ "1": 73,
127
+ "2": 0
128
+ },
129
+ "raw_shards": 400,
130
+ "platform": "AMD HPC Fund, MI210 (mi2104x), Chrono CRM HIP build (core md5 600414ef), bulk job 509760, export job 509836, 2026-11-08",
131
+ "simulation": {
132
+ "simulator": "Chrono (pychrono)",
133
+ "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e",
134
+ "pychrono_core_md5": "600414ef1296c505"
135
+ },
136
+ "generating_policy": {
137
+ "kind": "legged_rl_deploy ONNX (teacher)",
138
+ "onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45",
139
+ "deploy_config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2",
140
+ "per_shard_policy_sha256": [
141
+ "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45"
142
+ ],
143
+ "shards_with_policy_field": 400,
144
+ "shards": 400,
145
+ "source": "system.json physics_config.crm.deploy and every shard_meta.policy"
146
+ },
147
+ "used_by": {
148
+ "nrd_fresh_b": "yes, source key 'crm_lat_v2_hip' (crm_half/lat_v2, shared weight 0.25 with cuda)",
149
+ "ppo_v2n_s81": "no direct use"
150
+ },
151
+ "sha256": {
152
+ "unified_data.npz": "2e78115a8fef352781a6cb861bd530fd539260836152a07d155b2cabefeddf8b",
153
+ "manifest.json": "c60ddc252f87f32457a9485f74cd2817872359aac223c86b01a6f3f1f974e4db",
154
+ "system.json": "82b4a4e93ce8044d93f2ea491969407df912beebe131f8c18a960041add94e60"
155
+ }
156
+ },
157
+ "lateral_crm_v2_cuda": {
158
+ "release_folder": "go2_sand_finetune/data/lateral_crm_v2_cuda/",
159
+ "original_folder": "/home/harry/go2_sand/nrd_data/export/lateral_stuck_20261108_crm_v2_cuda",
160
+ "campaign": "lateral_stuck_20261108_crm_v2",
161
+ "plan": "go2_sand_finetune/data/plans/lateral_stuck_20261108_crm_v2.json",
162
+ "master_seed": 2026110803,
163
+ "plan_episodes": 480,
164
+ "plan_missing_episodes_in_this_export": 400,
165
+ "created_utc": "2026-11-09T05:41:59Z",
166
+ "export_code": null,
167
+ "export_code_dirty": false,
168
+ "pieces": 149,
169
+ "valid_records": 136413,
170
+ "hours": 0.3785111111111111,
171
+ "split_counts": {
172
+ "0": 135,
173
+ "1": 14,
174
+ "2": 0
175
+ },
176
+ "raw_shards": 80,
177
+ "platform": "Euler euler07, 5 x A4500, Chrono CRM CUDA build (core md5 2387ec6d), bulk job 113924, export job 113929, 2026-11-08",
178
+ "simulation": {
179
+ "simulator": "Chrono (pychrono)",
180
+ "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e",
181
+ "pychrono_core_md5": "2387ec6dda45eaa5"
182
+ },
183
+ "generating_policy": {
184
+ "kind": "legged_rl_deploy ONNX (teacher)",
185
+ "onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45",
186
+ "deploy_config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2",
187
+ "per_shard_policy_sha256": [
188
+ "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45"
189
+ ],
190
+ "shards_with_policy_field": 80,
191
+ "shards": 80,
192
+ "source": "system.json physics_config.crm.deploy and every shard_meta.policy"
193
+ },
194
+ "used_by": {
195
+ "nrd_fresh_b": "yes, source key 'crm_lat_v2_cuda' (crm_half/lat_v2, shared weight 0.25 with hip)",
196
+ "ppo_v2n_s81": "no direct use"
197
+ },
198
+ "sha256": {
199
+ "unified_data.npz": "f1079976f3f407596714bdcf9cc7616bd162280e1e6358cc9d21e03a6b9fa7a2",
200
+ "manifest.json": "f1429b3f3bda6b3eaeb21bdb034c9c9e0f2053a6ee63abe8591c3b51d76ce35b",
201
+ "system.json": "3a3f7b93b76048fe57b0bafff74f61c4639d21874d3fcb725036c600639809dc"
202
+ }
203
+ },
204
+ "lateral_crm_v2_test_hip": {
205
+ "release_folder": "go2_sand_finetune/data/lateral_crm_v2_test_hip/",
206
+ "original_folder": "/home/harry/go2_sand/nrd_data/export/lateral_stuck_20261108_crm_v2_test_hip",
207
+ "campaign": "lateral_stuck_20261108_crm_v2_test",
208
+ "plan": "go2_sand_finetune/data/plans/lateral_stuck_20261108_crm_v2_test.json",
209
+ "master_seed": 2026110804,
210
+ "plan_episodes": 60,
211
+ "plan_missing_episodes_in_this_export": 0,
212
+ "created_utc": "2026-11-09T05:42:20Z",
213
+ "export_code": null,
214
+ "export_code_dirty": false,
215
+ "pieces": 105,
216
+ "valid_records": 95556,
217
+ "hours": 0.26514166666666666,
218
+ "split_counts": {
219
+ "0": 0,
220
+ "1": 0,
221
+ "2": 105
222
+ },
223
+ "raw_shards": 60,
224
+ "platform": "AMD HPC Fund, MI210, Chrono CRM HIP build, bulk job 509760, export job 509836, 2026-11-08",
225
+ "simulation": {
226
+ "simulator": "Chrono (pychrono)",
227
+ "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e",
228
+ "pychrono_core_md5": "600414ef1296c505"
229
+ },
230
+ "generating_policy": {
231
+ "kind": "legged_rl_deploy ONNX (teacher)",
232
+ "onnx_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45",
233
+ "deploy_config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2",
234
+ "per_shard_policy_sha256": [
235
+ "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45"
236
+ ],
237
+ "shards_with_policy_field": 60,
238
+ "shards": 60,
239
+ "source": "system.json physics_config.crm.deploy and every shard_meta.policy"
240
+ },
241
+ "used_by": {
242
+ "nrd_fresh_b": "no (held out: splits_lateral_v2.json key heldout_test; load_arm refuses it)",
243
+ "ppo_v2n_s81": "no"
244
+ },
245
+ "sha256": {
246
+ "unified_data.npz": "e1f18d4814353a5ff0dbf6b86771896b1cdd68c3243e21731676013a868e5701",
247
+ "manifest.json": "b4dcaa08aaee26bb4290ee6e76c538340ef50d0f4a8bc348027e117f520ecd89",
248
+ "system.json": "84406be3a230c24c70a1ae7b0c13c3b3f90bf39df11dfd15646a055cd3514f08"
249
+ }
250
+ },
251
+ "lateral_crm_v2_slim_diag": {
252
+ "release_folder": "go2_sand_finetune/data/lateral_crm_v2_slim_diag/",
253
+ "original_folder": "/home/harry/go2_sand/nrd_data/export/lateral_stuck_20261108_crm_v2_slim_diag",
254
+ "campaign": "lateral_stuck_20261108_crm_v2 and _test",
255
+ "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>",
256
+ "made_by": "collect/scripts/extract_slim_diag.py in post jobs AMD 509836 (hip, test_hip) and Euler 113929 (cuda)",
257
+ "used_by": {
258
+ "nrd_fresh_b": "no (QA / diagnostics only)",
259
+ "ppo_v2n_s81": "no"
260
+ },
261
+ "sha256": {
262
+ "lateral_stuck_20261108_crm_v2_cuda_slim_diag.npz": "dc7158004218e2b6d05648b6b5de662620c15610b49d338f50d2200a4c08e761",
263
+ "lateral_stuck_20261108_crm_v2_hip_slim_diag.npz": "bc37034cfd5adb2520128b3158b51c029036f7b10c969891b2e74bb4c6157285",
264
+ "lateral_stuck_20261108_crm_v2_test_hip_slim_diag.npz": "6f1b7fff964c0e46dc2e94dee4408680c781205a7d1fe7709fc4ac25508c2b8c"
265
+ }
266
+ }
267
+ }
268
+ }
go2_sand_finetune/data/aux/rigid_test_s0000.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4291746111e9e496cfbfb0947ed7b8498105a146cc071b9855f8d5cc0bacd2cb
3
+ size 89542381
go2_sand_finetune/data/crm_prod/crm_gates.json ADDED
The diff for this file is too large to render. See raw diff
 
go2_sand_finetune/data/crm_prod/crm_gates_brief.json ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "planned": 2000,
3
+ "with_marker": 2000,
4
+ "missing": 0,
5
+ "status": {
6
+ "ok": 2000
7
+ },
8
+ "attempts": {
9
+ "ok": 2000
10
+ },
11
+ "fsi_abort_share": 0.0,
12
+ "terminal_reasons": {
13
+ "nominal": {
14
+ "planned_end": 404,
15
+ "off_bed": 70,
16
+ "nonfoot_contact": 4,
17
+ "tilt": 2
18
+ },
19
+ "difficult": {
20
+ "nonfoot_contact": 144,
21
+ "tilt": 77,
22
+ "planned_end": 475,
23
+ "off_bed": 23,
24
+ "fell": 1
25
+ },
26
+ "probe_drop": {
27
+ "planned_end": 500
28
+ },
29
+ "probe_landing": {
30
+ "planned_end": 300
31
+ }
32
+ },
33
+ "wall_per_sim_s": {
34
+ "nominal": {
35
+ "median": 6.512005792403264,
36
+ "min": 5.174011065669888,
37
+ "max": 10.285052144544514,
38
+ "n": 480
39
+ },
40
+ "difficult": {
41
+ "median": 6.332915835010262,
42
+ "min": 5.347029627434759,
43
+ "max": 12.729182214075584,
44
+ "n": 720
45
+ },
46
+ "probe_drop": {
47
+ "median": 9.64788262499558,
48
+ "min": 8.956308217409328,
49
+ "max": 11.025985791348624,
50
+ "n": 500
51
+ },
52
+ "probe_landing": {
53
+ "median": 8.870916865456255,
54
+ "min": 8.242487960185217,
55
+ "max": 9.865579874565926,
56
+ "n": 300
57
+ }
58
+ },
59
+ "build_plus_stand_wall_s": {
60
+ "nominal": {
61
+ "median": 15.904413787648082,
62
+ "max": 35.84517406951636
63
+ },
64
+ "difficult": {
65
+ "median": 13.62626469694078,
66
+ "max": 35.44896775390953
67
+ },
68
+ "probe_drop": {
69
+ "median": 0.6121977488510311,
70
+ "max": 0.7848611148074269
71
+ },
72
+ "probe_landing": {
73
+ "median": 0.6079686884768307,
74
+ "max": 0.9829784920439124
75
+ }
76
+ },
77
+ "totals": {
78
+ "sim_s": 21601.22000000035,
79
+ "wall_s": 156931.79610943794,
80
+ "wall_per_sim_s_overall": 7.264950595819838
81
+ },
82
+ "joint_limits": {
83
+ "nominal": {
84
+ "records": 887143,
85
+ "active": 74,
86
+ "episodes": 480,
87
+ "episodes_active": 0,
88
+ "torque_max": 0.0,
89
+ "pen_max": 0.0,
90
+ "steps": 0,
91
+ "active_record_rate": 8.341383519906035e-05
92
+ },
93
+ "difficult": {
94
+ "records": 1169179,
95
+ "active": 4701,
96
+ "episodes": 720,
97
+ "episodes_active": 21,
98
+ "torque_max": 115.5936559205135,
99
+ "pen_max": 0.31834866181951493,
100
+ "steps": 5787,
101
+ "active_record_rate": 0.004020770130151157
102
+ },
103
+ "probe_drop": {
104
+ "records": 60500,
105
+ "active": 36,
106
+ "episodes": 500,
107
+ "episodes_active": 0,
108
+ "torque_max": 0.0,
109
+ "pen_max": 0.0,
110
+ "steps": 0,
111
+ "active_record_rate": 0.0005950413223140496
112
+ },
113
+ "probe_landing": {
114
+ "records": 45300,
115
+ "active": 0,
116
+ "episodes": 300,
117
+ "episodes_active": 0,
118
+ "torque_max": 0.0,
119
+ "pen_max": 0.0,
120
+ "steps": 0,
121
+ "active_record_rate": 0.0
122
+ }
123
+ },
124
+ "tau_ff": {
125
+ "finite": 3513816,
126
+ "nonzero": 0
127
+ },
128
+ "crm_free": {
129
+ "nominal": {
130
+ "intervals": 886663,
131
+ "free": 0,
132
+ "share": 0.0,
133
+ "probe_free_intervals_before_first_contact": {}
134
+ },
135
+ "difficult": {
136
+ "intervals": 1168459,
137
+ "free": 12,
138
+ "share": 1.0269936728631471e-05,
139
+ "probe_free_intervals_before_first_contact": {}
140
+ },
141
+ "probe_drop": {
142
+ "intervals": 60000,
143
+ "free": 11569,
144
+ "share": 0.19281666666666666,
145
+ "probe_free_intervals_before_first_contact": {
146
+ "0": 8.0,
147
+ "10": 15.0,
148
+ "25": 18.0,
149
+ "50": 24.0,
150
+ "75": 28.0,
151
+ "90": 31.0,
152
+ "100": 33.0
153
+ }
154
+ },
155
+ "probe_landing": {
156
+ "intervals": 45000,
157
+ "free": 2430,
158
+ "share": 0.054,
159
+ "probe_free_intervals_before_first_contact": {
160
+ "0": 2.0,
161
+ "10": 4.0,
162
+ "25": 6.0,
163
+ "50": 8.0,
164
+ "75": 11.0,
165
+ "90": 12.0,
166
+ "100": 15.0
167
+ }
168
+ }
169
+ },
170
+ "nonfoot": {
171
+ "records_flagged": 148,
172
+ "cut:difficult": 144,
173
+ "cut:nominal": 4
174
+ },
175
+ "soil": {
176
+ "mismatch_vs_plan": [],
177
+ "sources": {
178
+ "plan": 2000
179
+ },
180
+ "cohesion_q": {
181
+ "0": 0.03554628044818742,
182
+ "10": 69.7009189480774,
183
+ "25": 245.30562411684411,
184
+ "50": 796.5552915564041,
185
+ "75": 1862.264993882804,
186
+ "90": 2961.5253065087345,
187
+ "100": 3993.145463029502
188
+ },
189
+ "friction_q": {
190
+ "0": 0.6001416839151741,
191
+ "10": 0.6307398432471917,
192
+ "25": 0.6779942816552935,
193
+ "50": 0.7515661712860295,
194
+ "75": 0.8229704294920599,
195
+ "90": 0.8700151145600103,
196
+ "100": 0.8997899850239188
197
+ },
198
+ "density": [
199
+ 1700.0
200
+ ],
201
+ "young_modulus": [
202
+ 500000.0
203
+ ],
204
+ "bins": {
205
+ "c[0,250)": 509,
206
+ "c[1000,2000)": 389,
207
+ "c[2000,4001)": 462,
208
+ "c[250,1000)": 640
209
+ }
210
+ },
211
+ "checker": {
212
+ "ok": true,
213
+ "fails": [],
214
+ "warnings": null,
215
+ "gates": {
216
+ "crm": {
217
+ "split": "0",
218
+ "core_windows": 1503,
219
+ "core_ok": false,
220
+ "single_windows": {
221
+ "FL_leg_ground": 1575,
222
+ "FR_leg_ground": 1007,
223
+ "RL_leg_ground": 1906,
224
+ "RR_leg_ground": 1324
225
+ },
226
+ "single_ok": true
227
+ }
228
+ }
229
+ }
230
+ }
go2_sand_finetune/data/crm_prod/export.log ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "episodes": 3489,
3
+ "valid_records": 2141261,
4
+ "hours": 5.938255555555556,
5
+ "split_counts": {
6
+ "0": 3138,
7
+ "1": 351,
8
+ "2": 0
9
+ },
10
+ "family_counts": {
11
+ "nominal": {
12
+ "0": 843,
13
+ "1": 92,
14
+ "2": 0
15
+ },
16
+ "difficult": {
17
+ "0": 1575,
18
+ "1": 179,
19
+ "2": 0
20
+ },
21
+ "probe_drop": {
22
+ "0": 450,
23
+ "1": 50,
24
+ "2": 0
25
+ },
26
+ "probe_landing": {
27
+ "0": 270,
28
+ "1": 30,
29
+ "2": 0
30
+ }
31
+ },
32
+ "terminal_reason_counts": {
33
+ "planned_end": 1679,
34
+ "fell": 1,
35
+ "tilt": 54,
36
+ "nonfoot_contact": 113,
37
+ "nonfinite": 0,
38
+ "off_bed": 0,
39
+ "fsi_abort": 0,
40
+ "push_cut": 884,
41
+ "validity_cut": 82,
42
+ "chunk": 676
43
+ }
44
+ }
go2_sand_finetune/data/crm_prod/manifest.json ADDED
The diff for this file is too large to render. See raw diff
 
go2_sand_finetune/data/crm_prod/system.json ADDED
@@ -0,0 +1,706 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "go2_locomotion",
3
+ "contract": "go2nrd_contract_v1",
4
+ "record_step_s": 0.01,
5
+ "model_step_s": 0.02,
6
+ "control_step_s": 0.02,
7
+ "target_time_s": 1.0,
8
+ "records_per_episode": 1001,
9
+ "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",
10
+ "bodies": [
11
+ {
12
+ "name": "robot",
13
+ "kind": "articulated",
14
+ "moving": true,
15
+ "state_dim": 37,
16
+ "channels": [
17
+ "x",
18
+ "y",
19
+ "z",
20
+ "qw",
21
+ "qx",
22
+ "qy",
23
+ "qz",
24
+ "FL_hip",
25
+ "FL_thigh",
26
+ "FL_calf",
27
+ "FR_hip",
28
+ "FR_thigh",
29
+ "FR_calf",
30
+ "RL_hip",
31
+ "RL_thigh",
32
+ "RL_calf",
33
+ "RR_hip",
34
+ "RR_thigh",
35
+ "RR_calf",
36
+ "vx",
37
+ "vy",
38
+ "vz",
39
+ "wx",
40
+ "wy",
41
+ "wz",
42
+ "FL_hip_rate",
43
+ "FL_thigh_rate",
44
+ "FL_calf_rate",
45
+ "FR_hip_rate",
46
+ "FR_thigh_rate",
47
+ "FR_calf_rate",
48
+ "RL_hip_rate",
49
+ "RL_thigh_rate",
50
+ "RL_calf_rate",
51
+ "RR_hip_rate",
52
+ "RR_thigh_rate",
53
+ "RR_calf_rate"
54
+ ],
55
+ "channel_types": [
56
+ "position",
57
+ "position",
58
+ "position",
59
+ "quaternion",
60
+ "quaternion",
61
+ "quaternion",
62
+ "quaternion",
63
+ "angle",
64
+ "angle",
65
+ "angle",
66
+ "angle",
67
+ "angle",
68
+ "angle",
69
+ "angle",
70
+ "angle",
71
+ "angle",
72
+ "angle",
73
+ "angle",
74
+ "angle",
75
+ "velocity",
76
+ "velocity",
77
+ "velocity",
78
+ "angular_velocity",
79
+ "angular_velocity",
80
+ "angular_velocity",
81
+ "angular_rate",
82
+ "angular_rate",
83
+ "angular_rate",
84
+ "angular_rate",
85
+ "angular_rate",
86
+ "angular_rate",
87
+ "angular_rate",
88
+ "angular_rate",
89
+ "angular_rate",
90
+ "angular_rate",
91
+ "angular_rate",
92
+ "angular_rate"
93
+ ],
94
+ "channel_mask": [
95
+ 1,
96
+ 1,
97
+ 1,
98
+ 1,
99
+ 1,
100
+ 1,
101
+ 1,
102
+ 1,
103
+ 1,
104
+ 1,
105
+ 1,
106
+ 1,
107
+ 1,
108
+ 1,
109
+ 1,
110
+ 1,
111
+ 1,
112
+ 1,
113
+ 1,
114
+ 1,
115
+ 1,
116
+ 1,
117
+ 1,
118
+ 1,
119
+ 1,
120
+ 1,
121
+ 1,
122
+ 1,
123
+ 1,
124
+ 1,
125
+ 1,
126
+ 1,
127
+ 1,
128
+ 1,
129
+ 1,
130
+ 1,
131
+ 1
132
+ ],
133
+ "action_dim": 12,
134
+ "action_channels": [
135
+ "FL_hip_target",
136
+ "FL_thigh_target",
137
+ "FL_calf_target",
138
+ "FR_hip_target",
139
+ "FR_thigh_target",
140
+ "FR_calf_target",
141
+ "RL_hip_target",
142
+ "RL_thigh_target",
143
+ "RL_calf_target",
144
+ "RR_hip_target",
145
+ "RR_thigh_target",
146
+ "RR_calf_target"
147
+ ],
148
+ "joint_names": [
149
+ "FL_hip_joint",
150
+ "FL_thigh_joint",
151
+ "FL_calf_joint",
152
+ "FR_hip_joint",
153
+ "FR_thigh_joint",
154
+ "FR_calf_joint",
155
+ "RL_hip_joint",
156
+ "RL_thigh_joint",
157
+ "RL_calf_joint",
158
+ "RR_hip_joint",
159
+ "RR_thigh_joint",
160
+ "RR_calf_joint"
161
+ ],
162
+ "base_body": "base_link",
163
+ "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)",
164
+ "default_joint_pos": [
165
+ -0.1,
166
+ 0.9,
167
+ -1.8,
168
+ 0.1,
169
+ 0.9,
170
+ -1.8,
171
+ -0.1,
172
+ 0.9,
173
+ -1.8,
174
+ 0.1,
175
+ 0.9,
176
+ -1.8
177
+ ],
178
+ "action_scale": 0.25,
179
+ "kp": [
180
+ 20.0,
181
+ 20.0,
182
+ 40.0,
183
+ 20.0,
184
+ 20.0,
185
+ 40.0,
186
+ 20.0,
187
+ 20.0,
188
+ 40.0,
189
+ 20.0,
190
+ 20.0,
191
+ 40.0
192
+ ],
193
+ "kd": [
194
+ 1.0,
195
+ 1.0,
196
+ 2.0,
197
+ 1.0,
198
+ 1.0,
199
+ 2.0,
200
+ 1.0,
201
+ 1.0,
202
+ 2.0,
203
+ 1.0,
204
+ 1.0,
205
+ 2.0
206
+ ],
207
+ "effort_limit_nm": [
208
+ 23.5,
209
+ 23.5,
210
+ 45.0,
211
+ 23.5,
212
+ 23.5,
213
+ 45.0,
214
+ 23.5,
215
+ 23.5,
216
+ 45.0,
217
+ 23.5,
218
+ 23.5,
219
+ 45.0
220
+ ]
221
+ },
222
+ {
223
+ "name": "ground",
224
+ "kind": "plane",
225
+ "moving": false,
226
+ "top_z_m": 0.0,
227
+ "size": "flat ground (mjlab plane; CRM soil bed: see physics_config.crm)"
228
+ }
229
+ ],
230
+ "pairs": [
231
+ [
232
+ 0,
233
+ 1
234
+ ],
235
+ [
236
+ 0,
237
+ 1
238
+ ],
239
+ [
240
+ 0,
241
+ 1
242
+ ],
243
+ [
244
+ 0,
245
+ 1
246
+ ]
247
+ ],
248
+ "pair_metadata": [
249
+ {
250
+ "name": "FL_leg_ground",
251
+ "leg": "FL",
252
+ "robot_geoms": {
253
+ "rigid": [
254
+ "FL_foot_collision"
255
+ ],
256
+ "crm": [
257
+ "FL_foot (FSI sphere)",
258
+ "FL_calf (FSI cylinder)"
259
+ ]
260
+ },
261
+ "ground_geoms": {
262
+ "rigid": [
263
+ "terrain"
264
+ ],
265
+ "crm": [
266
+ "CRM soil"
267
+ ]
268
+ }
269
+ },
270
+ {
271
+ "name": "FR_leg_ground",
272
+ "leg": "FR",
273
+ "robot_geoms": {
274
+ "rigid": [
275
+ "FR_foot_collision"
276
+ ],
277
+ "crm": [
278
+ "FR_foot (FSI sphere)",
279
+ "FR_calf (FSI cylinder)"
280
+ ]
281
+ },
282
+ "ground_geoms": {
283
+ "rigid": [
284
+ "terrain"
285
+ ],
286
+ "crm": [
287
+ "CRM soil"
288
+ ]
289
+ }
290
+ },
291
+ {
292
+ "name": "RL_leg_ground",
293
+ "leg": "RL",
294
+ "robot_geoms": {
295
+ "rigid": [
296
+ "RL_foot_collision"
297
+ ],
298
+ "crm": [
299
+ "RL_foot (FSI sphere)",
300
+ "RL_calf (FSI cylinder)"
301
+ ]
302
+ },
303
+ "ground_geoms": {
304
+ "rigid": [
305
+ "terrain"
306
+ ],
307
+ "crm": [
308
+ "CRM soil"
309
+ ]
310
+ }
311
+ },
312
+ {
313
+ "name": "RR_leg_ground",
314
+ "leg": "RR",
315
+ "robot_geoms": {
316
+ "rigid": [
317
+ "RR_foot_collision"
318
+ ],
319
+ "crm": [
320
+ "RR_foot (FSI sphere)",
321
+ "RR_calf (FSI cylinder)"
322
+ ]
323
+ },
324
+ "ground_geoms": {
325
+ "rigid": [
326
+ "terrain"
327
+ ],
328
+ "crm": [
329
+ "CRM soil"
330
+ ]
331
+ }
332
+ }
333
+ ],
334
+ "target_body": 0,
335
+ "contact_rule": {
336
+ "crm": {
337
+ "threshold_n": 20.0,
338
+ "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",
339
+ "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)",
340
+ "aggregation": "max over the force reads acting in the interval",
341
+ "step": "FSI exchange 1.0 ms (2 MBD substeps)",
342
+ "read_window": [
343
+ 2,
344
+ 1
345
+ ],
346
+ "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",
347
+ "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)",
348
+ "relabelled_from_contact_force": true
349
+ }
350
+ },
351
+ "categories": {
352
+ "crm": {
353
+ "ground_id": 1
354
+ }
355
+ },
356
+ "grounds": [
357
+ "rigid",
358
+ "crm"
359
+ ],
360
+ "ground_ids": {
361
+ "rigid": 0,
362
+ "crm": 1
363
+ },
364
+ "families": [
365
+ {
366
+ "name": "nominal",
367
+ "group": "nominal",
368
+ "select": true,
369
+ "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"
370
+ },
371
+ {
372
+ "name": "difficult",
373
+ "group": "difficult",
374
+ "select": true,
375
+ "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)"
376
+ },
377
+ {
378
+ "name": "probe_drop",
379
+ "group": "probe",
380
+ "select": false,
381
+ "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"
382
+ },
383
+ {
384
+ "name": "probe_landing",
385
+ "group": "probe",
386
+ "select": false,
387
+ "note": "low tilted release (0.01-0.12 m, tilt up to 20 deg), policy active, 1.5 s: single feet touch first"
388
+ }
389
+ ],
390
+ "terminal_reasons": [
391
+ "planned_end",
392
+ "fell",
393
+ "tilt",
394
+ "nonfoot_contact",
395
+ "nonfinite",
396
+ "off_bed",
397
+ "fsi_abort",
398
+ "push_cut",
399
+ "validity_cut",
400
+ "chunk"
401
+ ],
402
+ "termination": {
403
+ "min_base_height_m": 0.15,
404
+ "max_tilt_rad": 1.2217304763960306,
405
+ "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"
406
+ },
407
+ "physics_config": {
408
+ "crm": {
409
+ "simulator": "Chrono (pychrono)",
410
+ "pychrono": "unknown",
411
+ "pychrono_core_md5": "600414ef1296c505",
412
+ "backend": "chrono-crm",
413
+ "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e",
414
+ "soil": {
415
+ "keys": {
416
+ "cohesion_pa": "SoilProperties.cohesion_coeff (Pa)",
417
+ "friction": "SoilProperties.mu_fric_s = mu_fric_2 (internal friction mu_s = mu_2)",
418
+ "density": "SoilProperties.density (kg/m^3)",
419
+ "young_modulus_pa": "SoilProperties.Young_modulus (Pa)"
420
+ },
421
+ "base": {
422
+ "cohesion_pa": 2000.0,
423
+ "friction": 0.8,
424
+ "density": 1700.0,
425
+ "young_modulus_pa": 500000.0
426
+ },
427
+ "evaluator_defaults": {
428
+ "cohesion_pa": 2000.0,
429
+ "friction": 0.8,
430
+ "density": 1700.0,
431
+ "young_modulus_pa": 500000.0
432
+ },
433
+ "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']"
434
+ },
435
+ "terrain": "crm",
436
+ "params": {
437
+ "terrain": "crm",
438
+ "pd_mode": "substep",
439
+ "urdf": "go2_mjlab.urdf sha256 5d9b51e03a4215c71c2ad2dd9b97d3dce448a5baf67cdb7ae8262737201746d6",
440
+ "rigid_mbd_step_s": 0.0005,
441
+ "exchange_step_s": null,
442
+ "solver_iterations": 100,
443
+ "contact": {
444
+ "friction": 0.9,
445
+ "restitution": 0.01,
446
+ "kn": 200000.0,
447
+ "gn": 60.0,
448
+ "envelope_m": 0.0025,
449
+ "margin_m": 0.0025
450
+ },
451
+ "crm": {
452
+ "spacing_m": 0.02,
453
+ "depth_m": 0.2,
454
+ "cfd_step_s": 0.0005,
455
+ "integration": "RK2",
456
+ "d0_multiplier": 1.0,
457
+ "free_surface_threshold": 0.8,
458
+ "artificial_viscosity": 2.0,
459
+ "foot_radius_m": 0.025,
460
+ "calf_fsi": true,
461
+ "calf_radius_m": 0.02,
462
+ "calf_length_m": 0.2,
463
+ "active_domain_m": 0.5,
464
+ "active_domain_delay_s": 0.1,
465
+ "bed_margin_m": 0.25,
466
+ "bed_override_m": null,
467
+ "soil": {
468
+ "density": 1700.0,
469
+ "young_modulus_pa": 500000.0,
470
+ "poisson_ratio": 0.3,
471
+ "mu_i0": 0.04,
472
+ "friction": 0.8,
473
+ "average_diam_m": 0.005,
474
+ "cohesion_pa": 2000.0
475
+ }
476
+ }
477
+ },
478
+ "robot": {
479
+ "robot": "go2_mjlab",
480
+ "rotor": {
481
+ "enabled": true,
482
+ "coupling": "relative",
483
+ "ratio": 1.0,
484
+ "shaft_inertia": 0.0001,
485
+ "compensate": true,
486
+ "armature_scale": 1.0
487
+ },
488
+ "armature": {
489
+ "FL_hip_joint": 0.01,
490
+ "FL_thigh_joint": 0.01,
491
+ "FL_calf_joint": 0.02,
492
+ "FR_hip_joint": 0.01,
493
+ "FR_thigh_joint": 0.01,
494
+ "FR_calf_joint": 0.02,
495
+ "RL_hip_joint": 0.01,
496
+ "RL_thigh_joint": 0.01,
497
+ "RL_calf_joint": 0.02,
498
+ "RR_hip_joint": 0.01,
499
+ "RR_thigh_joint": 0.01,
500
+ "RR_calf_joint": 0.02
501
+ },
502
+ "legacy_calf_fsi": true,
503
+ "joint_limits": {
504
+ "mode": "mujoco",
505
+ "params_sha256": "e8de60cb6fe591c8"
506
+ }
507
+ },
508
+ "robot_mass_kg": 15.206408,
509
+ "mbd_step_s": 0.0005,
510
+ "sample_step_s": 0.001,
511
+ "fsi_exchange_step_s": 0.001,
512
+ "rigid_sample_note": null,
513
+ "surface_z_in_sim": 0.2,
514
+ "deploy": {
515
+ "config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2",
516
+ "model_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45",
517
+ "ll_dt": 0.005,
518
+ "policy_dt": 0.019999999552965164,
519
+ "tau_max": [
520
+ 23.5,
521
+ 23.5,
522
+ 45.0,
523
+ 23.5,
524
+ 23.5,
525
+ 45.0,
526
+ 23.5,
527
+ 23.5,
528
+ 45.0,
529
+ 23.5,
530
+ 23.5,
531
+ 45.0
532
+ ],
533
+ "torque_clip": false,
534
+ "command_clip": "none",
535
+ "fixstand_kp": [
536
+ 60.0,
537
+ 80.0,
538
+ 80.0,
539
+ 60.0,
540
+ 80.0,
541
+ 80.0,
542
+ 60.0,
543
+ 80.0,
544
+ 80.0,
545
+ 60.0,
546
+ 80.0,
547
+ 80.0
548
+ ],
549
+ "fixstand_kd": [
550
+ 5.0,
551
+ 4.0,
552
+ 4.0,
553
+ 5.0,
554
+ 4.0,
555
+ 4.0,
556
+ 5.0,
557
+ 4.0,
558
+ 4.0,
559
+ 5.0,
560
+ 4.0,
561
+ 4.0
562
+ ]
563
+ },
564
+ "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)",
565
+ "injection": "plan OU target noise added to the HighController target before torqueClip (motor order)",
566
+ "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)",
567
+ "force_read_window": {
568
+ "lo": 2,
569
+ "hi": 1,
570
+ "rule": "steps a+1..b <- reads a+1-lo..b-hi"
571
+ },
572
+ "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)",
573
+ "actuator": "PD law at every MBD step, clamped at the effort limit (23.5 / 45 N m) per step; no deploy torqueClip",
574
+ "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)"
575
+ }
576
+ },
577
+ "extras": {
578
+ "ground": "[N] int8 ground id of each episode (system.json ground_ids); optional (version B of the NRD)",
579
+ "episode_id": "[N] int64 = parent_episode_id * 10 + piece",
580
+ "parent_episode_id": "[N] int64 planned episode id; piece [N] int8 its push piece; record_offset [N] int32 first parent record of the piece",
581
+ "group_id": "[N] int64 = the parent's planned group (pieces share it and the split)",
582
+ "obs": "[N, T, 47] policy observation at policy records (even records), NaN elsewhere",
583
+ "raw_action": "[N, T, 12] raw policy output at policy records, NaN elsewhere",
584
+ "command": "[N, T, 3] (vx, vy, wz) command of the control period containing the record",
585
+ "phase_k": "[N, T] int32 the policy's phase counter k",
586
+ "push_force": "[N, T, 3] world push force in [t, t + 10 ms) (excised in kept data: zero)",
587
+ "nonfoot_contact": "[N, T] uint8 non-foot ground contact in [t, t + 10 ms)",
588
+ "contact_force": "[N, T-1, 4] max pair normal force over the interval's steps (N)",
589
+ "foot_force, calf_force": "[N, T-1, 4] optional CRM diagnostics (N)",
590
+ "validity_check": "[N] int8 0 = none, else 1 + index of the export validity check that cut the episode",
591
+ "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)",
592
+ "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",
593
+ "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",
594
+ "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)"
595
+ },
596
+ "core_free_flag": {
597
+ "array": "crm_free",
598
+ "grounds": [
599
+ "crm"
600
+ ],
601
+ "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"
602
+ },
603
+ "soil_columns": [
604
+ "cohesion_pa",
605
+ "friction",
606
+ "density",
607
+ "young_modulus_pa"
608
+ ],
609
+ "ground_feature_names": [
610
+ "is_crm",
611
+ "cohesion_code",
612
+ "friction_code"
613
+ ],
614
+ "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",
615
+ "evaluation": {
616
+ "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.",
617
+ "free": {},
618
+ "windows": {
619
+ "horizons_s": [
620
+ 0.02,
621
+ 0.2,
622
+ 0.5,
623
+ 1.0
624
+ ],
625
+ "first_start_s": 0.1,
626
+ "start_every_s": 0.5,
627
+ "end_window": true
628
+ },
629
+ "long_windows": {
630
+ "horizons_s": [
631
+ 2.0
632
+ ],
633
+ "first_start_s": 0.1,
634
+ "start_every_s": 1.0
635
+ },
636
+ "event_windows": {
637
+ "horizons_s": [
638
+ 0.2,
639
+ 0.5,
640
+ 1.0
641
+ ],
642
+ "lead_s": 0.1,
643
+ "min_gap_s": 0.1,
644
+ "events": [
645
+ "onset"
646
+ ]
647
+ },
648
+ "flags": {
649
+ "fall": {
650
+ "any": [
651
+ {
652
+ "body": "robot",
653
+ "channel": "z",
654
+ "below": 0.15
655
+ },
656
+ {
657
+ "body": "robot",
658
+ "tilt_above_rad": 0.7853981633974483
659
+ }
660
+ ]
661
+ }
662
+ },
663
+ "contact_tolerance_steps": 2,
664
+ "batch": 2048,
665
+ "score": [
666
+ {
667
+ "stat": "windows/1.0/robot/pos_m/p95",
668
+ "scale": 0.05,
669
+ "weight": 1.0
670
+ },
671
+ {
672
+ "stat": "windows/1.0/robot/angle_rad/p95",
673
+ "scale": 0.08726646259971647,
674
+ "weight": 1.0
675
+ },
676
+ {
677
+ "stat": "windows/1.0/robot/joint_rms_rad/p95",
678
+ "scale": 0.1,
679
+ "weight": 1.0
680
+ },
681
+ {
682
+ "stat": "windows/contacts/all/event_error_rate",
683
+ "scale": 0.1,
684
+ "weight": 1.0
685
+ },
686
+ {
687
+ "stat": "windows/contacts/all/timing_s/p95",
688
+ "scale": 0.02,
689
+ "weight": 1.0
690
+ },
691
+ {
692
+ "stat": "windows/flags/fall/disagreement",
693
+ "scale": 0.01,
694
+ "weight": 1.0
695
+ },
696
+ {
697
+ "stat": "nonfinite_fraction",
698
+ "scale": 0.01,
699
+ "weight": 1.0
700
+ }
701
+ ]
702
+ },
703
+ "campaigns": [
704
+ "crm_prod"
705
+ ]
706
+ }
go2_sand_finetune/data/crm_prod/unified_data.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35b73ce2d8bd1c28f7de88c92347dd6f76ee7b3c509635d900565027f24f0271
3
+ size 1096892318
go2_sand_finetune/data/crm_prod/validate_report.json ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dir": "/home/harry/go2_sand/nrd_data/export/crm_prod",
3
+ "system": "go2_locomotion",
4
+ "episodes": 3489,
5
+ "valid_records": 2141261,
6
+ "records_per_episode": 1001,
7
+ "hours": 5.938255555555556,
8
+ "padded_records": 3492489,
9
+ "padding_fraction": 0.3868954204293843,
10
+ "quat_norm_err_max": 4.209746207184395e-08,
11
+ "ground_counts": {
12
+ "crm": 3489
13
+ },
14
+ "soil": {
15
+ "cohesion_pa": {
16
+ "min": 0.035546280443668365,
17
+ "p50": 821.8724975585938,
18
+ "max": 3993.1455078125
19
+ },
20
+ "friction": {
21
+ "min": 0.600141704082489,
22
+ "p50": 0.7523771524429321,
23
+ "max": 0.8997899889945984
24
+ },
25
+ "density": {
26
+ "min": 1700.0,
27
+ "p50": 1700.0,
28
+ "max": 1700.0
29
+ },
30
+ "young_modulus_pa": {
31
+ "min": 500000.0,
32
+ "p50": 500000.0,
33
+ "max": 500000.0
34
+ }
35
+ },
36
+ "ground_features_formula_max_err": 1.1920928955078125e-07,
37
+ "ground_features": {
38
+ "is_crm": {
39
+ "min": 1.0,
40
+ "max": 1.0
41
+ },
42
+ "cohesion_code": {
43
+ "min": 5.018154115532525e-05,
44
+ "max": 0.9994302988052368
45
+ },
46
+ "friction_code": {
47
+ "min": 0.00047227973118424416,
48
+ "max": 0.999299943447113
49
+ }
50
+ },
51
+ "prev_raw_action": {
52
+ "unknown": 0,
53
+ "zero": 1989,
54
+ "abs_max": 8.03856372833252
55
+ },
56
+ "groups": 1989,
57
+ "split_family_counts": {
58
+ "nominal": {
59
+ "0": 843,
60
+ "1": 92,
61
+ "2": 0
62
+ },
63
+ "difficult": {
64
+ "0": 1575,
65
+ "1": 179,
66
+ "2": 0
67
+ },
68
+ "probe_drop": {
69
+ "0": 450,
70
+ "1": 50,
71
+ "2": 0
72
+ },
73
+ "probe_landing": {
74
+ "0": 270,
75
+ "1": 30,
76
+ "2": 0
77
+ }
78
+ },
79
+ "validation_group_fraction": {
80
+ "nominal": 0.1,
81
+ "difficult": 0.1001410437235543,
82
+ "probe_drop": 0.1,
83
+ "probe_landing": 0.1
84
+ },
85
+ "terminal_reasons": {
86
+ "planned_end": 1679,
87
+ "fell": 1,
88
+ "tilt": 54,
89
+ "nonfoot_contact": 113,
90
+ "push_cut": 884,
91
+ "validity_cut": 82,
92
+ "chunk": 676
93
+ },
94
+ "task_pieces": {
95
+ "count": 2689,
96
+ "min_records": 256,
97
+ "shorter_than_256": 0
98
+ },
99
+ "rate_consistency": {
100
+ "crm": {
101
+ "base_position": {
102
+ "record_10ms": {
103
+ "rms": 0.0008552051479089693,
104
+ "p50": 0.00028859497979283333,
105
+ "p95": 0.001703498512506483,
106
+ "max": 0.04324042797088623,
107
+ "relative_rms": 0.0035588069327056504
108
+ },
109
+ "shift_relative_rms": {
110
+ "aligned": 0.0035542627149714495,
111
+ "rates_one_record_late": 0.0777165189655358,
112
+ "rates_one_record_early": 0.08212193609071944
113
+ },
114
+ "best_alignment": "aligned",
115
+ "step_20ms_simpson": {
116
+ "rms": 0.0006516958501499254,
117
+ "p50": 0.00025070862223704887,
118
+ "p95": 0.0013325675080219914,
119
+ "max": 0.01913793881734227,
120
+ "relative_rms": 0.0027119337567129875
121
+ },
122
+ "step_20ms_relative_rms_per_channel": [
123
+ 0.0016,
124
+ 0.0017,
125
+ 0.0036
126
+ ]
127
+ },
128
+ "joints": {
129
+ "record_10ms": {
130
+ "rms": 0.07984451823691222,
131
+ "p50": 0.023865535855293274,
132
+ "p95": 0.16232565045356745,
133
+ "max": 7.728699743747711,
134
+ "relative_rms": 0.04516961940879301
135
+ },
136
+ "shift_relative_rms": {
137
+ "aligned": 0.04499651834439178,
138
+ "rates_one_record_late": 0.2617835738817814,
139
+ "rates_one_record_early": 0.31160872561617914
140
+ },
141
+ "best_alignment": "aligned",
142
+ "step_20ms_simpson": {
143
+ "rms": 0.07646891726612944,
144
+ "p50": 0.013368030389149937,
145
+ "p95": 0.16061253001292553,
146
+ "max": 3.8240599234898873,
147
+ "relative_rms": 0.043259975334370857
148
+ },
149
+ "step_20ms_relative_rms_per_channel": [
150
+ 0.0184,
151
+ 0.0209,
152
+ 0.0479,
153
+ 0.0186,
154
+ 0.0206,
155
+ 0.0472,
156
+ 0.0192,
157
+ 0.0211,
158
+ 0.0462,
159
+ 0.0189,
160
+ 0.0203,
161
+ 0.0459
162
+ ]
163
+ },
164
+ "base_angular": {
165
+ "record_10ms": {
166
+ "rms": 0.010827812006917107,
167
+ "p50": 0.002913675942259287,
168
+ "p95": 0.023299576331908666,
169
+ "max": 0.7863338810551888,
170
+ "relative_rms": 0.02308993313151337
171
+ },
172
+ "record_10ms_if_body_frame": {
173
+ "rms": 0.5291096325679482,
174
+ "p50": 0.08995285710925553,
175
+ "p95": 1.1821052761522857,
176
+ "max": 24.14709121207038,
177
+ "relative_rms": 1.1283079192203287
178
+ },
179
+ "frame_hint": "world",
180
+ "shift_relative_rms": {
181
+ "aligned": 0.023069739780111648,
182
+ "rates_one_record_late": 0.29664622617147135,
183
+ "rates_one_record_early": 0.31922825030145313
184
+ },
185
+ "best_alignment": "aligned",
186
+ "step_20ms_simpson": {
187
+ "rms": 0.012490932673752914,
188
+ "p50": 0.0023940412705333314,
189
+ "p95": 0.02659319169069073,
190
+ "max": 0.5334440947880124,
191
+ "relative_rms": 0.02663648020513682
192
+ }
193
+ },
194
+ "episodes": 400
195
+ }
196
+ },
197
+ "strict_rule": "crm_free = 1 in every interval of the window (CRM rows)",
198
+ "coverage": {
199
+ "all": {
200
+ "episodes": 3489,
201
+ "windows": 1068382,
202
+ "free_robot": 7059,
203
+ "core_robot": 1722,
204
+ "free_robot_strict_1N": 6808,
205
+ "core_robot_strict_1N": 1669,
206
+ "single_FL_leg_ground": 1710,
207
+ "on_FL_leg_ground": 771203,
208
+ "single_FR_leg_ground": 1099,
209
+ "on_FR_leg_ground": 744988,
210
+ "single_RL_leg_ground": 2135,
211
+ "on_RL_leg_ground": 753592,
212
+ "single_RR_leg_ground": 1441,
213
+ "on_RR_leg_ground": 742124,
214
+ "multi_contact": 1054938,
215
+ "feet_on_histogram": {
216
+ "0": 7059,
217
+ "1": 6385,
218
+ "2": 466178,
219
+ "3": 281874,
220
+ "4": 306886
221
+ },
222
+ "onsets_FL_leg_ground": 47446,
223
+ "onsets_FR_leg_ground": 49932,
224
+ "onsets_RL_leg_ground": 48840,
225
+ "onsets_RR_leg_ground": 48749
226
+ },
227
+ "split0": {
228
+ "episodes": 3138,
229
+ "windows": 962979,
230
+ "free_robot": 6371,
231
+ "core_robot": 1554,
232
+ "free_robot_strict_1N": 6141,
233
+ "core_robot_strict_1N": 1503,
234
+ "single_FL_leg_ground": 1575,
235
+ "on_FL_leg_ground": 694308,
236
+ "single_FR_leg_ground": 1007,
237
+ "on_FR_leg_ground": 671908,
238
+ "single_RL_leg_ground": 1906,
239
+ "on_RL_leg_ground": 679325,
240
+ "single_RR_leg_ground": 1324,
241
+ "on_RR_leg_ground": 669097,
242
+ "multi_contact": 950796,
243
+ "feet_on_histogram": {
244
+ "0": 6371,
245
+ "1": 5812,
246
+ "2": 420302,
247
+ "3": 253754,
248
+ "4": 276740
249
+ },
250
+ "onsets_FL_leg_ground": 42769,
251
+ "onsets_FR_leg_ground": 44941,
252
+ "onsets_RL_leg_ground": 44076,
253
+ "onsets_RR_leg_ground": 43880
254
+ },
255
+ "split1": {
256
+ "episodes": 351,
257
+ "windows": 105403,
258
+ "free_robot": 688,
259
+ "core_robot": 168,
260
+ "free_robot_strict_1N": 667,
261
+ "core_robot_strict_1N": 166,
262
+ "single_FL_leg_ground": 135,
263
+ "on_FL_leg_ground": 76895,
264
+ "single_FR_leg_ground": 92,
265
+ "on_FR_leg_ground": 73080,
266
+ "single_RL_leg_ground": 229,
267
+ "on_RL_leg_ground": 74267,
268
+ "single_RR_leg_ground": 117,
269
+ "on_RR_leg_ground": 73027,
270
+ "multi_contact": 104142,
271
+ "feet_on_histogram": {
272
+ "0": 688,
273
+ "1": 573,
274
+ "2": 45876,
275
+ "3": 28120,
276
+ "4": 30146
277
+ },
278
+ "onsets_FL_leg_ground": 4677,
279
+ "onsets_FR_leg_ground": 4991,
280
+ "onsets_RL_leg_ground": 4764,
281
+ "onsets_RR_leg_ground": 4869
282
+ },
283
+ "family_nominal": {
284
+ "episodes": 935,
285
+ "windows": 443278,
286
+ "free_robot": 0,
287
+ "core_robot": 0,
288
+ "free_robot_strict_1N": 0,
289
+ "core_robot_strict_1N": 0,
290
+ "single_FL_leg_ground": 15,
291
+ "on_FL_leg_ground": 314504,
292
+ "single_FR_leg_ground": 4,
293
+ "on_FR_leg_ground": 300356,
294
+ "single_RL_leg_ground": 24,
295
+ "on_RL_leg_ground": 304955,
296
+ "single_RR_leg_ground": 15,
297
+ "on_RR_leg_ground": 299383,
298
+ "multi_contact": 443220,
299
+ "feet_on_histogram": {
300
+ "0": 0,
301
+ "1": 58,
302
+ "2": 243440,
303
+ "3": 66860,
304
+ "4": 132920
305
+ },
306
+ "onsets_FL_leg_ground": 14938,
307
+ "onsets_FR_leg_ground": 15322,
308
+ "onsets_RL_leg_ground": 15741,
309
+ "onsets_RR_leg_ground": 14930
310
+ },
311
+ "family_difficult": {
312
+ "episodes": 1754,
313
+ "windows": 572604,
314
+ "free_robot": 57,
315
+ "core_robot": 12,
316
+ "free_robot_strict_1N": 2,
317
+ "core_robot_strict_1N": 1,
318
+ "single_FL_leg_ground": 1499,
319
+ "on_FL_leg_ground": 424610,
320
+ "single_FR_leg_ground": 886,
321
+ "on_FR_leg_ground": 413493,
322
+ "single_RL_leg_ground": 1895,
323
+ "on_RL_leg_ground": 417143,
324
+ "single_RR_leg_ground": 1241,
325
+ "on_RR_leg_ground": 412087,
326
+ "multi_contact": 567026,
327
+ "feet_on_histogram": {
328
+ "0": 57,
329
+ "1": 5521,
330
+ "2": 201195,
331
+ "3": 203902,
332
+ "4": 161929
333
+ },
334
+ "onsets_FL_leg_ground": 30337,
335
+ "onsets_FR_leg_ground": 32421,
336
+ "onsets_RL_leg_ground": 30924,
337
+ "onsets_RR_leg_ground": 31653
338
+ },
339
+ "family_probe_drop": {
340
+ "episodes": 500,
341
+ "windows": 30000,
342
+ "free_robot": 5746,
343
+ "core_robot": 1340,
344
+ "free_robot_strict_1N": 5667,
345
+ "core_robot_strict_1N": 1326,
346
+ "single_FL_leg_ground": 100,
347
+ "on_FL_leg_ground": 17899,
348
+ "single_FR_leg_ground": 97,
349
+ "on_FR_leg_ground": 17209,
350
+ "single_RL_leg_ground": 102,
351
+ "on_RL_leg_ground": 17514,
352
+ "single_RR_leg_ground": 100,
353
+ "on_RR_leg_ground": 16828,
354
+ "multi_contact": 23855,
355
+ "feet_on_histogram": {
356
+ "0": 5746,
357
+ "1": 399,
358
+ "2": 9851,
359
+ "3": 6667,
360
+ "4": 7337
361
+ },
362
+ "onsets_FL_leg_ground": 1234,
363
+ "onsets_FR_leg_ground": 1252,
364
+ "onsets_RL_leg_ground": 1235,
365
+ "onsets_RR_leg_ground": 1238
366
+ },
367
+ "family_probe_landing": {
368
+ "episodes": 300,
369
+ "windows": 22500,
370
+ "free_robot": 1256,
371
+ "core_robot": 370,
372
+ "free_robot_strict_1N": 1139,
373
+ "core_robot_strict_1N": 342,
374
+ "single_FL_leg_ground": 96,
375
+ "on_FL_leg_ground": 14190,
376
+ "single_FR_leg_ground": 112,
377
+ "on_FR_leg_ground": 13930,
378
+ "single_RL_leg_ground": 114,
379
+ "on_RL_leg_ground": 13980,
380
+ "single_RR_leg_ground": 85,
381
+ "on_RR_leg_ground": 13826,
382
+ "multi_contact": 20837,
383
+ "feet_on_histogram": {
384
+ "0": 1256,
385
+ "1": 407,
386
+ "2": 11692,
387
+ "3": 4445,
388
+ "4": 4700
389
+ },
390
+ "onsets_FL_leg_ground": 937,
391
+ "onsets_FR_leg_ground": 937,
392
+ "onsets_RL_leg_ground": 940,
393
+ "onsets_RR_leg_ground": 928
394
+ },
395
+ "ground_crm": {
396
+ "episodes": 3489,
397
+ "windows": 1068382,
398
+ "free_robot": 7059,
399
+ "core_robot": 1722,
400
+ "free_robot_strict_1N": 6808,
401
+ "core_robot_strict_1N": 1669,
402
+ "single_FL_leg_ground": 1710,
403
+ "on_FL_leg_ground": 771203,
404
+ "single_FR_leg_ground": 1099,
405
+ "on_FR_leg_ground": 744988,
406
+ "single_RL_leg_ground": 2135,
407
+ "on_RL_leg_ground": 753592,
408
+ "single_RR_leg_ground": 1441,
409
+ "on_RR_leg_ground": 742124,
410
+ "multi_contact": 1054938,
411
+ "feet_on_histogram": {
412
+ "0": 7059,
413
+ "1": 6385,
414
+ "2": 466178,
415
+ "3": 281874,
416
+ "4": 306886
417
+ },
418
+ "onsets_FL_leg_ground": 47446,
419
+ "onsets_FR_leg_ground": 49932,
420
+ "onsets_RL_leg_ground": 48840,
421
+ "onsets_RR_leg_ground": 48749
422
+ },
423
+ "ground_crm_split0": {
424
+ "episodes": 3138,
425
+ "windows": 962979,
426
+ "free_robot": 6371,
427
+ "core_robot": 1554,
428
+ "free_robot_strict_1N": 6141,
429
+ "core_robot_strict_1N": 1503,
430
+ "single_FL_leg_ground": 1575,
431
+ "on_FL_leg_ground": 694308,
432
+ "single_FR_leg_ground": 1007,
433
+ "on_FR_leg_ground": 671908,
434
+ "single_RL_leg_ground": 1906,
435
+ "on_RL_leg_ground": 679325,
436
+ "single_RR_leg_ground": 1324,
437
+ "on_RR_leg_ground": 669097,
438
+ "multi_contact": 950796,
439
+ "feet_on_histogram": {
440
+ "0": 6371,
441
+ "1": 5812,
442
+ "2": 420302,
443
+ "3": 253754,
444
+ "4": 276740
445
+ },
446
+ "onsets_FL_leg_ground": 42769,
447
+ "onsets_FR_leg_ground": 44941,
448
+ "onsets_RL_leg_ground": 44076,
449
+ "onsets_RR_leg_ground": 43880
450
+ }
451
+ },
452
+ "gates": {
453
+ "crm": {
454
+ "split": "0",
455
+ "core_windows": 1503,
456
+ "core_ok": false,
457
+ "single_windows": {
458
+ "FL_leg_ground": 1575,
459
+ "FR_leg_ground": 1007,
460
+ "RL_leg_ground": 1906,
461
+ "RR_leg_ground": 1324
462
+ },
463
+ "single_ok": true
464
+ }
465
+ },
466
+ "fails": [],
467
+ "warns": [
468
+ "gate: crm: 1503 contact-free core-grid training windows (< 10000)"
469
+ ],
470
+ "ok": true
471
+ }
go2_sand_finetune/data/lateral_crm_v2_cuda/export.log ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "episodes": 149,
3
+ "valid_records": 136413,
4
+ "hours": 0.3785111111111111,
5
+ "split_counts": {
6
+ "0": 135,
7
+ "1": 14,
8
+ "2": 0
9
+ },
10
+ "family_counts": {
11
+ "nominal": {
12
+ "0": 103,
13
+ "1": 12,
14
+ "2": 0
15
+ },
16
+ "difficult": {
17
+ "0": 32,
18
+ "1": 2,
19
+ "2": 0
20
+ },
21
+ "probe_drop": {
22
+ "0": 0,
23
+ "1": 0,
24
+ "2": 0
25
+ },
26
+ "probe_landing": {
27
+ "0": 0,
28
+ "1": 0,
29
+ "2": 0
30
+ }
31
+ },
32
+ "terminal_reason_counts": {
33
+ "planned_end": 56,
34
+ "fell": 0,
35
+ "tilt": 2,
36
+ "nonfoot_contact": 22,
37
+ "nonfinite": 0,
38
+ "off_bed": 0,
39
+ "fsi_abort": 0,
40
+ "push_cut": 0,
41
+ "validity_cut": 0,
42
+ "chunk": 69
43
+ }
44
+ }
go2_sand_finetune/data/lateral_crm_v2_cuda/manifest.json ADDED
The diff for this file is too large to render. See raw diff
 
go2_sand_finetune/data/lateral_crm_v2_cuda/system.json ADDED
@@ -0,0 +1,734 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "go2_locomotion",
3
+ "contract": "go2nrd_contract_v1",
4
+ "record_step_s": 0.01,
5
+ "model_step_s": 0.02,
6
+ "control_step_s": 0.02,
7
+ "target_time_s": 1.0,
8
+ "records_per_episode": 1001,
9
+ "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",
10
+ "bodies": [
11
+ {
12
+ "name": "robot",
13
+ "kind": "articulated",
14
+ "moving": true,
15
+ "state_dim": 37,
16
+ "channels": [
17
+ "x",
18
+ "y",
19
+ "z",
20
+ "qw",
21
+ "qx",
22
+ "qy",
23
+ "qz",
24
+ "FL_hip",
25
+ "FL_thigh",
26
+ "FL_calf",
27
+ "FR_hip",
28
+ "FR_thigh",
29
+ "FR_calf",
30
+ "RL_hip",
31
+ "RL_thigh",
32
+ "RL_calf",
33
+ "RR_hip",
34
+ "RR_thigh",
35
+ "RR_calf",
36
+ "vx",
37
+ "vy",
38
+ "vz",
39
+ "wx",
40
+ "wy",
41
+ "wz",
42
+ "FL_hip_rate",
43
+ "FL_thigh_rate",
44
+ "FL_calf_rate",
45
+ "FR_hip_rate",
46
+ "FR_thigh_rate",
47
+ "FR_calf_rate",
48
+ "RL_hip_rate",
49
+ "RL_thigh_rate",
50
+ "RL_calf_rate",
51
+ "RR_hip_rate",
52
+ "RR_thigh_rate",
53
+ "RR_calf_rate"
54
+ ],
55
+ "channel_types": [
56
+ "position",
57
+ "position",
58
+ "position",
59
+ "quaternion",
60
+ "quaternion",
61
+ "quaternion",
62
+ "quaternion",
63
+ "angle",
64
+ "angle",
65
+ "angle",
66
+ "angle",
67
+ "angle",
68
+ "angle",
69
+ "angle",
70
+ "angle",
71
+ "angle",
72
+ "angle",
73
+ "angle",
74
+ "angle",
75
+ "velocity",
76
+ "velocity",
77
+ "velocity",
78
+ "angular_velocity",
79
+ "angular_velocity",
80
+ "angular_velocity",
81
+ "angular_rate",
82
+ "angular_rate",
83
+ "angular_rate",
84
+ "angular_rate",
85
+ "angular_rate",
86
+ "angular_rate",
87
+ "angular_rate",
88
+ "angular_rate",
89
+ "angular_rate",
90
+ "angular_rate",
91
+ "angular_rate",
92
+ "angular_rate"
93
+ ],
94
+ "channel_mask": [
95
+ 1,
96
+ 1,
97
+ 1,
98
+ 1,
99
+ 1,
100
+ 1,
101
+ 1,
102
+ 1,
103
+ 1,
104
+ 1,
105
+ 1,
106
+ 1,
107
+ 1,
108
+ 1,
109
+ 1,
110
+ 1,
111
+ 1,
112
+ 1,
113
+ 1,
114
+ 1,
115
+ 1,
116
+ 1,
117
+ 1,
118
+ 1,
119
+ 1,
120
+ 1,
121
+ 1,
122
+ 1,
123
+ 1,
124
+ 1,
125
+ 1,
126
+ 1,
127
+ 1,
128
+ 1,
129
+ 1,
130
+ 1,
131
+ 1
132
+ ],
133
+ "action_dim": 12,
134
+ "action_channels": [
135
+ "FL_hip_target",
136
+ "FL_thigh_target",
137
+ "FL_calf_target",
138
+ "FR_hip_target",
139
+ "FR_thigh_target",
140
+ "FR_calf_target",
141
+ "RL_hip_target",
142
+ "RL_thigh_target",
143
+ "RL_calf_target",
144
+ "RR_hip_target",
145
+ "RR_thigh_target",
146
+ "RR_calf_target"
147
+ ],
148
+ "joint_names": [
149
+ "FL_hip_joint",
150
+ "FL_thigh_joint",
151
+ "FL_calf_joint",
152
+ "FR_hip_joint",
153
+ "FR_thigh_joint",
154
+ "FR_calf_joint",
155
+ "RL_hip_joint",
156
+ "RL_thigh_joint",
157
+ "RL_calf_joint",
158
+ "RR_hip_joint",
159
+ "RR_thigh_joint",
160
+ "RR_calf_joint"
161
+ ],
162
+ "base_body": "base_link",
163
+ "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)",
164
+ "default_joint_pos": [
165
+ -0.1,
166
+ 0.9,
167
+ -1.8,
168
+ 0.1,
169
+ 0.9,
170
+ -1.8,
171
+ -0.1,
172
+ 0.9,
173
+ -1.8,
174
+ 0.1,
175
+ 0.9,
176
+ -1.8
177
+ ],
178
+ "action_scale": 0.25,
179
+ "kp": [
180
+ 20.0,
181
+ 20.0,
182
+ 40.0,
183
+ 20.0,
184
+ 20.0,
185
+ 40.0,
186
+ 20.0,
187
+ 20.0,
188
+ 40.0,
189
+ 20.0,
190
+ 20.0,
191
+ 40.0
192
+ ],
193
+ "kd": [
194
+ 1.0,
195
+ 1.0,
196
+ 2.0,
197
+ 1.0,
198
+ 1.0,
199
+ 2.0,
200
+ 1.0,
201
+ 1.0,
202
+ 2.0,
203
+ 1.0,
204
+ 1.0,
205
+ 2.0
206
+ ],
207
+ "effort_limit_nm": [
208
+ 23.5,
209
+ 23.5,
210
+ 45.0,
211
+ 23.5,
212
+ 23.5,
213
+ 45.0,
214
+ 23.5,
215
+ 23.5,
216
+ 45.0,
217
+ 23.5,
218
+ 23.5,
219
+ 45.0
220
+ ]
221
+ },
222
+ {
223
+ "name": "ground",
224
+ "kind": "plane",
225
+ "moving": false,
226
+ "top_z_m": 0.0,
227
+ "size": "flat ground (mjlab plane; CRM soil bed: see physics_config.crm)"
228
+ }
229
+ ],
230
+ "pairs": [
231
+ [
232
+ 0,
233
+ 1
234
+ ],
235
+ [
236
+ 0,
237
+ 1
238
+ ],
239
+ [
240
+ 0,
241
+ 1
242
+ ],
243
+ [
244
+ 0,
245
+ 1
246
+ ]
247
+ ],
248
+ "pair_metadata": [
249
+ {
250
+ "name": "FL_leg_ground",
251
+ "leg": "FL",
252
+ "robot_geoms": {
253
+ "rigid": [
254
+ "FL_foot_collision"
255
+ ],
256
+ "crm": [
257
+ "FL_foot (FSI sphere)",
258
+ "FL_calf (FSI cylinder)"
259
+ ]
260
+ },
261
+ "ground_geoms": {
262
+ "rigid": [
263
+ "terrain"
264
+ ],
265
+ "crm": [
266
+ "CRM soil"
267
+ ]
268
+ }
269
+ },
270
+ {
271
+ "name": "FR_leg_ground",
272
+ "leg": "FR",
273
+ "robot_geoms": {
274
+ "rigid": [
275
+ "FR_foot_collision"
276
+ ],
277
+ "crm": [
278
+ "FR_foot (FSI sphere)",
279
+ "FR_calf (FSI cylinder)"
280
+ ]
281
+ },
282
+ "ground_geoms": {
283
+ "rigid": [
284
+ "terrain"
285
+ ],
286
+ "crm": [
287
+ "CRM soil"
288
+ ]
289
+ }
290
+ },
291
+ {
292
+ "name": "RL_leg_ground",
293
+ "leg": "RL",
294
+ "robot_geoms": {
295
+ "rigid": [
296
+ "RL_foot_collision"
297
+ ],
298
+ "crm": [
299
+ "RL_foot (FSI sphere)",
300
+ "RL_calf (FSI cylinder)"
301
+ ]
302
+ },
303
+ "ground_geoms": {
304
+ "rigid": [
305
+ "terrain"
306
+ ],
307
+ "crm": [
308
+ "CRM soil"
309
+ ]
310
+ }
311
+ },
312
+ {
313
+ "name": "RR_leg_ground",
314
+ "leg": "RR",
315
+ "robot_geoms": {
316
+ "rigid": [
317
+ "RR_foot_collision"
318
+ ],
319
+ "crm": [
320
+ "RR_foot (FSI sphere)",
321
+ "RR_calf (FSI cylinder)"
322
+ ]
323
+ },
324
+ "ground_geoms": {
325
+ "rigid": [
326
+ "terrain"
327
+ ],
328
+ "crm": [
329
+ "CRM soil"
330
+ ]
331
+ }
332
+ }
333
+ ],
334
+ "target_body": 0,
335
+ "contact_rule": {
336
+ "crm": {
337
+ "threshold_n": 20.0,
338
+ "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",
339
+ "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)",
340
+ "aggregation": "max over the force reads acting in the interval",
341
+ "step": "FSI exchange 1.0 ms (2 MBD substeps)",
342
+ "read_window": [
343
+ 2,
344
+ 1
345
+ ],
346
+ "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",
347
+ "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)",
348
+ "relabelled_from_contact_force": true
349
+ }
350
+ },
351
+ "categories": {
352
+ "crm": {
353
+ "ground_id": 1
354
+ }
355
+ },
356
+ "grounds": [
357
+ "rigid",
358
+ "crm"
359
+ ],
360
+ "ground_ids": {
361
+ "rigid": 0,
362
+ "crm": 1
363
+ },
364
+ "families": [
365
+ {
366
+ "name": "nominal",
367
+ "group": "nominal",
368
+ "select": true,
369
+ "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"
370
+ },
371
+ {
372
+ "name": "difficult",
373
+ "group": "difficult",
374
+ "select": true,
375
+ "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)"
376
+ },
377
+ {
378
+ "name": "probe_drop",
379
+ "group": "probe",
380
+ "select": false,
381
+ "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"
382
+ },
383
+ {
384
+ "name": "probe_landing",
385
+ "group": "probe",
386
+ "select": false,
387
+ "note": "low tilted release (0.01-0.12 m, tilt up to 20 deg), policy active, 1.5 s: single feet touch first"
388
+ }
389
+ ],
390
+ "terminal_reasons": [
391
+ "planned_end",
392
+ "fell",
393
+ "tilt",
394
+ "nonfoot_contact",
395
+ "nonfinite",
396
+ "off_bed",
397
+ "fsi_abort",
398
+ "push_cut",
399
+ "validity_cut",
400
+ "chunk"
401
+ ],
402
+ "termination": {
403
+ "min_base_height_m": 0.15,
404
+ "max_tilt_rad": 1.2217304763960306,
405
+ "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"
406
+ },
407
+ "physics_config": {
408
+ "crm": {
409
+ "simulator": "Chrono (pychrono)",
410
+ "pychrono": "unknown",
411
+ "pychrono_core_md5": "2387ec6dda45eaa5",
412
+ "backend": "chrono-crm",
413
+ "build_id": "chrono-crm-unknown:5d9b51e0:b8c272d2:1ms:mjlab-cc42687e",
414
+ "soil": {
415
+ "keys": {
416
+ "cohesion_pa": "SoilProperties.cohesion_coeff (Pa)",
417
+ "friction": "SoilProperties.mu_fric_s = mu_fric_2 (internal friction mu_s = mu_2)",
418
+ "density": "SoilProperties.density (kg/m^3)",
419
+ "young_modulus_pa": "SoilProperties.Young_modulus (Pa)"
420
+ },
421
+ "base": {
422
+ "cohesion_pa": 2000.0,
423
+ "friction": 0.8,
424
+ "density": 1700.0,
425
+ "young_modulus_pa": 500000.0
426
+ },
427
+ "evaluator_defaults": {
428
+ "cohesion_pa": 2000.0,
429
+ "friction": 0.8,
430
+ "density": 1700.0,
431
+ "young_modulus_pa": 500000.0
432
+ },
433
+ "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']"
434
+ },
435
+ "terrain": "crm",
436
+ "params": {
437
+ "terrain": "crm",
438
+ "pd_mode": "substep",
439
+ "urdf": "go2_mjlab.urdf sha256 5d9b51e03a4215c71c2ad2dd9b97d3dce448a5baf67cdb7ae8262737201746d6",
440
+ "rigid_mbd_step_s": 0.0005,
441
+ "exchange_step_s": null,
442
+ "solver_iterations": 100,
443
+ "contact": {
444
+ "friction": 0.9,
445
+ "restitution": 0.01,
446
+ "kn": 200000.0,
447
+ "gn": 60.0,
448
+ "envelope_m": 0.0025,
449
+ "margin_m": 0.0025
450
+ },
451
+ "crm": {
452
+ "spacing_m": 0.02,
453
+ "depth_m": 0.2,
454
+ "cfd_step_s": 0.0005,
455
+ "integration": "RK2",
456
+ "d0_multiplier": 1.0,
457
+ "free_surface_threshold": 0.8,
458
+ "artificial_viscosity": 2.0,
459
+ "foot_radius_m": 0.025,
460
+ "calf_fsi": true,
461
+ "calf_radius_m": 0.02,
462
+ "calf_length_m": 0.2,
463
+ "active_domain_m": 0.5,
464
+ "active_domain_delay_s": 0.1,
465
+ "bed_margin_m": 0.25,
466
+ "bed_override_m": null,
467
+ "soil": {
468
+ "density": 1700.0,
469
+ "young_modulus_pa": 500000.0,
470
+ "poisson_ratio": 0.3,
471
+ "mu_i0": 0.04,
472
+ "friction": 0.8,
473
+ "average_diam_m": 0.005,
474
+ "cohesion_pa": 2000.0
475
+ }
476
+ }
477
+ },
478
+ "robot": {
479
+ "robot": "go2_mjlab",
480
+ "rotor": {
481
+ "enabled": true,
482
+ "coupling": "relative",
483
+ "ratio": 1.0,
484
+ "shaft_inertia": 0.0001,
485
+ "compensate": true,
486
+ "armature_scale": 1.0
487
+ },
488
+ "armature": {
489
+ "FL_hip_joint": 0.01,
490
+ "FL_thigh_joint": 0.01,
491
+ "FL_calf_joint": 0.02,
492
+ "FR_hip_joint": 0.01,
493
+ "FR_thigh_joint": 0.01,
494
+ "FR_calf_joint": 0.02,
495
+ "RL_hip_joint": 0.01,
496
+ "RL_thigh_joint": 0.01,
497
+ "RL_calf_joint": 0.02,
498
+ "RR_hip_joint": 0.01,
499
+ "RR_thigh_joint": 0.01,
500
+ "RR_calf_joint": 0.02
501
+ },
502
+ "legacy_calf_fsi": true,
503
+ "joint_limits": {
504
+ "mode": "mujoco",
505
+ "params_sha256": "e8de60cb6fe591c8"
506
+ }
507
+ },
508
+ "robot_mass_kg": 15.206408,
509
+ "mbd_step_s": 0.0005,
510
+ "sample_step_s": 0.001,
511
+ "fsi_exchange_step_s": 0.001,
512
+ "rigid_sample_note": null,
513
+ "surface_z_in_sim": 0.2,
514
+ "deploy": {
515
+ "config_sha256": "5ea1984807ba2211c01f810846d4d61f88875f75c009b402f9a1dc67e1427ce2",
516
+ "model_sha256": "c58a3494b22604b5aa67640ec6ebabe0c6c277d85b072dc9e76c3191e2dfdd45",
517
+ "ll_dt": 0.005,
518
+ "policy_dt": 0.019999999552965164,
519
+ "tau_max": [
520
+ 23.5,
521
+ 23.5,
522
+ 45.0,
523
+ 23.5,
524
+ 23.5,
525
+ 45.0,
526
+ 23.5,
527
+ 23.5,
528
+ 45.0,
529
+ 23.5,
530
+ 23.5,
531
+ 45.0
532
+ ],
533
+ "torque_clip": false,
534
+ "command_clip": "none",
535
+ "fixstand_kp": [
536
+ 60.0,
537
+ 80.0,
538
+ 80.0,
539
+ 60.0,
540
+ 80.0,
541
+ 80.0,
542
+ 60.0,
543
+ 80.0,
544
+ 80.0,
545
+ 60.0,
546
+ 80.0,
547
+ 80.0
548
+ ],
549
+ "fixstand_kd": [
550
+ 5.0,
551
+ 4.0,
552
+ 4.0,
553
+ 5.0,
554
+ 4.0,
555
+ 4.0,
556
+ 5.0,
557
+ 4.0,
558
+ 4.0,
559
+ 5.0,
560
+ 4.0,
561
+ 4.0
562
+ ]
563
+ },
564
+ "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)",
565
+ "injection": "plan OU target noise added to the HighController target before torqueClip (motor order)",
566
+ "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)",
567
+ "force_read_window": {
568
+ "lo": 2,
569
+ "hi": 1,
570
+ "rule": "steps a+1..b <- reads a+1-lo..b-hi"
571
+ },
572
+ "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)",
573
+ "actuator": "PD law at every MBD step, clamped at the effort limit (23.5 / 45 N m) per step; no deploy torqueClip",
574
+ "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)",
575
+ "terrain_relief": {
576
+ "schema": "go2nrd_crm_relief_v1",
577
+ "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",
578
+ "nominal_surface": "z = depth_m (flat-bed top); state z and diag foot z stay relative to it",
579
+ "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",
580
+ "per_episode": "RawEpisode.meta['terrain_relief'] (spec, seed, dk sha256, layer stats); diag relief_dk, surface_*"
581
+ },
582
+ "swing_lift": {
583
+ "schema": "go2nrd_swing_lift_v1",
584
+ "module": "go2nrd.collect.chrono.swing_lift",
585
+ "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",
586
+ "leg_phase_offset": [
587
+ 0.5,
588
+ 0.0,
589
+ 0.0,
590
+ 0.5
591
+ ],
592
+ "period_s": 0.6,
593
+ "command_threshold": 0.1,
594
+ "raw_per_record": "swing_lift [L, 12] policy order (rad)",
595
+ "diag": [
596
+ "swing_lift_offset",
597
+ "swing_lift_weight",
598
+ "swing_lift_env",
599
+ "swing_lift_k",
600
+ "injection_applied"
601
+ ]
602
+ }
603
+ }
604
+ },
605
+ "extras": {
606
+ "ground": "[N] int8 ground id of each episode (system.json ground_ids); optional (version B of the NRD)",
607
+ "episode_id": "[N] int64 = parent_episode_id * 10 + piece",
608
+ "parent_episode_id": "[N] int64 planned episode id; piece [N] int8 its push piece; record_offset [N] int32 first parent record of the piece",
609
+ "group_id": "[N] int64 = the parent's planned group (pieces share it and the split)",
610
+ "obs": "[N, T, 47] policy observation at policy records (even records), NaN elsewhere",
611
+ "raw_action": "[N, T, 12] raw policy output at policy records, NaN elsewhere",
612
+ "command": "[N, T, 3] (vx, vy, wz) command of the control period containing the record",
613
+ "phase_k": "[N, T] int32 the policy's phase counter k",
614
+ "push_force": "[N, T, 3] world push force in [t, t + 10 ms) (excised in kept data: zero)",
615
+ "nonfoot_contact": "[N, T] uint8 non-foot ground contact in [t, t + 10 ms)",
616
+ "contact_force": "[N, T-1, 4] max pair normal force over the interval's steps (N)",
617
+ "foot_force, calf_force": "[N, T-1, 4] optional CRM diagnostics (N)",
618
+ "validity_check": "[N] int8 0 = none, else 1 + index of the export validity check that cut the episode",
619
+ "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)",
620
+ "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",
621
+ "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",
622
+ "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)"
623
+ },
624
+ "core_free_flag": {
625
+ "array": "crm_free",
626
+ "grounds": [
627
+ "crm"
628
+ ],
629
+ "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"
630
+ },
631
+ "soil_columns": [
632
+ "cohesion_pa",
633
+ "friction",
634
+ "density",
635
+ "young_modulus_pa"
636
+ ],
637
+ "ground_feature_names": [
638
+ "is_crm",
639
+ "cohesion_code",
640
+ "friction_code"
641
+ ],
642
+ "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",
643
+ "evaluation": {
644
+ "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.",
645
+ "free": {},
646
+ "windows": {
647
+ "horizons_s": [
648
+ 0.02,
649
+ 0.2,
650
+ 0.5,
651
+ 1.0
652
+ ],
653
+ "first_start_s": 0.1,
654
+ "start_every_s": 0.5,
655
+ "end_window": true
656
+ },
657
+ "long_windows": {
658
+ "horizons_s": [
659
+ 2.0
660
+ ],
661
+ "first_start_s": 0.1,
662
+ "start_every_s": 1.0
663
+ },
664
+ "event_windows": {
665
+ "horizons_s": [
666
+ 0.2,
667
+ 0.5,
668
+ 1.0
669
+ ],
670
+ "lead_s": 0.1,
671
+ "min_gap_s": 0.1,
672
+ "events": [
673
+ "onset"
674
+ ]
675
+ },
676
+ "flags": {
677
+ "fall": {
678
+ "any": [
679
+ {
680
+ "body": "robot",
681
+ "channel": "z",
682
+ "below": 0.15
683
+ },
684
+ {
685
+ "body": "robot",
686
+ "tilt_above_rad": 0.7853981633974483
687
+ }
688
+ ]
689
+ }
690
+ },
691
+ "contact_tolerance_steps": 2,
692
+ "batch": 2048,
693
+ "score": [
694
+ {
695
+ "stat": "windows/1.0/robot/pos_m/p95",
696
+ "scale": 0.05,
697
+ "weight": 1.0
698
+ },
699
+ {
700
+ "stat": "windows/1.0/robot/angle_rad/p95",
701
+ "scale": 0.08726646259971647,
702
+ "weight": 1.0
703
+ },
704
+ {
705
+ "stat": "windows/1.0/robot/joint_rms_rad/p95",
706
+ "scale": 0.1,
707
+ "weight": 1.0
708
+ },
709
+ {
710
+ "stat": "windows/contacts/all/event_error_rate",
711
+ "scale": 0.1,
712
+ "weight": 1.0
713
+ },
714
+ {
715
+ "stat": "windows/contacts/all/timing_s/p95",
716
+ "scale": 0.02,
717
+ "weight": 1.0
718
+ },
719
+ {
720
+ "stat": "windows/flags/fall/disagreement",
721
+ "scale": 0.01,
722
+ "weight": 1.0
723
+ },
724
+ {
725
+ "stat": "nonfinite_fraction",
726
+ "scale": 0.01,
727
+ "weight": 1.0
728
+ }
729
+ ]
730
+ },
731
+ "campaigns": [
732
+ "lateral_stuck_20261108_crm_v2"
733
+ ]
734
+ }
go2_sand_finetune/data/lateral_crm_v2_cuda/unified_data.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1079976f3f407596714bdcf9cc7616bd162280e1e6358cc9d21e03a6b9fa7a2
3
+ size 54009166