rli14 commited on
Commit
59cdc3c
·
verified ·
1 Parent(s): c85c20f

rsm_rise code snapshot (HF_PUSH_ALL)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. README.md +34 -0
  3. THIRD_PARTY.md +18 -0
  4. frozen/rsm_libero_freeze_20261002/CLAUDE.md +291 -0
  5. frozen/rsm_libero_freeze_20261002/FINDINGS.md +344 -0
  6. frozen/rsm_libero_freeze_20261002/FREEZE_COMMIT +1 -0
  7. frozen/rsm_libero_freeze_20261002/README.md +737 -0
  8. frozen/rsm_libero_freeze_20261002/audit_logged_goal.py +93 -0
  9. frozen/rsm_libero_freeze_20261002/audit_logged_goal.sbatch +17 -0
  10. frozen/rsm_libero_freeze_20261002/autoresearch_driver.py +78 -0
  11. frozen/rsm_libero_freeze_20261002/awr.py +275 -0
  12. frozen/rsm_libero_freeze_20261002/bc_arm.py +153 -0
  13. frozen/rsm_libero_freeze_20261002/calib_dwm.py +106 -0
  14. frozen/rsm_libero_freeze_20261002/capture_cpu.sbatch +32 -0
  15. frozen/rsm_libero_freeze_20261002/capture_init_feats.py +88 -0
  16. frozen/rsm_libero_freeze_20261002/crn_diag.py +58 -0
  17. frozen/rsm_libero_freeze_20261002/data.py +587 -0
  18. frozen/rsm_libero_freeze_20261002/df_readout.py +228 -0
  19. frozen/rsm_libero_freeze_20261002/dinowm_readout.py +168 -0
  20. frozen/rsm_libero_freeze_20261002/dwm_model.py +562 -0
  21. frozen/rsm_libero_freeze_20261002/dwm_readout.py +314 -0
  22. frozen/rsm_libero_freeze_20261002/dwm_readout_timing.py +78 -0
  23. frozen/rsm_libero_freeze_20261002/encode_parquet.py +83 -0
  24. frozen/rsm_libero_freeze_20261002/encode_t5.py +52 -0
  25. frozen/rsm_libero_freeze_20261002/encode_t5.sbatch +16 -0
  26. frozen/rsm_libero_freeze_20261002/eval_closed_loop.py +1025 -0
  27. frozen/rsm_libero_freeze_20261002/eval_slurm.sbatch +90 -0
  28. frozen/rsm_libero_freeze_20261002/extract_clips.py +98 -0
  29. frozen/rsm_libero_freeze_20261002/extract_viz.py +90 -0
  30. frozen/rsm_libero_freeze_20261002/ibm_autoresearch.sh +53 -0
  31. frozen/rsm_libero_freeze_20261002/ibm_bias_diag.sh +16 -0
  32. frozen/rsm_libero_freeze_20261002/ibm_cell.sh +21 -0
  33. frozen/rsm_libero_freeze_20261002/ibm_crn_diag.sh +13 -0
  34. frozen/rsm_libero_freeze_20261002/ibm_eval.sh +51 -0
  35. frozen/rsm_libero_freeze_20261002/ibm_eval_depth.sh +7 -0
  36. frozen/rsm_libero_freeze_20261002/ibm_eval_matrix.sh +25 -0
  37. frozen/rsm_libero_freeze_20261002/ibm_eval_matrix_last.sh +38 -0
  38. frozen/rsm_libero_freeze_20261002/ibm_eval_ocb.sh +23 -0
  39. frozen/rsm_libero_freeze_20261002/ibm_eval_robust.sh +25 -0
  40. frozen/rsm_libero_freeze_20261002/ibm_eval_sde.sh +20 -0
  41. frozen/rsm_libero_freeze_20261002/ibm_full_wave.sh +44 -0
  42. frozen/rsm_libero_freeze_20261002/ibm_pack_onpol.sh +12 -0
  43. frozen/rsm_libero_freeze_20261002/ibm_rerender.sh +18 -0
  44. frozen/rsm_libero_freeze_20261002/ibm_resubmit_missing.sh +30 -0
  45. frozen/rsm_libero_freeze_20261002/ibm_retry_tasks.sh +16 -0
  46. frozen/rsm_libero_freeze_20261002/ibm_table.py +70 -0
  47. frozen/rsm_libero_freeze_20261002/ibm_train_onpol.sh +15 -0
  48. frozen/rsm_libero_freeze_20261002/iql.py +259 -0
  49. frozen/rsm_libero_freeze_20261002/is_ope.py +727 -0
  50. frozen/rsm_libero_freeze_20261002/label_full.sbatch +20 -0
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ frozen/rsm_libero_freeze_20261002/notes/action_contrast.pdf filter=lfs diff=lfs merge=lfs -text
37
+ frozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -text
38
+ frozen/rsm_libero_rsmpi/notes/action_contrast.pdf filter=lfs diff=lfs merge=lfs -text
39
+ frozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ tags: [robotics, offline-rl, successor-measure, rise, robomimic]
4
+ ---
5
+ # rsm_rise -- code snapshot
6
+
7
+ Code for **RSM (successor model) as the value function on top of the RISE stack** (RISE: arXiv 2510.19495):
8
+ the pipeline, training/eval launchers and the paper tables' source docs. Snapshot taken 2026-11-22.
9
+
10
+ | folder | what it is |
11
+ |---|---|
12
+ | `gen_q_rsm/` | `git archive` of github.com/williamd4112/gen_q, branch `rsm_rise_data`, commit `1c1e6d32273b541e41229609b76f0f1acfb0efe7` (`rsm_libero/` = RSM trainer + scorer, `rsm_rise/pipeline/` = RISE glue, `rsm_rise/pipeline/hf_ckpt.py` = checkpoint fetcher) |
13
+ | `frozen/rsm_libero_freeze_20261002/` | the verbatim RSM code the flagship sim tables were produced with (FREEZE_COMMIT 95842af1); set `RSM_LIBERO_DIR` to it |
14
+ | `frozen/rsm_libero_rsmpi/` | RSM policy-iteration (RSM-pi) variant |
15
+ | `frozen/rsm_libero_snap_20261030/` | later RSM snapshot (2026-10-30, source only) |
16
+ | `code_src/` | source-only copies (as run, incl. our edits) of the RISE code (`rise_code`), the RISE robomimic fork with the RSM planner mixin (`rise_robomimic`), and the IFQL / diffusion-forcing / TD-MPC2 baselines |
17
+ | `rsm_rise/scripts/` | cluster launchers, eval cells, table builders (`scripts/real` = real-robot cooking, `scripts/rsmpi` = RSM-pi) |
18
+ | `rsm_rise/docs/` | plan of record, master table, checkpoint choice, LaTeX sources of the reports (`docs/tex`) |
19
+ | `THIRD_PARTY.md` | upstream repos + commits (RISE code, robomimic fork, robosuite, mimicgen, diffusion_policy, ...) that are not vendored |
20
+
21
+ Secrets (HF / W&B tokens) are excluded and the staged tree was scanned for token patterns before upload.
22
+
23
+ ## Checkpoints
24
+ | repo | content |
25
+ |---|---|
26
+ | [rli14/rsm_rise_sim_checkpoints](https://huggingface.co/rli14/rsm_rise_sim_checkpoints) | every simulation checkpoint a paper table cell loads (RISE/IDQL/IFQL/BC actors+critics, RSM successors, hop heads, world-model baselines, cache metadata) + `rsmpi/`; `manifest.tsv` maps each file to its source path and table cell |
27
+ | [rli14/rsm_cooking_v5_checkpoints](https://huggingface.co/rli14/rsm_cooking_v5_checkpoints) | real-robot cooking checkpoints (v5 at the root; `v6/`, `v7/` later rounds) |
28
+ | `hf://buckets/rsm-bucket/rsm-shared/` | v6/v7 real-robot bulk exports (bucket) |
29
+
30
+ ```python
31
+ from huggingface_hub import hf_hub_download
32
+ p = hf_hub_download("rli14/rsm_rise_sim_checkpoints", "square_sub_20100/rsm/M/ckpt_best.pt")
33
+ ```
34
+ or `hf download rli14/rsm_rise_sim_checkpoints --include "square_sub_20100/*" --local-dir ckpts/`.
THIRD_PARTY.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-party code used by rsm_rise (not vendored here)
2
+
3
+ | dir under rsm_rise/code | upstream remote | commit | note |
4
+ |---|---|---|---|
5
+ | df_rise | (vendored source-only copy in code_src/df_rise) | - | as run, incl. local edits |
6
+ | diffusion_forcing | https://github.com/buoyancy99/diffusion-forcing.git | 475e0bcab87545e48b24b39fb46a81fe59d80594 | 2025-02-22 13:48:31 -0500 |
7
+ | diffusion_forcing_paper | (not a git checkout) | - | |
8
+ | diffusion_policy | https://github.com/UWRobotLearning/diffusion_policy.git | 078ce1ee2064cde28074db239ff0af2f9254069b | 2025-01-27 04:42:52 -0800 |
9
+ | gen_q_rsm_snap_20261030 | (not a git checkout) | - | |
10
+ | ifql | (vendored source-only copy in code_src/ifql) | - | as run, incl. local edits |
11
+ | mimicgen_environments | https://github.com/UWRobotLearning/mimicgen_environments.git | 14d8eb5709b38c6b75ecf140c3608ff984196832 | 2025-02-17 16:06:34 -0800 |
12
+ | ogbench_beta | (not a git checkout) | - | |
13
+ | rise_code | (vendored source-only copy in code_src/rise_code) | - | as run, incl. local edits |
14
+ | rise_robomimic | (vendored source-only copy in code_src/rise_robomimic) | - | as run, incl. local edits |
15
+ | robosuite | https://github.com/UWRobotLearning/robosuite.git | 9ea2411569d66776bd476d3c4e5944a6a8482ae1 | 2024-12-02 02:46:43 -0800 |
16
+ | rsm_libero_rpred | (not a git checkout) | - | |
17
+ | tdmpc2 | https://github.com/nicklashansen/tdmpc2.git | e9f59321933cbc8e11a002b842adc7d4ffae8ff1 | 2026-07-13 15:26:47 -0700 |
18
+ | tdmpc2_rise | (vendored source-only copy in code_src/tdmpc2_rise) | - | as run, incl. local edits |
frozen/rsm_libero_freeze_20261002/CLAUDE.md ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # rsm_libero — LIBERO-10 RSM critic evaluation
2
+
3
+ ## INVALIDATION (2026-09-13): every result before this date is void
4
+
5
+ Every run directory under `rsm_libero_runs/mit/` suffixed `_wrong_eval_env` (105 of them) and
6
+ every eval JSON under `rsm_libero_runs/eval/wrong_eval_env/` (143) was produced with the rollout
7
+ latents and the evaluator in DIFFERENT feature spaces. Do not cite, compare against, or resume
8
+ from them. The results tables further down in this file are retained only as a record of what
9
+ was believed; they are superseded. Valid runs are `*_r` and later, trained on
10
+ `rsm_libero_cache/full_demo_r256` (or its full-corpus successor) and evaluated at `--cam-res 256`.
11
+
12
+ ## PINNED INPUT FORMAT (offline data == online environment, or the run is inadmissible)
13
+
14
+ | item | value | why |
15
+ |---|---|---|
16
+ | camera render | **256x256**, both cameras (`--cam-res 256`, the default) | RLinf `config/env/libero_10.yaml`; the collector rendered at 256 |
17
+ | orientation | raw render `[::-1, ::-1]` -> serving orientation | parquet images are stored already upright; demo hdf5 stores raw |
18
+ | resize | 256 -> 224 bilinear, **round and clamp to uint8** | `to224`: float input alone moves the latent 3 sigma |
19
+ | encoder | the latent-cache BUILDER's PaliGemma, base||wrist 2048+2048 | same module the evaluator imports |
20
+ | proprio | eef_pos(3) ++ ee_ori **axis-angle**(3) ++ gripper_qpos(2) | Euler was the #243 bug |
21
+ | demos | `libero10_demo_ogpo_cache_r256` (re-rendered from hdf5 `states` at 256) | the 128 demo cache is off-manifold under this evaluator |
22
+ | normalisation | `feat_stats*.npz` of the cache being trained on | eval reads `norm_pool` from the checkpoint |
23
+
24
+ **Naming and marker convention (2026-09-13).** Every dataset, cache and checkpoint carries the render
25
+ resolution it was produced at, twice: in the NAME (`_cam128`, `_cam256`; a mix is `_MIXED_..._INVALID`)
26
+ and in a machine-readable marker (`RENDER.json` / `PACK.json` `cam_res`; checkpoints store `cam_res`).
27
+ `eval_closed_loop.py` REFUSES a policy, critic or Q whose declared resolution differs from
28
+ `--cam-res`, and refuses an undeclared one (`--allow-cam-mismatch 1` overrides; never for a reported
29
+ number). `pack.py --cam-res` is how a cache gets its declaration.
30
+
31
+ | asset | name | cam_res |
32
+ |---|---|---|
33
+ | rollout latents | `pi05_lib10_ogpo_fl15_v1` (+RENDER.json) | 256 |
34
+ | demos, LIBERO hdf5 render | `libero10_demo_ogpo_cache_cam128` | 128 -- invalid under the 256 evaluator |
35
+ | demos, re-rendered | `libero10_demo_ogpo_cache_cam256` | 256 |
36
+ | subset cache | `rsm_libero_cache/full_demo_cam256` (`full_demo_r256` is a symlink for running jobs) | 256 |
37
+ | full cache | `rsm_libero_cache/full_r256` | 256 |
38
+ | old subset cache | `full_demo_MIXED_128demos_256rollouts_INVALID` | mixed |
39
+
40
+ Rule, extended from reward labels to features: **a latent the eval environment cannot produce is
41
+ inadmissible for offline training.** Verify with `rerender_rollouts.py --validate-rollouts` /
42
+ `--validate-demos` (re-render from logged state in the evaluator's env; L2 to the cached latent
43
+ must sit at the within-cloud scale, ~4-12, not 60+).
44
+
45
+ ## RULE: offline data must reproduce its reward labels in the EVAL environment
46
+
47
+ **A trajectory is admissible for offline training only if replaying its logged actions
48
+ in the environment we evaluate in reproduces its reward labels. If it does not
49
+ reproduce, drop the trajectory.**
50
+
51
+ This is not a data-cleaning nicety, it is a correctness condition. An offline learner
52
+ fits $(s,a,r,s')$ tuples and is then scored in the simulator. If those tuples cannot be
53
+ reproduced there, they describe different dynamics than the ones the policy is graded
54
+ against, and the learner is being fit to an environment that does not exist. That is the
55
+ standard way offline RL silently fails.
56
+
57
+ Three consequences that are easy to get wrong:
58
+
59
+ 1. **"The label was honest" is NOT the admissibility test.** Evaluating the goal
60
+ predicate at an episode's own logged final state answers whether the recorder told
61
+ the truth about the state it reached. Useful diagnostics, wrong question. A truthful
62
+ label on a trajectory that will not reproduce here is still inadmissible.
63
+ 2. **The replay must run in the SAME configuration as eval** — same venv, same package
64
+ versions, same renderer and device. A trajectory that reproduces on CPU/osmesa but
65
+ not on the GPU/EGL path we actually evaluate on is not admissible, because the eval
66
+ path is the one that defines the environment.
67
+ 3. **If the eval environment changes, admissibility must be recomputed.** Moving eval to
68
+ a different cluster, venv or `bddl` version invalidates the existing mask. See the
69
+ pinned versions below: IBM's `bddl` is 1.0.1 against MIT's 3.6.0, and `bddl` defines
70
+ the goal predicates, so a mask built for MIT does not transfer.
71
+
72
+ Measured on R1 (`pi05_lib10_sde_v1`): replaying logged successes reproduces **~81%**
73
+ (per task 0.620--0.938). The remaining ~19% are inadmissible and are dropped by
74
+ `merge_verify.py --shards`, leaving ~1800 usable rollout successes. For contrast, the
75
+ diagnostic goal-predicate check passes ~87% — the gap between the two is exactly the
76
+ set of trajectories that were honestly recorded but do not reproduce, and **those are
77
+ inadmissible too**.
78
+
79
+ ## THE TWO EVALUATION PROTOCOLS — always report both
80
+
81
+ There are two initial-state distributions, they give materially different numbers,
82
+ and **which one you use decides who wins**. Never report one without saying which.
83
+
84
+ | protocol | flag | what it does | who is at home in it |
85
+ |---|---|---|---|
86
+ | **A. stock LIBERO test set** | `FRESH=0` (default) | replays `bench.get_task_init_states(tid)` — the benchmark's own fixed init states | **the demos** (they were collected from these) |
87
+ | **B. 5 cm continuous region** | `FRESH=1` | `env.reset()` only, so the task's placement initialiser samples object poses continuously | **the rollouts** (`fresh_reset=true`, "fresh 5 cm inits") |
88
+
89
+ ```bash
90
+ # A: stock init states
91
+ sbatch --export=ALL,POLICY=$P,NINIT=50,OUT=$E/x.json eval_slurm.sbatch
92
+ # B: continuous region
93
+ sbatch --export=ALL,POLICY=$P,NINIT=50,FRESH=1,OUT=$E/x_fresh.json eval_slurm.sbatch
94
+ ```
95
+
96
+ ### How an initial condition is actually defined
97
+
98
+ Per episode, indexed by task `tid` and episode `k` (both protocols):
99
+
100
+ ```python
101
+ pseed = 7_919_003 + policy_seed*500_009 + tid*1_013 + k # policy sampling RNG
102
+ torch.manual_seed(pseed); torch.cuda.manual_seed_all(pseed)
103
+ np.random.seed(seed*100_003 + tid*1_009 + k)
104
+ env.seed(seed*100_003 + tid*1_009 + k) # env RNG
105
+ env.reset() # B stops here
106
+ if not fresh:
107
+ env.set_init_state(inits[k % 50]) # A overrides the reset
108
+ ```
109
+
110
+ **Protocol A** — `env.set_init_state()` writes one of LIBERO's 50 stored full sim-state
111
+ vectors (`bench.get_task_init_states(tid)`), overwriting whatever `reset()` sampled.
112
+ Object poses are therefore a deterministic replay of a fixed, finite, curated set.
113
+ `NINIT=10` replays inits 0-9, which is why it is biased (see above); `NINIT=50` uses
114
+ each stored state exactly once.
115
+
116
+ **Protocol B** — no override, so object poses come from the task's BDDL placement
117
+ regions (`bddl_base_domain.py`: `regions[name]["ranges"]` → `UniformRandomSampler`,
118
+ uniform in x/y over the task's rectangle plus a z-rotation). Under B, `NINIT=10` is a
119
+ small unbiased sample rather than a curated subset — noisy, but not systematically easy.
120
+
121
+ **MEASURED (`probe_inits.py`, 2026-09-12): protocol B is NARROWER than protocol A.**
122
+ Mean std of the randomised sim-state DoF, over 50 states per task:
123
+
124
+ | protocol | mean std | note |
125
+ |---|---|---|
126
+ | A, stock init states | **0.0236** | wider on all 10 tasks |
127
+ | B, `env.reset()` | **0.0138** | 0.58x of A |
128
+
129
+ So `--fresh 1` is **not** an "expanded region" — it is a tighter one, and A is the more
130
+ demanding of the two. (`stock_inside_fresh_support = 0.00` is a consequence of A being
131
+ wider, not of a distribution shift.)
132
+
133
+ **Neither protocol reproduces the rollout corpus's init distribution.** The corpus was
134
+ collected with RLinf's `fresh_reset=true`, documented as "fresh 5 cm inits" — 0.05
135
+ would be wider than both A and B. Our evaluator has no equivalent. Evaluating on the
136
+ genuine 5 cm region would require explicit jitter of object free-joint xy after reset;
137
+ until that exists, the critic and the success-pool policies are under a mild init
138
+ shift under BOTH protocols.
139
+
140
+ **Protocol A CANNOT be replicated by varying `SEED`.** `set_init_state` overwrites
141
+ whatever `env.reset()` sampled, so `env.seed` has no effect; `np.random.seed` is set but
142
+ never used in the rollout loop; and the policy stream is keyed on `--policy-seed`, not
143
+ `--seed`. Re-running protocol A at a different `SEED` reproduces the identical 500
144
+ episodes. **A is hard-capped at 500 distinct episodes** (50 stored inits x 10 tasks).
145
+ Its only legitimate replication is `PSEED=1,2,...`, which resamples the policy on those
146
+ same inits. Protocol B draws fresh placements per episode, so `SEED` gives genuine new
147
+ episodes and n scales without limit — it is the only protocol that supports replication.
148
+
149
+ **Both protocols are PAIRED across arms.** The env seed depends only on
150
+ `(seed, tid, k)` and the policy seed only on `(policy_seed, tid, k)` — neither depends
151
+ on which policy or critic is being evaluated. So with `SEED=0` every arm sees the
152
+ identical sequence of initial conditions and the identical policy-sampling RNG stream.
153
+ Differences between arms are attributable to the arm, and variance on a *difference*
154
+ is lower than the independent-sample formula implies. Never vary `SEED` between arms
155
+ you intend to compare.
156
+
157
+ ### Why this is not a detail
158
+
159
+ Provenance of every component, verified 2026-09-12 from the corpus `DATASET.md` files:
160
+
161
+ | component | source | init distribution |
162
+ |---|---|---|
163
+ | 500 demos → BC-on-demos | `libero10_demo_ogpo_cache_srv` (official LIBERO-10 human demos) | **stock init states** |
164
+ | 4500 rollouts → BC-on-successes, **93% of critic training** | `pi05_lib10_ogpo_fl15_v1` ← `pi05_lib10_sde_v1` | **fresh 5 cm**, `fresh_reset=true` |
165
+
166
+ Under protocol A we evaluate on exactly the configurations the demos were collected
167
+ from, while the rollout corpus — which trains the critic and the success-pool policies
168
+ — comes from a different, wider region. That is a structural advantage for
169
+ BC-on-demos and a distribution shift against everything else. Protocol B is the one
170
+ where the critic's training distribution matches the test distribution.
171
+
172
+ ## PINNED: simulator versions, and where eval may run
173
+
174
+ **All LIBERO evaluation and the R1 rollout collection run in the SAME MIT venv**, so
175
+ they are comparable by construction. Do not change this venv without re-deriving every
176
+ number in this file.
177
+
178
+ ```
179
+ venv continual_learning_for_manipulation/venvs/rlinf-libero-eval-venv (python 3.11.15)
180
+ mujoco 3.8.1 robosuite 1.4.1 bddl 3.6.0 libero vendored
181
+ installed 2026-08-31 (corpus R1 collected 2026-09-05 with this same venv, unchanged since)
182
+ collection driver: logs/09052026_pi05_lib10_collect.sh -> PYE=.../rlinf-libero-eval-venv/bin/python
183
+ ```
184
+
185
+ **IBM cannot run LIBERO eval, and its stack is not equivalent:**
186
+
187
+ | | MIT (eval + collection) | IBM `/proj/dmfexp/zwhong/venvs/lerobot_env` |
188
+ |---|---|---|
189
+ | mujoco | 3.8.1 | 3.8.1 |
190
+ | robosuite | **1.4.1** | **1.4.0** |
191
+ | bddl | **3.6.0** | **1.0.1** |
192
+ | libero | vendored | **absent** |
193
+
194
+ `bddl` differs by a major version and **bddl defines the goal predicates**, so a
195
+ "success" computed on IBM would not be the same event. IBM is **training-only**; every
196
+ closed-loop number must come from MIT.
197
+
198
+ **The replay divergence is NOT a version mismatch.** Collection and replay share the
199
+ venv and the versions, installed before collection and untouched since. Re-executing
200
+ logged actions reproduces only ~81% of successes because contact-rich manipulation is
201
+ chaotic and the two runs differ in floating-point detail (collection on GPU nodes under
202
+ EGL, replay on CPU under osmesa). This is why label correctness must be measured by
203
+ evaluating the goal predicate at the LOGGED FINAL state (~87% correct) rather than by
204
+ replay (~81%) -- replay conflates label error with non-reproducibility and overstates
205
+ it by roughly 3x on the worst task.
206
+
207
+ ## Other measurement traps in this directory
208
+
209
+ **`NINIT=10` is a fixed easier subset, not a sample.** Init states are selected as
210
+ `inits[k % 50]`, so `n_init=10` always replays inits 0–9. Measured on one policy:
211
+ **0.630 at n=100 vs 0.532 at n=500**, a +0.098 mean per-task gap on 8 of 10 tasks.
212
+ It is deterministic and does not shrink with repetition. Control: a Q-filter gate
213
+ firing on 0.5% of decisions (≈ BC) returned exactly 0.630 at n=100.
214
+ **Use `NINIT=50` for any number you intend to quote.** At n=100 the standard error on
215
+ a *difference* is ±0.069, so sub-14-point effects are unresolvable.
216
+
217
+ **Success labels are ~16% optimistic.** A replay audit of the source corpus found 5 of
218
+ 32 logged successes did not actually succeed. BC-on-successes clones a pool where
219
+ ~1 in 6 "successes" is a failure, and the critic's `γ^steps-to-success` reward gives
220
+ those episodes a full progress curve toward a success that never happened.
221
+
222
+ **Held-out action win rate does not predict closed-loop.** `ckpt_best.pt` selects on
223
+ it, but it went 0.478 → 0.784 → 0.896 across critics while closed-loop went
224
+ 0.496 → 0.490. A collapse to 0.363 cost only 0.046. Treat it as a broken-critic alarm,
225
+ not a selection criterion.
226
+
227
+ **A silent 0% means a config mismatch**, not a bad policy — a chunk-25 flow policy run
228
+ through the chunk-10 concat harness scores exactly 0/350. Same signature as the
229
+ original Euler-vs-axis-angle proprio bug.
230
+
231
+ ## Results, n=500, both protocols
232
+
233
+ Protocol B column is filled as arms land; `--` = not yet run.
234
+
235
+ | arm | uses demo labels? | A: stock | B: 5 cm continuous |
236
+ |---|---|---|---|
237
+ | BC-on-demos | yes (pool) | **0.532** | **0.520** |
238
+ | BC-on-successes | no | 0.438 | -- |
239
+ | RSM ranking, successes proposal, N=32 | **no** | 0.416 | -- |
240
+ | IQL extraction (200k steps) | yes (pool) | 0.416 | -- |
241
+ | RSM ranking, demos proposal (best: `c1Mb`, β 0.98/0.99) | yes | **0.540** | -- |
242
+ | RSM ranking, successes proposal | **no** | -- | -- |
243
+ | AWR extraction on success pool | **no** | -- | -- |
244
+
245
+ **Measured 2026-09-12: BC-on-demos scores 0.532 (A) vs 0.520 (B) — it does NOT
246
+ memorise the stock init states.** Protocol A is not inflating the baseline; the bar is
247
+ real. The remaining reason to run B is the reverse concern: the critic and the
248
+ success-pool policies were trained on the continuous-region corpus, so protocol A puts
249
+ *them* under mild shift.
250
+
251
+ Scoring rule (PI): using the demo *label* is a privilege that only counts if it beats
252
+ BC-on-demos. Using demo *data* without the label is unprivileged; beating
253
+ BC-on-successes there is already signal, and beating BC-on-demos is the strong claim.
254
+
255
+ ### Critic ablations (protocol A, n=500, demos proposal)
256
+
257
+ | knob | result |
258
+ |---|---|
259
+ | **trained β band** 0.85–0.97 / **0.93–0.995** / 0.96–0.999 | 0.490 / **0.540** / 0.502 — inverted-U, optimum found |
260
+ | read-out β 0.95 / 0.98 / 0.99 / 0.995 | 0.524 / 0.540 / 0.540 / 0.500 — plateau 0.98–0.99 |
261
+ | critic steps 12k → 110k (same band) | 0.496 → 0.490 — **no effect** |
262
+ | best-of-N 8 → 32 | flat to harmful |
263
+ | confidence gate (6 thresholds, 0.5%–60% fire) | 0.488–0.532 — no regime beats BC |
264
+ | candidate noise (SDE 0.3) | 0.510 → 0.290 — strongly harmful |
265
+ | demo-chunk retrieval (+4 / +8 / retrieval-only) | 0.516 / 0.392 / 0.352 — **strongly harmful** |
266
+ | action chunk 10 → 16 / 24 / 32 | 0.630 → 0.49 / 0.29 / 0.25 (n=100) — strongly harmful |
267
+ | AWR advantage into the actor (demos pool) | 0.520 → 0.350 vs its own `w≡1` control — strongly harmful |
268
+
269
+ **The critic cannot rank off-proposal candidates.** Noise, N=32 and retrieval all fail,
270
+ and retrieval fails *in proportion to how often the retrieved chunk is used*. Its
271
+ ordering is calibrated only on the proposal's own distribution; outside it the ranking
272
+ is actively misleading, not merely uninformative. Corollary: AWR on a pool of uniformly
273
+ expert demos can only damage it — run advantage weighting on the **success** pool,
274
+ where quality actually varies.
275
+
276
+ ## Paths
277
+
278
+ ```
279
+ code /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero
280
+ cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo # 5000 eps = 500 demo + 4500 rollout
281
+ runs /data/pulkitag/users/rli14/rsm_libero_runs/mit
282
+ evals /data/pulkitag/users/rli14/rsm_libero_runs/eval
283
+ best critic runs/mit/critic_1M_b995/ckpt_best.pt # band 0.93-0.995, step 110k
284
+ BC-demos runs/mit/A_nd/policy_r1.pt # 0.532 (A, n=500)
285
+ BC-successes runs/mit/B_nd/policy_r1.pt # 0.438 (A, n=500)
286
+ ```
287
+
288
+ Compute: MIT slurm, `--qos=vision-pulkitag-free-cycles`. Never `vision-pulkitag-main`.
289
+ `lab-free`/`csail-shared-h200` gets root-cancelled within seconds — use
290
+ `vision-pulkitag-l40s,vision-pulkitag-a6000`. Training is resumable (`--resume 1`,
291
+ saves optimiser state); chain with `--dependency=afterany`.
frozen/rsm_libero_freeze_20261002/FINDINGS.md ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RSM on the LIBERO-10 pi0.5 rollout corpus: findings
2
+
3
+ Branch `rsm-libero10-ope`. All closed-loop numbers: 10 tasks x 10 initial states
4
+ (n=100), 520-step cap, action chunk 10 with 10 executed, seed 0, measured by
5
+ `eval_closed_loop.py` after the fix described in section 2.
6
+
7
+ ---
8
+
9
+ ## 1. Headline
10
+
11
+ Behaviour cloning on the 500 demonstrations is the best policy in this lane, and
12
+ no value-guided extraction beats it.
13
+
14
+ | arm | succ/n | SR | thr succ | thr all |
15
+ |---|---|---|---|---|
16
+ | **BC on demonstrations** | **63/100** | **0.630** | 1.132 | 0.874 |
17
+ | lane reference `bcdemos_h1024d4`, our harness | 53/100 | 0.530 | 0.946 | 0.691 |
18
+ | RSM Q-filter, 16 candidates | 51/100 | 0.510 | 0.951 | 0.668 |
19
+ | IQL + AWR (demo pool) | 50/100 | 0.500 | 0.963 | 0.658 |
20
+ | IQL + AWR (success pool) | 49/100 | 0.490 | 0.839 | 0.615 |
21
+ | BC on successful rollouts | 48/100 | 0.480 | 0.807 | 0.596 |
22
+ | PARL + RSM value (collapsed proposal) | 44/100 | 0.440 | - | - |
23
+ | RSM + AWR (demo pool) | 43/100 | 0.430 | 0.758 | 0.528 |
24
+ | RSM + AWR (success pool) | 41/100 | 0.410 | 0.802 | 0.513 |
25
+
26
+ Our BC also clears the published 0.584 reference: that checkpoint scores 0.530
27
+ through this harness, and ours scores 0.630 under the same protocol.
28
+
29
+ Both critic arms start from the *same* 0.630 clone and move it **down**. The
30
+ advantage signal is harmful, not merely uninformative.
31
+
32
+ ---
33
+
34
+ ## 2. The bug that invalidated everything before it
35
+
36
+ For most of this work every arm scored **0%**. The cause was in our evaluator, not
37
+ in any policy: it converted the end-effector quaternion to **Euler angles**, while
38
+ the latent cache stores robosuite **axis-angle**. Three of the eight
39
+ proprioception dimensions were a different physical quantity at every timestep of
40
+ every episode.
41
+
42
+ Proof, same machine and same weights, on the lane's own 0.584 policy:
43
+
44
+ | evaluator | task 5 |
45
+ |---|---|
46
+ | lane's `09032026_latent_head_eval.py` (axis-angle) | 5/5 |
47
+ | ours before the fix (Euler) | 0/5 |
48
+ | ours after the fix | 5/5 |
49
+
50
+ Why every existing check missed it:
51
+
52
+ * The visual latent is 4096 of 4104 input dimensions, so the three corrupted ones
53
+ never moved a **cosine similarity**. Our encoder reproduces the cache at
54
+ cos 0.9999 offline and 0.9903 from live frames; both stayed green throughout.
55
+ * The **offline fit** is computed on cached proprio, which is correct, so held-out
56
+ sampled action MSE looked healthy at 0.049.
57
+ * A **bit-exact comparison of the first action chunk** passed, because it called
58
+ the same helper on both sides.
59
+
60
+ Only an end-to-end control with a known-good policy exposes it. That control did
61
+ not exist in this lane before now; `eval_closed_loop.py --lane-norm` runs it.
62
+
63
+ A second, smaller deviation in the same file: `to224` returned the raw float32
64
+ interpolation where the cache builder rounds to uint8, shifting the latent by up
65
+ to 0.31 against a per-dim std of 0.107. Fixed, though not the cause of the 0%.
66
+
67
+ **Anything measured through this evaluator before commit `b64ebddf` says nothing
68
+ about the policy it was measuring.**
69
+
70
+ ---
71
+
72
+ ## 3. What the main-branch recipe gave us, and what it did not
73
+
74
+ Adopted from `ogbench_unified_rsm/RECIPE.md` and the lane's BC:
75
+
76
+ | item | effect here |
77
+ |---|---|
78
+ | flow-matching occupancy on residuals, per-dim RMS normalised | works; CFM val loss 0.17-0.30 |
79
+ | EMA target encoder, variance floor | no collapse observed (latent std min 0.10-0.41) |
80
+ | Fourier beta conditioning, FiLM in the successor | retained |
81
+ | beta band + query beta | see section 5: the band is not the lever |
82
+ | action-contrastive term | does not fix the action gap at any weight |
83
+ | concatenation flow head for the policy (their BC head) | matches their fit exactly |
84
+ | select on ODE-sampled MSE, not the CFM loss | correct, but see section 6 |
85
+ | SWA at deploy, two-tower `q_readout=lik` | **not implemented** |
86
+
87
+ Two things we added that mattered more than any recipe item:
88
+
89
+ 1. **The policy must not read the critic's latent.** That encoder is trained to
90
+ predict reward and discards what an action head needs. On the 264-d latent a
91
+ flow policy beat a predict-the-mean baseline by 14% in action MSE with a biased
92
+ gripper channel. Reading the full observation is what took arms off the floor.
93
+ 2. **Policy input scaling**, section 4.
94
+
95
+ ---
96
+
97
+ ## 4. Normalisation is worth more than any algorithm here
98
+
99
+ | policy input | SR |
100
+ |---|---|
101
+ | centred with DEMONSTRATION statistics | **0.630** |
102
+ | centred with rollout-dominated statistics | 0.430 |
103
+ | per-dim z-scored | 0.010 |
104
+
105
+ Centring matters because the mean feature vector has norm 51.1 against a
106
+ per-frame deviation of 9.0, so 85% of the raw magnitude is a constant. *Which*
107
+ frames the statistics come from matters because the rollout corpus is a different
108
+ distribution (pi0.5 with SDE noise 0.5, about half failures). Whitening is
109
+ catastrophic because per-dim std spans 0.048 to 3.675, so it shrinks the few
110
+ informative directions up to 34x relative to the median.
111
+
112
+ Note the sign flip against intuition: whitening *improved* the critic's action gap
113
+ (-0.086 to a +0.103 peak) while destroying the policy. The critic and the policy
114
+ want different input geometry, which is why they are scaled separately.
115
+
116
+ ---
117
+
118
+ ## 5. The critic ranks states well and actions barely at all
119
+
120
+ Held-out within-task action win rate versus reward AUC, across every intervention:
121
+
122
+ | critic | action win | reward AUC |
123
+ |---|---|---|
124
+ | chunk 10, w_actcon 0.5 (deployed) | 0.568 | 0.96 |
125
+ | w_actcon 1.0, d_z 512 | 0.532 | 0.96 |
126
+ | w_actcon 2.0 | 0.533 | 0.96 |
127
+ | inverse dynamics 1.0 | 0.445 | 0.96 |
128
+ | inverse dynamics 5.0 | 0.534 | 0.96 |
129
+ | chunk 10, hop 0.97 | 0.558 | 0.96 |
130
+ | chunk 10, hop 0.99 | 0.551 | 0.96 |
131
+ | chunk 30, hop 0.967 | 0.597 | 0.96 |
132
+ | chunk 100, hop 0.99 | **0.613** | 0.95 |
133
+
134
+ All peak between step 1000 and 2000 and then decay below chance. The state value
135
+ is excellent throughout; only the action channel is missing.
136
+
137
+ **The lever is the action window, not the hop.** Holding chunk at 10 and sweeping
138
+ the hop is flat (0.568 / 0.558 / 0.551). Widening the window to 100 frames is the
139
+ only thing that moves it. A 10-frame chunk does not determine enough about the
140
+ outcome on these tasks.
141
+
142
+ This is consistent with the lane's own earlier measurement: over 5 frames the
143
+ executed action correlates with the **proprio** delta at |r| up to 0.98 but with
144
+ the **visual-latent** delta at only 0.49 (mean 0.10). A mean-pooled PaliGemma
145
+ embedding barely resolves what a short chunk does.
146
+
147
+ And the trade is strictly unfavourable, because the policy moves the other way:
148
+
149
+ | chunk | BC on demos | RSM extraction | critic win |
150
+ |---|---|---|---|
151
+ | 10 | **0.630** | 0.430 | 0.568 |
152
+ | 30 | 0.440 | 0.160 | 0.597 |
153
+ | 100 | 0.080 | 0.020 | 0.613 |
154
+
155
+ ---
156
+
157
+ ## 6. The experiment that settles it: PARL with proposal diversity
158
+
159
+ PARL ranks N=32 proposal samples by Q, keeps the argmax, and distills. Its own
160
+ precondition is that the proposal must be diverse, because ranking N copies of one
161
+ action cannot improve anything. Measured action std against the data's 0.421:
162
+
163
+ | proposal | action std | ratio |
164
+ |---|---|---|
165
+ | BC on demos, 120k steps, best-MSE checkpoint | 0.029 | 0.070 |
166
+ | BC on demos, 20k steps | 0.053 | 0.126 |
167
+ | the same, sampling temperature 1.5 | 0.103 | 0.244 |
168
+ | the same, sampling temperature 2.5 | 0.222 | 0.527 |
169
+
170
+ **Selecting a checkpoint by best held-out sampled MSE picks the most
171
+ mean-collapsed policy.** Our earlier Q-filter was therefore ranking 32 near-copies
172
+ of one action, which is why it returned 0.510 instead of anything informative.
173
+ This is a trap for anyone reusing `train_bc`'s selection for a proposal.
174
+
175
+ Result:
176
+
177
+ | proposal diversity | PARL SR |
178
+ |---|---|
179
+ | 0.070 | 0.350 |
180
+ | 0.126 | 0.440 |
181
+ | 0.244 | 0.230 |
182
+ | 0.527 | **0.000** |
183
+
184
+ and dropping the variance penalty, so selection follows the raw value instead of
185
+ hugging the mode, makes it worse again:
186
+
187
+ | selection rule | T=1.5 | T=2.5 |
188
+ |---|---|---|
189
+ | Q minus 2 particle std | 0.230 | 0.000 |
190
+ | pure expected success | 0.130 | 0.010 |
191
+
192
+ Critic, N, distillation and evaluator are fixed across every row; the only
193
+ variable is how much freedom the value has to choose. A value carrying signal gets
194
+ *better* with a wider candidate set. This one destroys the policy.
195
+
196
+ **Conclusion: Q responds to the action, but the direction of its response is
197
+ uncorrelated with action quality.** Measured directly with
198
+ `probe_perturb.py` on demonstration frames, where the logged chunk is by
199
+ construction the good action:
200
+
201
+ | perturbation noise | mean Q | expert wins |
202
+ |---|---|---|
203
+ | 0 (expert chunk) | 48.749 | - |
204
+ | 0.05 | 48.800 | 0.489 |
205
+ | 0.10 | 48.674 | 0.508 |
206
+ | 0.20 | 48.769 | 0.508 |
207
+ | 0.40 | 48.962 | 0.490 |
208
+ | 0.80 | 49.243 | 0.483 |
209
+
210
+ The data's own action std is 0.421, so noise 0.80 destroys the action completely,
211
+ and mean Q moves by 1%, with the expert winning half the comparisons at every
212
+ level.
213
+
214
+ That alone is ambiguous: it is equally consistent with "Q ignores the action" and
215
+ with "the Monte-Carlo estimator cannot resolve the action", because q_recursive
216
+ draws fresh flow noise per call. `probe_crn.py` separates them by scoring
217
+ candidates under COMMON random numbers, which cancels the shared noise from the
218
+ paired difference:
219
+
220
+ | perturbation | paired abs dQ (CRN) | expert wins | ratio to repeat noise |
221
+ |---|---|---|---|
222
+ | 0.10 | 0.399 | 0.481 | 0.18 |
223
+ | 0.20 | 0.719 | 0.503 | 0.32 |
224
+ | 0.40 | 1.588 | 0.482 | 0.71 |
225
+ | 0.80 | 3.793 | 0.502 | 1.69 |
226
+
227
+ (repeat noise, same action under independent draws: 2.246)
228
+
229
+ So Q is **not** blind. It moves substantially when the action changes, roughly
230
+ linearly in the perturbation size, and at noise 0.8 the paired response exceeds
231
+ the estimator noise. What is missing is the SIGN: perturbing an expert action is
232
+ exactly as likely to raise Q as to lower it, even at the smallest perturbation and
233
+ even with the shared noise cancelled.
234
+
235
+ The occupancy model has therefore learned an action-conditioned map whose
236
+ counterfactual gradient is meaningless. It is trained only on (state, action
237
+ actually taken, observed future); it never sees a counterfactual action with a
238
+ real outcome, so off the logged action it extrapolates confidently and
239
+ arbitrarily. Magnitude without direction.
240
+
241
+ This explains every downstream result coherently, and explains the PARL sweep
242
+ better than "weak critic" does. Selection follows an arbitrary direction, so PARL
243
+ effectively picks a random member of its candidate set; the wider the set, the
244
+ further off-support the winner, and the worse the policy -- exactly the monotone
245
+ collapse 0.440 -> 0.230 -> 0.000. AWR weights become noise that dilutes the clone.
246
+ A collapsed proposal looks harmless because a random choice among 32 copies of one
247
+ action is still that action, and it is also the only configuration that stays
248
+ inside the region where the model was ever trained.
249
+
250
+ It also explains why the 0.568 offline win rate looked survivable: comparing the
251
+ logged chunk against a DIFFERENT episode's chunk is dominated by on-support versus
252
+ off-support, which the occupancy model does capture. Ranking a policy's own
253
+ candidates at the same state is a different question, and there the model has
254
+ nothing to say.
255
+
256
+ The 0.568 offline win rate did not reveal this, because ranking *dataset*
257
+ alternatives is dominated by on-support versus off-support. That is a different
258
+ question from ranking a policy's *own* candidates, which is what every extraction
259
+ method actually does. `probe_perturb.py` asks the right question directly: does Q
260
+ prefer the expert chunk over noisy perturbations of it.
261
+
262
+ ### The filtering test the corpus was collected for
263
+
264
+ One configuration tests the critic's whole reason to exist. Fit the proposal to
265
+ the WHOLE corpus, failures included, so its candidate set genuinely contains both
266
+ good and bad behaviour, then let the value filter it. A critic that can separate
267
+ success-like from failure-like actions should recover demonstration-level
268
+ performance from a proposal that on its own is poor.
269
+
270
+ | proposal | PARL SR |
271
+ |---|---|
272
+ | demonstrations only (diversity 0.126) | 0.440 |
273
+ | whole corpus incl. failures (diversity 0.132) | **0.170** |
274
+
275
+ It does not filter. Given a candidate set that by construction contains the
276
+ failure modes the critic was trained on, selection makes things worse, not better.
277
+
278
+ That run also shows candidate diversity cannot be bought with data: fitting the
279
+ proposal to the whole corpus gives action std 0.056, against 0.053 for
280
+ demonstrations only. Flow matching learns the conditional mean regardless of how
281
+ varied the data behind it is. The only lever that moved diversity was sampling
282
+ temperature, and that pushes candidates off the manifold -- exactly where the
283
+ value's response was measured to be arbitrary. On-manifold and diverse are not
284
+ jointly available from a flow behaviour clone here.
285
+
286
+ ---
287
+
288
+ ## 7. Bugs fixed along the way
289
+
290
+ Each of these alone produced a zero or a badly wrong number.
291
+
292
+ 1. Evaluator sent Euler angles where the cache holds axis-angle (section 2).
293
+ 2. Evaluator fed float32 pixels where the builder quantises to uint8.
294
+ 3. `import_file` given an absolute path: ValueError before any env was built.
295
+ 4. The featuriser imported from the rollout producer, which does not define it.
296
+ 5. `RawFeat` left on CPU once it carried a buffer.
297
+ 6. `offline_score` indexed an empty failure pool on a demos-only cache.
298
+ 7. `bc_arm` scored before saving, discarding a finished 120k-step run.
299
+ 8. Launchers ended with `echo`, so crashed jobs exited 0 and every
300
+ `--dependency=afterok` eval ran against a checkpoint never written.
301
+ 9. AWR weight degeneracy: advantage std ~8 at beta 3 saturates the exponent, so
302
+ the "soft" weight was a hard sign filter on a 0.568-accurate critic. Worth 0.11
303
+ (IQL 0.380 to 0.490 once the advantage is standardised).
304
+ 10. `q_recursive` called the extracted policy to re-draw continuation actions in
305
+ latent space, which a raw-feature policy cannot answer; it now uses a separate
306
+ latent-space continuation policy.
307
+
308
+ ---
309
+
310
+ ## 8. Where to iterate next
311
+
312
+ The blocker is specific: the latent does not carry the action, so no read-out
313
+ built on it can rank actions, and the horizon over which a short chunk matters is
314
+ too short to recover the signal. In rough order of expected value:
315
+
316
+ 1. ~~Ask whether the ranking is inverted or absent.~~ **Answered: neither.** Q
317
+ responds to the action with the right magnitude and an arbitrary sign
318
+ (section 6). There is no sign to flip and no variance to average away -- common
319
+ random numbers make the paired response exceed the estimator noise and the
320
+ expert still wins only half the time. The defect is that the model's
321
+ COUNTERFACTUAL response is untrained: it only ever sees the action that was
322
+ actually taken. Everything below attacks that.
323
+ 2. **A latent that is action-predictive by construction.** The inverse-dynamics
324
+ auxiliary tried here (`--w-invdyn`) is the weak version: it shares the encoder
325
+ with a reward objective that dominates. Stronger: train the occupancy in a
326
+ latent whose *only* objectives are reward AND inverse dynamics, or concatenate
327
+ a proprio-history channel that already correlates with the action at 0.98.
328
+ 3. **The recipe's `q_readout=lik`.** The two-tower InfoNCE goal likelihood is the
329
+ one main-branch item not implemented here. `GoalLikelihood` already exists in
330
+ `model.py`, unused. A contrastive read-out is better calibrated than a
331
+ saturating reward head and may rank where the sigmoid cannot.
332
+ 4. **Decouple the critic's action window from the policy's.** The measured
333
+ trade-off is that the critic wants 100 frames and the policy wants 10. A
334
+ model-based lookahead that scores the policy's 10-frame chunk followed by
335
+ occupancy-rolled continuation would give the critic its long window without
336
+ forcing the policy to emit one. This is the most promising direction and the
337
+ most work; the pieces (`q_recursive`, a latent continuation policy) exist.
338
+ 5. **Richer features.** Mean-pooled PaliGemma is the root constraint. Patch tokens
339
+ or an explicitly action-conditioned encoder would change the ceiling rather
340
+ than work around it.
341
+
342
+ What is NOT worth repeating: action-contrastive weight sweeps, latent width,
343
+ recursion depth, hop length, and AWR pool choice. All were measured and none moves
344
+ the action win rate off ~0.57.
frozen/rsm_libero_freeze_20261002/FREEZE_COMMIT ADDED
@@ -0,0 +1 @@
 
 
1
+ 95842af1aa0e0854934b1fbf67f88a2cd6df850e
frozen/rsm_libero_freeze_20261002/README.md ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RSM + importance-sampled OPE on the LIBERO-10 rollout corpus
2
+
3
+ Goal: learn an occupancy critic on the pi0.5 LIBERO-10 rollout corpus (43,135
4
+ episodes, ~49.5% success), evaluate a target policy off-policy with the
5
+ importance-sampling correction, and distil a policy that beats behaviour cloning.
6
+
7
+ ## Why this corpus and not the demos
8
+
9
+ The smolvla RSM critic was fit on demonstrations only. Its AWR extraction was a
10
+ null result for a mechanical reason recorded in `rsm_vla/smolvla_rsm/README.md`:
11
+ the mean absolute advantage was **0.019**, because a BC actor that imitates the
12
+ demos scores its own action the same as the demo action. Half of this corpus is
13
+ failure, so the advantage has real spread.
14
+
15
+ ## Pipeline
16
+
17
+ | stage | file | what it produces |
18
+ |---|---|---|
19
+ | pack | `pack.py` | flat memmap cache from the per-episode npz corpus |
20
+ | critic | `train_rsm.py` | reward-predictive latent + action-conditioned occupancy |
21
+ | OPE | `is_ope.py`, `run_ope.py` | ratio nets, endpoint weight, recursive Q, gate |
22
+ | improvement | `awr.py` | advantage-weighted regression, looped with re-fitted ratios |
23
+
24
+ ## Tricks carried over from `main` (ogbench_unified_rsm)
25
+
26
+ Taken from `RECIPE.md` and `notes/COLLAPSE_ANALYSIS.md`:
27
+
28
+ * train over a **beta band**, not one discount, with Fourier features on the
29
+ log-horizon
30
+ * **residual** successor, normalised per dimension by the dataset RMS of the
31
+ residual
32
+ * **EMA target encoder** supplies the future target, with a variance floor
33
+ against latent collapse
34
+ * condition on the action chunk and the task **equally**, concat plus FiLM
35
+ * keep recursion **shallow** (2 hops here), and never prune mid checkpoints
36
+
37
+ Deliberately not carried over: the goal-ball arrival likelihood. LIBERO has no
38
+ privileged success ball in this latent, so the read-out is a learned reward
39
+ decoder, which is what the image branch of `CLAUDE.md` requires anyway.
40
+
41
+ The collapse analysis' central lesson drives the diagnostics: a value that ranks
42
+ STATES but cannot rank ACTIONS shows flat batch losses and then falls off a
43
+ cliff in closed loop. So the headline validation metric here is the **action gap**,
44
+ Q on the logged chunk minus Q on a foreign chunk at the same state, not the
45
+ state-level success AUC.
46
+
47
+ ## The importance-sampling correction
48
+
49
+ The behaviour policy is a flow model sampled as an SDE at noise 0.5 and has **no
50
+ tractable density**, which is open question 2 in the notes. We never ask for one:
51
+
52
+ 1. a classifier separates a logged chunk from a chunk sampled from the target
53
+ policy at the same state, and its logit is `log pi/mu` on balanced classes;
54
+ 2. the chunk product runs over the interior decisions of a beta-hop only, which
55
+ with a 10-action chunk is ~5 factors per hop rather than ~50;
56
+ 3. that product is regressed onto the endpoint under squared loss, whose
57
+ minimizer is `E[W | endpoint] = d^pi_beta / d^mu_beta`, the only form usable
58
+ at inference because the occupancy model emits endpoints and not actions;
59
+ 4. the recursive read multiplies endpoint weights along hops and self-normalises.
60
+
61
+ Decision-point ratios are prefix-summed once per ratio fit, so the chunk product
62
+ is an O(1) lookup rather than one forward pass per interior decision.
63
+
64
+ ## Data notes
65
+
66
+ * `task_index` is 0 in every episode of this corpus. The producer that caused it
67
+ is already fixed upstream; the packer takes ids from the canonical benchmark
68
+ order in `09052026_lib10_tasks.txt` and refuses to run on a task directory that
69
+ is not in that list.
70
+ * Failed episodes are all exactly 520 frames while successes end early, so
71
+ episode length nearly determines the outcome. Any label built from "frames
72
+ remaining" leaks it. The reward label is therefore defined on terminal states
73
+ of successful episodes, and action ranking is the headline metric.
74
+
75
+ ## Findings so far (dev cache: 2,350 episodes, 954k frames, 50% success)
76
+
77
+ ### The critic learns states well and actions weakly
78
+
79
+ Reward AUC 0.99, occupancy loss 0.27 -> 0.13, state AUC 0.50 -> 0.66 over 16k steps.
80
+ The pooled action win rate never left chance in eight checkpoints.
81
+
82
+ ### The action-ranking metric has to use an ON-SUPPORT alternative
83
+
84
+ Comparing Q on the logged chunk against a chunk permuted across the whole batch
85
+ compares against an action from a *different task*. Once the successor is
86
+ action-conditioned that lands off-manifold, and the frozen reward decoder scores
87
+ off-manifold latents arbitrarily -- the win rate fell to 0.361, i.e. the critic
88
+ "preferred" the off-support action 2 times in 3. The same bug was latent in the
89
+ sweep, whose recursion originally used an untrained continuation head.
90
+
91
+ With a within-task alternative and 8,192 pairs, the base critic ranks actions
92
+ above chance near the goal: 0.61 mean near-terminal win, vs a cross-task control
93
+ pinned at 0.47-0.52 in all twelve cells.
94
+
95
+ ### Recursion depth costs action signal; longer single hops do not
96
+
97
+ Base arm, near-terminal win pooled over four discounts:
98
+
99
+ | depth | mean win | n | 95% CI |
100
+ |---|---|---|---|
101
+ | 1 | 0.630 | ~4000 | [0.615, 0.645] |
102
+ | 2 | 0.608 | ~4000 | [0.592, 0.623] |
103
+ | 3 | 0.580 | ~3000 | [0.562, 0.598] |
104
+
105
+ The query action conditions only the first hop, so each extra hop hands more of
106
+ the trajectory to the continuation policy. Meanwhile reach at depth 1 grows from
107
+ 25 to 200 frames as beta goes 0.96 -> 0.995 with the win rate flat at 0.61-0.64.
108
+ **A single long hop dominates stacked short hops here** -- but only because the
109
+ occupancy was trained on a beta BAND covering the query horizon. Recursion earns
110
+ its place when composing *beyond* the trained band, which is not what this tested.
111
+
112
+ ### The action-contrastive term: better actions, worse states, and an artifact
113
+
114
+ At weight 1.0 it reaches its own objective (contrastive loss 0.68 -> 0.39) and
115
+ ranks near-terminal actions better (0.667 vs 0.609 over 12,000 pairs), but state
116
+ AUC drops 0.66 -> 0.59 and the occupancy loss stalls.
117
+
118
+ It also shows a **perfect depth-parity artifact**: pooled win 0.460 / 0.617 /
119
+ 0.542 at depths 1 / 2 / 3, with the value gap negative at odd depth and positive
120
+ at even depth in 12 of 12 cells. The base arm is flat at 0.505 for every depth.
121
+ Unexplained; not built on.
122
+
123
+ ### Contrastive weight: 0.1 is free, 1.0 is destructive
124
+
125
+ | arm | w_actcon | state AUC | occupancy loss |
126
+ |---|---|---|---|
127
+ | base | 0 | 0.660 | 0.132 |
128
+ | actcon01 | 0.1 | **0.676** | 0.133 |
129
+ | actcon | 1.0 | 0.587 | 0.175 |
130
+
131
+ The damage at 1.0 is an over-weighting artifact, not something inherent to the
132
+ contrastive idea. The 1.0 arm is also the one carrying the unexplained
133
+ depth-parity behaviour, so treat it as suspect.
134
+
135
+ ### The importance-sampling correction FAILED its null control
136
+
137
+ Both gates use the same critic and differ only in whether the target policy is
138
+ genuinely different from the behaviour policy.
139
+
140
+ | metric | signal (pi = BC on successes) | null (pi = BC on all ~ mu) |
141
+ |---|---|---|
142
+ | ratio classifier accuracy | 1.000 | 0.999 |
143
+ | raw `E_mu[W]` (must be 1.0) | 0.181 | 0.181 |
144
+ | calibration factor | x5.229 | x5.238 |
145
+ | weight ESS | 0.563 | 0.559 |
146
+ | corr(endpoint w, chunk W) | 0.432 | 0.434 |
147
+ | relative value shift from IS | 0.1925 | 0.1842 |
148
+ | success AUC change | +0.0019 | -0.0054 |
149
+
150
+ Identical to within noise. The correction shifts values ~19% whether or not
151
+ there is a policy difference to correct, and never improves discrimination.
152
+
153
+ **Cause, and it is an implementation error not a property of the method:** the
154
+ target policy was a diagonal Gaussian while the behaviour policy is a flow
155
+ sampled as an SDE. The classifier reached 100% accuracy by recognising the
156
+ SAMPLER, not the policy, so `log pi/mu` was a parametric-family artifact. This is
157
+ open question 2 of the notes -- a likelihood-free ratio only works if both
158
+ policies come from the same family, else the classifier solves the easier problem.
159
+
160
+ Note how well the signal gate looked in isolation: weights calibrated to 1.016,
161
+ ESS 0.56, and the best success AUC in the run (0.6645). Without the null control
162
+ that would have been reported as a working correction.
163
+
164
+ **Fix:** `FlowPolicy` in `model.py` -- a flow-matching target policy that matches
165
+ the behaviour family. AWR weights the per-sample flow-matching loss in place of a
166
+ log-density. The fix is confirmed only if classifier accuracy drops below 1.0 AND
167
+ the null gate moves to `E_mu[W]` near 1 while the signal gate does not.
168
+
169
+ ### The residual cause is the collection noise, not just the family
170
+
171
+ Same critic, same null gate, only the ratio estimator changes:
172
+
173
+ | configuration | classifier acc | `E_mu[W]` (must be 1.0) |
174
+ |---|---|---|
175
+ | Gaussian policy, no smoothing | 0.999 | 0.181 |
176
+ | flow policy, no smoothing | 0.98 | 0.184 |
177
+ | flow policy + per-dim smoothing (0.5) | 0.934 | 0.219 |
178
+
179
+ Matching the family cut classifier confidence 20x (bce 0.0035 -> 0.076) and moved
180
+ `E_mu[W]` **not at all**. The corpus was collected with pi0.5 flow **SDE noise
181
+ 0.5** deliberately injected for exploration; any policy fit to that data without
182
+ the same dispersion stays distinguishable from it. Exploration noise at
183
+ collection time is exactly what makes the behaviour distribution broad, and
184
+ breadth is what makes a target policy trivially separable from it.
185
+
186
+ Across 3 critics and 2 policy families the correction consistently shifts values
187
+ 18-26% and consistently fails to improve what the values are for:
188
+
189
+ | critic / policy | rel value shift | success AUC with IS | without IS |
190
+ |---|---|---|---|
191
+ | base / gaussian, signal | 0.192 | 0.6645 | 0.6626 |
192
+ | base / gaussian, null | 0.184 | 0.6577 | 0.6631 |
193
+ | actcon / flow, signal | 0.256 | 0.5741 | 0.5768 |
194
+
195
+ ### Smoothing helps the diagnostics and not the estimator
196
+
197
+ Null gate, where a correct weight must do NOTHING:
198
+
199
+ | configuration | acc | `E_mu[W]` | weight ESS | rel value shift | AUC change |
200
+ |---|---|---|---|---|---|
201
+ | gaussian, no smoothing | 0.999 | 0.181 | 0.559 | 0.184 | -0.005 |
202
+ | flow, no smoothing | 0.98 | 0.184 | - | - | - |
203
+ | flow + smoothing 0.5 | 0.934 | 0.219 | 0.625 | 0.219 | **+0.018** |
204
+
205
+ Smoothing did what it was meant to (acc 0.999 -> 0.934, ESS 0.559 -> 0.625) and
206
+ did not fix the estimator. The clearest tell is the **+0.018 AUC gain in the NULL
207
+ gate**: a correction that improves discrimination when there is nothing to
208
+ correct is fitting something other than the policy difference. The endpoint
209
+ regression also went unstable under smoothing (loss 0.11 -> 5.73 at step 3000).
210
+
211
+ **Verdict: across 3 critics x 2 policy families x 2 smoothing levels, the
212
+ per-decision importance weight fails its null control every time.**
213
+
214
+ ### AWR made the policy WORSE, and the mechanism is dilution
215
+
216
+ | metric | pi_0 (cloned on successes) | after 1 AWR round |
217
+ |---|---|---|
218
+ | flow loss on SUCCESS chunks | 0.1706 | 0.1708 |
219
+ | flow loss on FAILURE chunks | 0.1876 | **0.1713** |
220
+ | separation gap | **0.0170** | **0.00046** |
221
+
222
+ Round 2 is worse still: success loss 0.1770 (up from 0.1706), failure loss 0.1672
223
+ (down from 0.1876), gap **-0.0098**. The gap declines monotonically and CROSSES
224
+ ZERO -- after two rounds the policy fits FAILED chunks better than successful
225
+ ones. Iterating the loop does not merely fail to improve the policy, it
226
+ progressively inverts it.
227
+
228
+ The policy did not improve on successes; it got much better at fitting FAILURES.
229
+ `awr_step` samples from ALL training episodes and relies on the advantage to
230
+ downweight the bad ones. With an advantage this weak (the critic ranks actions at
231
+ 0.608 near the goal and at chance beyond one hop) that reduces to behaviour
232
+ cloning on the full half-failure corpus, undoing the success filtering that made
233
+ pi_0 good. It is the offline echo of this lane's own `bcall` 0.108 vs `bcdemos`
234
+ 0.584.
235
+
236
+ Normalised, the advantage is **not** larger than the demonstration-only baseline
237
+ it was supposed to beat: 0.0160-0.0221 in probability units vs the smolvla null
238
+ result's 0.0190. The raw printout reads 1.60-2.21 only because Q is divided by
239
+ (1-gamma). **The premise that failure data would give AWR a bigger signal is not
240
+ supported by this measurement.**
241
+
242
+ **The correction is NOT what breaks the loop.** Turning it off changes nothing
243
+ qualitative:
244
+
245
+ | arm | pi_0 gap | after round 1 | change |
246
+ |---|---|---|---|
247
+ | IS on | 0.0170 | 0.00046 | -97% |
248
+ | IS off | 0.0089 | 0.00111 | -87% |
249
+
250
+ Both collapse. So the loop failure and the IS failure are INDEPENDENT negatives:
251
+ the weights never tracked the policy difference (they fail their null control),
252
+ and separately the advantage is too weak to stop AWR diluting a success-cloned
253
+ policy with the failure half of the corpus.
254
+
255
+ **Caveat on the AWR arms:** `awr.py` seeded numpy but not torch, so the IS-on and
256
+ IS-off arms started from different policies (pi_0 gaps 0.0170 vs 0.0089). Each
257
+ arm's trajectory relative to its OWN baseline is valid; the absolute numbers are
258
+ not matched across arms. Fixed for future runs.
259
+
260
+ ### FINAL: no policy-extraction win. All three AWR arms lose ground.
261
+
262
+ Separation gap between success and failure chunks (higher is better):
263
+
264
+ | arm | pi_0 | round 1 | round 2 |
265
+ |---|---|---|---|
266
+ | IS on, pool=all | +0.0170 | +0.00046 | **-0.0098** |
267
+ | IS off, pool=all | +0.0089 | +0.00111 | **-0.0082** |
268
+ | IS off, pool=succ (dilution control) | +0.0211 | +0.0166 | **+0.0054** |
269
+
270
+ Two of three INVERT: the policy ends up fitting FAILED chunks better than
271
+ successful ones. Restricting the pool slows the collapse a lot but still loses
272
+ 3/4 of the starting gap. **None improves on its own starting point.** The
273
+ advantage from this critic is too weak to drive improvement even when it cannot
274
+ dilute.
275
+
276
+ ### FINAL: the smoothed IS pair is backwards
277
+
278
+ | gate | rel value shift | AUC with IS | AUC without |
279
+ |---|---|---|---|
280
+ | NULL (pi ~ mu, should do nothing) | 0.219 | 0.6675 | 0.6499 |
281
+ | SIGNAL (pi better, should help) | 0.247 | 0.6510 | **0.6557** |
282
+
283
+ It helps +0.018 where it should do nothing and hurts -0.005 where it should
284
+ help. Inverted. That closes the question.
285
+
286
+ ## Status
287
+
288
+ COMPLETE. Critic works; every off-policy result is negative. See the two FINAL
289
+ sections above. Raw artifacts in `results/`; runs under
290
+ `/data/pulkitag/users/rli14/rsm_libero_runs/`.
291
+
292
+ ## FINAL RESULTS
293
+
294
+ ### The AWR loop WORKS once the action chunk spans the hop it conditions
295
+
296
+ Every failing arm conditioned the occupancy on 10 frames of action while asking it
297
+ to predict a 50-frame hop, so 4/5 of the transition came from actions the critic
298
+ never saw. A model-free probe shows the action's contribution to predicting success
299
+ rises monotonically with sequence length: +0.0237 (10 frames) -> +0.0627 (100).
300
+
301
+ With `--chunk 100` spanning a 100-frame hop:
302
+
303
+ | critic | pooled action win | near-terminal | state AUC |
304
+ |---|---|---|---|
305
+ | chunk=100, depth 2 | **0.580** [0.569,0.591] | **0.73** | 0.698 |
306
+ | chunk=10, depth 2 | 0.519 | 0.60 | 0.664 |
307
+
308
+ **Depth 2 beats depth 1** (0.580 vs 0.547), reversing the earlier "depth hurts"
309
+ result and supporting the 2-3 hop intuition once the chunk spans the hop.
310
+
311
+ | AWR arm | pi_0 | round 1 | round 2 |
312
+ |---|---|---|---|
313
+ | **chunk=100, pool=succ** | **+0.0671** | **+0.0791** | **+0.0825** |
314
+ | chunk=10, IS on | +0.0170 | +0.00046 | -0.0098 |
315
+ | chunk=10, IS off | +0.0089 | +0.00111 | -0.0082 |
316
+ | chunk=10, pool=succ | +0.0211 | +0.0166 | +0.0054 |
317
+
318
+ Advantage is 0.068-0.080 in probability units vs the demo-only smolvla null
319
+ result's 0.019 -- ~4x more. The original premise holds at the RIGHT granularity.
320
+
321
+ ### ROOT CAUSE of every IS failure: the classifier measures NETWORK IDENTITY
322
+
323
+ Six confounds were found and removed (gaussian-vs-flow family mismatch, missing
324
+ smoothing, ratio scored over the conditioning window instead of decisions, target
325
+ policy at the wrong granularity, and two shape/order bugs). Overlap improved every
326
+ time -- classifier bce 0.0035 -> 0.286 -- and the weights still collapsed.
327
+
328
+ The identity control explains why. Train two BC policies on **identical data** with
329
+ different seeds; they are the SAME policy, so a ratio classifier must be at chance:
330
+
331
+ | comparison | classifier acc |
332
+ |---|---|
333
+ | two policies, same data, different seed | **0.945-0.977** |
334
+ | target policy vs behaviour policy | 0.941 |
335
+
336
+ Identical. The classifier detects **which network generated a sample** -- sampler
337
+ artifacts and generator fingerprints -- not a density difference. Every ratio it
338
+ produced was meaningless. `E_mu[W]` sat at 0.13-0.22 in all six configurations
339
+ regardless of critic, family, smoothing or granularity, and the final clean null
340
+ gate applied a **0.537 relative value shift where zero is correct**.
341
+
342
+ **This RETRACTS the intermediate conclusion** that flow SDE noise 0.5 at collection
343
+ made the policies too separable and that the fix was data collection. The
344
+ separability was never between policies; less injected noise would not have helped.
345
+
346
+ **Actual cause:** discriminative density-ratio estimation does not work on
347
+ continuous high-dimensional action chunks in this setup. It is an ESTIMATOR
348
+ property, not a data property. The notes' likelihood-free route -- classify instead
349
+ of requiring normalised densities -- is not viable here. A working correction needs
350
+ a genuine likelihood ratio (tractable densities on both sides) or a correction that
351
+ does not route through sample classification.
352
+
353
+ ### The likelihood ratio FIXES the estimator; the product length still kills it
354
+
355
+ Replacing the classifier with a genuine `pi/mu_hat` (two tractable Gaussians, one
356
+ fit to the logged actions by maximum likelihood, densities evaluated AT the logged
357
+ action so nothing has to tell samples apart):
358
+
359
+ | route | E_mu[w] | median w | ESS | null-gate value shift |
360
+ |---|---|---|---|---|
361
+ | classifier | 0.156 | - | 0.52 | 0.537 |
362
+ | **likelihood** | **1.756** | **0.974** | 0.526 | 0.607 |
363
+
364
+ The per-decision weight is now RIGHT IN THE BULK (median 0.974 vs a required 1.0);
365
+ the classifier's was wrong everywhere. But the null gate still fails, and the
366
+ endpoint regression needed a x10 calibration.
367
+
368
+ **Cause is arithmetic.** At `beta_q=0.99` a hop spans 100 frames = **10 policy
369
+ decisions**, so W is a product of 10 factors each with p95 = 4.48. That product is
370
+ catastrophically heavy-tailed however well-calibrated each factor is.
371
+
372
+ This is precisely the variance argument in the notes, and the real case for myopic
373
+ beta: keep each hop SHORT so the product has few factors, then recurse. The tension
374
+ is now measured on both sides:
375
+
376
+ * action signal needs LONG action windows (+0.0237 at 10 frames -> +0.0627 at 100)
377
+ * estimable weights need SHORT hops (1 decision per hop, not 10)
378
+
379
+ **Untested middle ground:** chunk = hop = ~25 frames, i.e. ~2.5 decisions per
380
+ product, where the probe still shows +0.0334 action contribution (40% above the
381
+ 10-frame case). That is the configuration most likely to satisfy both, and it is
382
+ the obvious next experiment.
383
+
384
+ ## What would come next
385
+
386
+ 1. Run the loop **without** the correction: `--chunk 100 --awr-pool succ --use-is 0`.
387
+ This is the only configuration that improves the policy monotonically.
388
+ 1b. To make IS viable, test chunk = hop = ~25 frames (~2.5 decisions per product)
389
+ with `--ratio-mode likelihood`. Both requirements are measured; this is where
390
+ they might overlap.
391
+ 2. Condition the occupancy on an action window that **spans its hop** -- the single
392
+ highest-impact setting found.
393
+ 3. For IS, replace the classifier with a genuine likelihood ratio, or drop it.
394
+ 4. Closed-loop LIBERO eval is NOT run here. Nothing in this file supports a claim
395
+ of beating BC on demos (0.584 +- 0.025 step-matched in the lane).
396
+
397
+ ## Closed-loop results, 2026-09-10 (MIT)
398
+
399
+ ### The control that was missing
400
+
401
+ The lane's own bcdemos policy, run through the lane's own evaluator on this
402
+ machine, scores **0.20 / 0.20 / 0.70 on tasks 0-2 (11/30 = 0.367)** before slurm
403
+ preempted it. The environment, EGL rendering, pi0.5 encoder, initial states and
404
+ success detection here are therefore sound, and any 0% is ours to fix. Two things
405
+ were needed to get it to run: `FL15_TASKS` must name the 10 libero_10 tasks (it
406
+ defaults to a 15-task list and the head's task embedding then refuses the
407
+ checkpoint), and the evaluation-protocol freeze needs a fresh output directory.
408
+
409
+ ### What actually caused the 0% across every arm
410
+
411
+ The policy was conditioned on the critic's 264-d encoder output. That encoder is
412
+ trained to predict REWARD, so it keeps what separates success from failure and
413
+ discards what an action head needs. On a trained arm the policy beat a
414
+ predict-the-mean action baseline by only 14% in MSE (0.1456 vs 0.1701) with a
415
+ biased gripper channel. The policy now reads the full 4104-d observation; only
416
+ the advantage comes from the critic.
417
+
418
+ ### Whitening the policy input breaks the closed loop
419
+
420
+ Four runs, one consistent pattern:
421
+
422
+ | policy input | head | steps | pooled SR |
423
+ |---|---|---|---|
424
+ | raw, chunk 25 | FiLM | 60k | 0.040 |
425
+ | **center**, chunk 10 | FiLM | 60k | **0.110** |
426
+ | z-score, chunk 10 | FiLM | 60k | 0.000 |
427
+ | z-score, chunk 10 | concat | 120k | 0.000 |
428
+
429
+ The z-scored arm had the BEST offline fit of any arm (sampled action MSE 0.0374
430
+ against 0.042 for the others) and still scored 0/100. Per-dim std on this corpus
431
+ spans 0.048 to 3.675, so whitening shrinks the few high-variance directions by up
432
+ to 34x relative to the median and flattens the spectrum. Offline the network
433
+ simply relearns its weights; at deployment the small online-vs-cache featurisation
434
+ difference is then comparable to the signal that survives. Centering removes the
435
+ uninformative common mode (mean vector norm 51.1 against a per-frame deviation of
436
+ 9.0) without flattening the spectrum, and is what the arms now use.
437
+
438
+ ### Not the cause, established by measurement
439
+
440
+ * **Featurisation.** Our encoder reproduces the demo latent cache at cos 0.9999
441
+ offline and 0.9903 from live env frames; demo and rollout latents agree at
442
+ 0.991; env obs shares the h5 orientation (pixel MAE 13.9 as-is vs 101 flipped),
443
+ so the evaluator's ROT180 is right. The previously reported 0.6015 mismatch does
444
+ not reproduce.
445
+ * **Policy architecture.** Their concatenation head, their loader and their loss,
446
+ trained here for 20k steps, reach val_mse 0.0495 -- the same as our pipeline at
447
+ the same budget (0.0471). Their published 0.0032 is reachable only with their
448
+ `--train-all` flag, which puts the validation demos into training.
449
+
450
+ ### Bugs fixed (each alone produced a zero)
451
+
452
+ 1. `import_file` given an absolute path -- ValueError before any env was built.
453
+ 2. The featuriser imported from the producer, which does not define it.
454
+ 3. `RawFeat` left on CPU once it carried a buffer.
455
+ 4. `offline_score` indexed an empty failure pool on a demos-only cache.
456
+ 5. `bc_arm` scored before saving, discarding a finished 120k-step run.
457
+ 6. Launchers ended with `echo`, so crashed jobs exited 0 and every
458
+ `--dependency=afterok` eval ran against a checkpoint that was never written.
459
+
460
+ ## Results with the FIXED evaluator (2026-09-11)
461
+
462
+ All runs: 10 tasks x 10 initial states, max 520 steps, chunk 10, executed 10.
463
+ Throughput = pooled SR * max_steps / mean_steps.
464
+
465
+ | arm | succ/n | pooled SR | thr (succ) | thr (all) |
466
+ |---|---|---|---|---|
467
+ | reference bcdemos, **our** harness | 53/100 | 0.530 | 0.946 | 0.691 |
468
+ | reference bcdemos, **its own** harness | 46/100 | 0.460 | 0.888 | 0.591 |
469
+ | **A: BC on demos (ours)** | **58/100** | **0.580** | **1.082** | **0.794** |
470
+ | B: BC on successful rollouts | 47/100 | 0.470 | 0.831 | 0.591 |
471
+ | C: IQL critic + AWR | 38/100 | 0.380 | 0.607 | 0.443 |
472
+ | ablation: A with z-scored input | 1/100 | 0.010 | 0.014 | 0.010 |
473
+
474
+ The harness control (0.530 ours vs 0.460 theirs, same weights) confirms this
475
+ evaluator is equivalent to the lane's; the 0.07 spread is seed variation at
476
+ n=100.
477
+
478
+ ### The whitening ablation is now clean
479
+
480
+ A trained on demonstrations, center-scaled, scores 0.580. The identical run with
481
+ per-dim z-scored input scores 0.010. Same data, same head, same budget, same
482
+ seed -- only the input scaling differs. Whitening flattens a spectrum whose
483
+ per-dim std spans 0.048 to 3.675, shrinking the informative high-variance
484
+ directions by up to 34x relative to the median.
485
+
486
+ ### AWR currently HURTS
487
+
488
+ C starts from a BC-on-successes clone (0.470) and IQL-weighted AWR takes it to
489
+ 0.380. Both critic arms initialised on successes alone, which starts them 0.11
490
+ below the BC-on-demos bar they must clear. `--init-pool demos_succ` now lets both
491
+ arms start from demonstrations plus successful rollouts, so the comparison
492
+ measures the critic rather than the initialisation.
493
+
494
+ ## Matched four-arm comparison (2026-09-11, demonstration statistics)
495
+
496
+ Every arm: full_demo cache, demo-pool feature statistics, center scaling, the
497
+ concatenation flow head, chunk 10, batch 1024, 120k steps, seed 0. The critic
498
+ arms start from the SAME behaviour clone as arm A, so the comparison isolates the
499
+ improvement signal.
500
+
501
+ | arm | succ/n | SR | thr succ / all |
502
+ |---|---|---|---|
503
+ | **A: BC on demonstrations** | **63/100** | **0.630** | 1.183 / 0.788 |
504
+ | B: BC on successful rollouts | 48/100 | 0.480 | 0.807 / 0.596 |
505
+ | C: IQL critic + AWR (soft) | 49/100 | 0.490 | 0.839 / 0.615 |
506
+ | D: RSM critic + AWR (soft, pessimism 2.0) | running | | |
507
+
508
+ Reference: the lane's own bcdemos policy scores 0.530 through this harness and
509
+ 0.460 through its own.
510
+
511
+ ### Two normalisation findings worth keeping
512
+
513
+ | policy input | SR |
514
+ |---|---|
515
+ | centred with DEMONSTRATION statistics | 0.630 |
516
+ | centred with rollout-dominated statistics | 0.430 |
517
+ | per-dim z-scored | 0.010 |
518
+
519
+ Centring matters (the mean feature vector has norm 51.1 against a per-frame
520
+ deviation of 9.0), WHICH frames the statistics come from matters (the rollout
521
+ corpus is a noisier, half-failing distribution), and whitening is catastrophic
522
+ (per-dim std spans 0.048 to 3.675, so it shrinks the informative directions up to
523
+ 34x relative to the median).
524
+
525
+ ## The critic is the blocker, and it is upstream of the flow
526
+
527
+ Held-out within-task action win rate -- how often Q ranks the action actually
528
+ taken above another action from the same task -- across every intervention tried:
529
+
530
+ | critic | best win rate |
531
+ |---|---|
532
+ | chunk 10, w_actcon 0.5 (the one deployed) | 0.568 |
533
+ | w_actcon 1.0, d_z 512 | 0.532 |
534
+ | w_actcon 2.0 | 0.533 |
535
+ | inverse dynamics 1.0 | 0.445 |
536
+ | inverse dynamics 5.0 | 0.534 |
537
+ | deployed critic + pessimism 2.0 (probe) | 0.570 |
538
+
539
+ All peak between step 1000 and 2000 and then decay below chance while reward AUC
540
+ stays above 0.95. The state value is excellent and the action ranking is near
541
+ coin-flip.
542
+
543
+ The cause is upstream of the occupancy model. This lane measured that over 5
544
+ frames the executed action correlates with the proprio delta at |r| up to 0.98
545
+ but with the visual-latent delta at only 0.49 (mean 0.10): a mean-pooled
546
+ PaliGemma embedding barely resolves the motion a 10-frame chunk produces. Raising
547
+ the action-contrastive weight asks the flow to use information the latent does
548
+ not carry, which is why 2.0 was worse than 0.5.
549
+
550
+ ### Every downstream use of that critic fails
551
+
552
+ | use | from | to |
553
+ |---|---|---|
554
+ | AWR, hard weight (IQL) | 0.470 | 0.380 |
555
+ | AWR, hard weight (RSM) round 1 | 0.470 | 0.400 |
556
+ | AWR, hard weight (RSM) round 2 | 0.470 | 0.290 |
557
+ | AWR, soft weight (IQL) | 0.630 | 0.490 |
558
+ | Q-filter, 16 candidates (RSM) | 0.630 | 0.510 |
559
+
560
+ The hard-weight collapse was a real bug and is fixed: with advantage std ~8 and
561
+ beta 3 the exponent saturates, so the "soft" weight became a hard filter on the
562
+ sign of a 0.568-accurate critic. Standardising the advantage recovers most of the
563
+ loss (IQL 0.380 -> 0.490) but does not turn a coin-flip critic into an
564
+ improvement.
565
+
566
+ ## Where RSM stands (2026-09-11)
567
+
568
+ Matched: full_demo cache, demo statistics, center scaling, concatenation flow
569
+ head, chunk 10, batch 1024, 120k steps, seed 0. C and D start from the SAME
570
+ demonstration clone as A.
571
+
572
+ | arm | succ/n | SR | thr succ / all |
573
+ |---|---|---|---|
574
+ | **A: BC on demonstrations** | **63/100** | **0.630** | 1.183 / 0.788 |
575
+ | C: IQL + AWR (soft, pool = successes) | 49/100 | 0.490 | 0.839 / 0.615 |
576
+ | B: BC on successful rollouts | 48/100 | 0.480 | 0.807 / 0.596 |
577
+ | RSM Q-filter, 16 candidates, on A | 51/100 | 0.510 | - |
578
+ | D: RSM + AWR (soft, pessimism 2.0, pool = successes) | 41/100 | 0.410 | 0.802 / 0.513 |
579
+
580
+ **RSM does not yet beat the baselines.** Both critic arms move the policy DOWN
581
+ from the 0.630 clone they start at, and RSM moves it further down than IQL.
582
+
583
+ Chunk 100 was tried because it is the only setting where the critic ranks actions
584
+ well (win 0.613 against 0.568 at chunk 10, confirming that over a 10-frame hop the
585
+ action barely moves the success probability). It does not rescue the result: BC at
586
+ chunk 100 fits far worse (sampled action MSE 0.114 against 0.049) and scores
587
+ 0.00-0.20 per task over the first six, so the better critic sits on top of a much
588
+ weaker policy.
589
+
590
+ ### What would have to change
591
+
592
+ The critic ranks actions at 0.57 and that ceiling survived every intervention:
593
+ action-contrastive weight 0.5/1.0/2.0, latent width 512, inverse dynamics 1.0/5.0,
594
+ particle pessimism, and chunk/hop length. Reward AUC stays above 0.95 throughout,
595
+ so the state value is strong and only the ACTION channel is missing. The measured
596
+ cause is upstream: over 5 frames the executed action correlates with the proprio
597
+ delta at |r| up to 0.98 but with the visual latent delta at only 0.49 (mean 0.10).
598
+ Until the latent carries the action, no read-out on top of it can rank actions,
599
+ and every consumer of that ranking -- AWR in two flavours, Q-filtering -- lowers a
600
+ good policy instead of raising it.
601
+
602
+ ## FINAL: all arms, fixed evaluator (2026-09-11)
603
+
604
+ 10 tasks x 10 initial states, 520-step cap, chunk 10 executed 10. Every arm uses
605
+ the same cache, demonstration statistics, center scaling, concatenation flow head,
606
+ batch 1024, 120k steps, seed 0. Both critic arms start from the SAME demonstration
607
+ clone as arm A, so the only difference is the improvement signal.
608
+
609
+ | arm | succ/n | SR | thr succ | thr all |
610
+ |---|---|---|---|---|
611
+ | **A: BC on demonstrations** | **63/100** | **0.630** | 1.132 | 0.874 |
612
+ | reference bcdemos, our harness | 53/100 | 0.530 | 0.946 | 0.691 |
613
+ | RSM Q-filter, 16 candidates | 51/100 | 0.510 | 0.951 | 0.668 |
614
+ | C: IQL + AWR (demo pool) | 50/100 | 0.500 | 0.963 | 0.658 |
615
+ | C: IQL + AWR (success pool) | 49/100 | 0.490 | 0.839 | 0.615 |
616
+ | B: BC on successful rollouts | 48/100 | 0.480 | 0.807 | 0.596 |
617
+ | D: RSM + AWR (demo pool) | 43/100 | 0.430 | 0.758 | 0.528 |
618
+ | D: RSM + AWR (success pool) | 41/100 | 0.410 | 0.802 | 0.513 |
619
+
620
+ **The RSM recipe does not beat BC-on-demonstrations, BC-on-successes, or IQL
621
+ extraction on this dataset.** Behaviour cloning on the 500 demonstrations wins
622
+ outright, and it also beats the published reference through the same harness.
623
+
624
+ ### The search that was run
625
+
626
+ Critic: action-contrastive weight 0.5 / 1.0 / 2.0; latent width 256 / 512;
627
+ inverse dynamics 1.0 / 5.0; chunk and hop 10 / 100; particle pessimism 0 to 4.
628
+ Extraction: AWR with hard and standardised weights, over the all / success /
629
+ demonstration pools, with and without the importance-sampling correction, one and
630
+ two rounds, plus deployment-time Q-filtering over 4 and 16 candidates.
631
+
632
+ ### The single blocker
633
+
634
+ Held-out within-task action win rate never exceeds 0.57 at chunk 10 (0.613 at
635
+ chunk 100), while reward AUC stays above 0.95. The state value is strong; the
636
+ action channel is missing, and it is missing upstream of the occupancy model: over
637
+ 5 frames the executed action correlates with the proprio delta at |r| up to 0.98
638
+ but with the visual-latent delta at only 0.49 (mean 0.10). A mean-pooled PaliGemma
639
+ embedding does not resolve what a 10-frame chunk does. Every consumer of that
640
+ ranking therefore lowers a good policy rather than raising it.
641
+
642
+ The chunk-100 result is the constructive part: lengthening the action window and
643
+ the hop is the one intervention that moved the win rate (0.568 -> 0.613), which
644
+ says the horizon, not the read-out, is what starves the signal. Making that
645
+ usable needs a policy that is still accurate at a 100-frame chunk; ours loses more
646
+ to the longer chunk (sampled action MSE 0.114 vs 0.049) than the critic gains.
647
+
648
+ ### The ceiling is the ACTION WINDOW, not the hop
649
+
650
+ Held-out within-task action win rate, chunk 10 held fixed while the hop varies:
651
+
652
+ | chunk | hop (beta_q) | best win |
653
+ |---|---|---|
654
+ | 10 | 0.90 (~10 frames) | 0.568 |
655
+ | 10 | 0.97 (~33 frames) | 0.558 |
656
+ | 10 | 0.99 (~100 frames) | 0.551 |
657
+ | 100 | 0.99 (~100 frames) | **0.613** |
658
+
659
+ Lengthening the hop does nothing; lengthening the ACTION WINDOW is what moves it.
660
+ A 10-frame chunk simply does not determine much about the future on this task, so
661
+ the ranking ceiling at chunk 10 is a property of the data rather than a modelling
662
+ failure. And the policy trades the other way: a chunk-100 policy loses more to the
663
+ longer chunk (sampled action MSE 0.114 against 0.049) than the critic gains.
664
+
665
+ With this featurisation you can have an accurate policy or a discriminative
666
+ critic, not both. That is the finding, and it is what any future attempt on this
667
+ corpus has to break.
668
+
669
+ ## PARL with the RSM value, and the experiment that settles it
670
+
671
+ PARL: sample N=32 action chunks from a proposal policy, rank by the RSM Q, keep
672
+ the argmax, distill into a fresh head. The recipe's own precondition is that the
673
+ proposal's samples must be DIVERSE, because ranking N copies of one action cannot
674
+ improve anything. Measured proposal action std against the data's 0.421:
675
+
676
+ | proposal | action std | ratio |
677
+ |---|---|---|
678
+ | BC on demos, 120k steps, best-MSE checkpoint | 0.029 | 0.070 |
679
+ | BC on demos, 20k steps | 0.053 | 0.126 |
680
+ | the same, sampling temperature 1.5 | 0.103 | 0.244 |
681
+ | the same, sampling temperature 2.5 | 0.222 | 0.527 |
682
+
683
+ Selecting a checkpoint by best held-out sampled reconstruction MSE picks the most
684
+ mean-collapsed one, so the earlier Q-filter run was ranking near-identical
685
+ candidates. That is fixed above.
686
+
687
+ ### The result
688
+
689
+ | proposal diversity | PARL SR |
690
+ |---|---|
691
+ | 0.070 (120k clone) | 0.350 |
692
+ | 0.126 | 0.440 |
693
+ | 0.244 | 0.230 |
694
+ | 0.527 | **0.000** |
695
+
696
+ Success falls monotonically as the critic is given more freedom to choose. Every
697
+ other factor is fixed: same critic, same N, same distillation, same evaluator.
698
+ The only variable is how different the candidates are. If the value function
699
+ carried signal, widening the candidate set would help; it destroys the policy
700
+ instead, so the ranking is not weak, it is pointed the wrong way. A collapsed
701
+ proposal scores near BC simply because selection can do little harm when all 32
702
+ candidates are the same action.
703
+
704
+ This is the cleanest isolation of the critic in this lane, and it agrees with the
705
+ offline probe: held-out within-task action win rate 0.568, barely above chance,
706
+ while reward AUC stays above 0.95.
707
+
708
+ Chunk 30 closes the last alternative: BC 0.440, RSM + AWR 0.160, with a critic
709
+ that ranks at 0.597. Across all three action windows the same pattern holds.
710
+
711
+ | chunk | BC on demos | RSM extraction | critic win rate |
712
+ |---|---|---|---|
713
+ | 10 | 0.630 | 0.430 | 0.568 |
714
+ | 30 | 0.440 | 0.160 | 0.597 |
715
+ | 100 | 0.080 | 0.020 | 0.613 |
716
+
717
+ A better-ranking critic goes with a worse policy at every size, and the product is
718
+ worse than plain behaviour cloning in all three.
719
+
720
+ ### PARL grid: both knobs point the same way
721
+
722
+ | selection rule | T=1.5 (diversity 0.244) | T=2.5 (diversity 0.527) |
723
+ |---|---|---|
724
+ | Q minus 2 particle std | 0.230 | 0.000 |
725
+ | pure expected success | 0.130 | 0.010 |
726
+
727
+ Two independent controls, same conclusion. Giving the value more candidates to
728
+ choose among makes it worse, and removing the variance penalty -- so that
729
+ selection follows the raw value rather than staying near the mode -- makes it
730
+ worse again. The penalty was masking the problem by keeping choices close to the
731
+ proposal's mode, not by adding information.
732
+
733
+ The RSM value's preference over actions is anti-correlated with action quality on
734
+ this corpus. That is a stronger and more useful statement than "the critic is
735
+ weak", and it is what the offline probe was too blunt to show: a 0.568 win rate
736
+ against dataset alternatives is dominated by on-support versus off-support, which
737
+ says nothing about ranking a policy's own candidates.
frozen/rsm_libero_freeze_20261002/audit_logged_goal.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Is the label wrong, or did the replay diverge? These are different claims.
2
+
3
+ Replaying logged actions tests reproducibility; the corpus is documented as NOT
4
+ bit-reproducible, so a replay failure does not by itself prove the label is wrong.
5
+
6
+ This does the direct test instead and needs no replay: load the episode's LOGGED FINAL
7
+ sim_state, restore the simulator to it, and evaluate LIBERO's own goal predicate.
8
+ If the predicate is false in the very state the episode ended in, while is_success=1,
9
+ the label is wrong -- no nondeterminism can explain it.
10
+
11
+ Per-conjunct results are also recorded, which measures how much of a compound task a
12
+ "successful" episode actually completed.
13
+ """
14
+ import argparse, io, os, re, sys, base64
15
+ import numpy as np
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"
18
+ PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
19
+
20
+
21
+ def src_parquet(ep_src):
22
+ m = PAT.search(str(ep_src))
23
+ if not m: return None
24
+ t, b, i, idx = m.groups()
25
+ p = (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}"
26
+ f"/data/chunk-000/episode_{int(idx):06d}.parquet")
27
+ return p if os.path.exists(p) else None
28
+
29
+
30
+ def main():
31
+ ap = argparse.ArgumentParser()
32
+ ap.add_argument("--cache", required=True); ap.add_argument("--task", type=int, required=True)
33
+ ap.add_argument("--out", required=True); ap.add_argument("--limit", type=int, default=0)
34
+ ap.add_argument("--save-img", type=int, default=12, help="keep this many final frames of label errors")
35
+ args = ap.parse_args()
36
+
37
+ import pyarrow.parquet as pq
38
+ from libero.libero import benchmark, get_libero_path
39
+ from libero.libero.envs.env_wrapper import ControlEnv
40
+ from pathlib import Path
41
+
42
+ m = np.load(f"{args.cache}/meta.npz", allow_pickle=True)
43
+ d, s, task = m["ep_demo"].astype(bool), m["ep_success"].astype(bool), m["ep_task"]
44
+ todo = np.where((task == args.task) & s & ~d)[0]
45
+ if args.limit: todo = todo[:args.limit]
46
+
47
+ bench = benchmark.get_benchmark_dict()["libero_10"]()
48
+ t = bench.get_task(args.task)
49
+ env = ControlEnv(bddl_file_name=str(Path(get_libero_path("bddl_files"))
50
+ / t.problem_folder / t.bddl_file),
51
+ has_renderer=False, has_offscreen_renderer=False, use_camera_obs=False)
52
+ env.reset()
53
+ goal = env.env.parsed_problem["goal_state"]
54
+ print(f"[audit] task {args.task}: {len(todo)} logged successes, goal={goal}", flush=True)
55
+
56
+ rows, imgs = [], []
57
+ for n, e in enumerate(todo):
58
+ p = src_parquet(m["ep_src"][e])
59
+ if p is None: rows.append((int(e), -1, -1, 0)); continue
60
+ tb = pq.read_table(p, columns=["sim_state", "is_success", "image"])
61
+ last = tb.num_rows - 1
62
+ st = np.asarray(tb["sim_state"][last].as_py(), np.float64)
63
+ env.env.sim.set_state_from_flattened(st)
64
+ env.env.sim.forward()
65
+ conj = [bool(env.env._eval_predicate(g)) for g in goal]
66
+ ok = all(conj)
67
+ rows.append((int(e), int(ok), int(sum(conj)), len(conj)))
68
+ if not ok and len(imgs) < args.save_img:
69
+ imgs.append((int(e), int(sum(conj)), len(conj),
70
+ base64.b64encode(tb["image"][last].as_py()["bytes"]).decode()))
71
+ if (n + 1) % 50 == 0:
72
+ g = [r for r in rows if r[1] >= 0]
73
+ print(f"[audit] {n+1}/{len(todo)} goal-holds-at-logged-end "
74
+ f"{sum(r[1] for r in g)}/{len(g)}", flush=True)
75
+ env.close()
76
+ a = np.array([r for r in rows if r[1] >= 0])
77
+ np.savez_compressed(args.out, rows=np.array(rows), task=args.task,
78
+ imgs=np.array([i[3] for i in imgs], dtype=object),
79
+ img_ep=np.array([i[0] for i in imgs]),
80
+ img_sat=np.array([[i[1], i[2]] for i in imgs]))
81
+ if len(a):
82
+ holds = int(a[:, 1].sum()); tot = len(a)
83
+ print(f"[audit] task {args.task}: goal predicate TRUE at the logged final state "
84
+ f"for {holds}/{tot} ({holds/tot:.3f}) of logged successes", flush=True)
85
+ bad = a[a[:, 1] == 0]
86
+ if len(bad):
87
+ print(f"[audit] of the {len(bad)} label errors, conjuncts satisfied: "
88
+ f"{np.bincount(bad[:, 2], minlength=int(a[0,3])+1).tolist()} "
89
+ f"(index = #subgoals met of {int(a[0,3])})", flush=True)
90
+
91
+
92
+ if __name__ == "__main__":
93
+ main()
frozen/rsm_libero_freeze_20261002/audit_logged_goal.sbatch ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --job-name=audit_goal
3
+ #SBATCH --account=vision-pulkitag
4
+ #SBATCH --cpus-per-task=4 --mem=32G
5
+ #SBATCH --array=0-9
6
+ #SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%a_%A.out
7
+ #SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%a_%A.err
8
+ set -uo pipefail
9
+ B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation
10
+ S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion
11
+ export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard
12
+ export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1
13
+ OUT=/data/pulkitag/users/rli14/rsm_libero_runs/goalaudit; mkdir -p $OUT
14
+ $B/venvs/rlinf-libero-eval-venv/bin/python \
15
+ /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/audit_logged_goal.py \
16
+ --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \
17
+ --task $SLURM_ARRAY_TASK_ID --out $OUT/task$SLURM_ARRAY_TASK_ID.npz
frozen/rsm_libero_freeze_20261002/autoresearch_driver.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Autoresearch driver: reads the local JSON mirror, advances stages, launches the next
2
+ cells via ibm_autoresearch.sh. Idempotent (state in a JSON file); run it repeatedly."""
3
+ import json, os, subprocess, sys, glob
4
+ sys.argv = ["x"]; sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
5
+ import ibm_table as T
6
+ D = "/data/pulkitag/scratch/rli14/ibm_eval_json"; ST = "/data/pulkitag/scratch/rli14/autoresearch_state.json"
7
+ IB = "/proj/dmfexp/zwhong/rsm_libero"; R = f"{IB}/runs/full_r256"
8
+ st = json.load(open(ST)) if os.path.exists(ST) else {}
9
+ def save(): json.dump(st, open(ST, "w"), indent=1)
10
+ def run(*a): return subprocess.run(["./ibm_autoresearch.sh", *a], capture_output=True, text=True, timeout=1800).stdout
11
+ cells = T.load(D)
12
+ V = {k[0]: v for k, v in cells.items() if k[1] == "DL" and k[4] == "V"}
13
+ plain = V.get("plain")
14
+ def vs_plain(arm):
15
+ if arm not in V or plain is None: return None
16
+ r = T.pair(V[arm], plain); return r
17
+ print(f"V cells: {len(V)} plain={plain['sr'] if plain else None}")
18
+ for arm in sorted(V):
19
+ r = vs_plain(arm); print(f" {arm:22} SR {V[arm]['sr']:.3f} thr {V[arm]['thr']:.3f}" + (f" dSR {r['dsr']:+.3f} p={r['p']:.2f}" if r else ""))
20
+ # ---- stage 1 -> stage 2
21
+ s1 = [f"RSMb{b}d{d}{pp}" for b in (90, 95, 98) for d in (1, 2, 3) for pp in ("", "p256")]
22
+ if "stage2" not in st and all(a in V for a in s1) and plain:
23
+ best = max(s1, key=lambda a: (V[a]["sr"], V[a]["thr"]))
24
+ b, d = best[4:6], best[7]; pp = "256" if best.endswith("p256") else "16" # RSMb<bb>d<d>[p256]
25
+ print(f"stage1 complete -> best {best}; launching stage2 at {pp} particles"); os.environ["QFPART"] = pp; print(run("stage2", b, d))
26
+ st["stage2"] = {"beta": b, "depth": d, "part": pp}; save()
27
+ # ---- BC checkpoint selection
28
+ if "bcsel" not in st:
29
+ out = subprocess.run(["ssh", "-o", "BatchMode=yes", "bluevela", f"ls {R}/BCdemo_c/policy_s120000.pt 2>/dev/null"], capture_output=True, text=True, timeout=120).stdout
30
+ if "policy_s120000" in out:
31
+ print("BCdemo_c finished -> launching bcsel"); print(run("bcsel")); st["bcsel"] = 1; save()
32
+ # ---- critic checkpoint selection on V for each finished critic run, then confirm the arg-max on A/B
33
+ CB = f"{R}/qsg_f/ckpt_best.pt"; HOP = f"{R}/HOPdemo_f/policy_r1.pt"
34
+ b2, d2 = (st["stage2"]["beta"], st["stage2"]["depth"]) if "stage2" in st else ("95", "3")
35
+ for crun in ("qsg_bce", "qind_bce", "qsoft_f", "qsg_b90", "qsg_wide"):
36
+ key = f"critsel_{crun}"
37
+ if key not in st:
38
+ done = subprocess.run(["ssh", "-o", "BatchMode=yes", "bluevela", f"grep -q '^\\[rsm\\] DONE' {R}/logs/{crun}.out && ls {R}/{crun}/ckpt_s*.pt 2>/dev/null | wc -l"], capture_output=True, text=True, timeout=120).stdout.strip()
39
+ if done and done != "0":
40
+ print(f"{crun} finished ({done} periodic ckpts) -> critsel on V"); print(run("critsel", crun, b2, d2))
41
+ st[key] = {"n": int(done)}; save()
42
+ elif "confirmed" not in st[key]:
43
+ arms = sorted([a for a in V if a.startswith(f"RSMc{crun}S")], key=lambda a: -V[a]["sr"])
44
+ if len(arms) >= st[key]["n"] and arms:
45
+ step = arms[0][len(f"RSMc{crun}S"):]
46
+ print(f"{crun}: V arg-max checkpoint = step {step} (SR {V[arms[0]]['sr']:.3f}); confirming on A/B x 3 seeds")
47
+ env = f"CRITIC={R}/{crun}/ckpt_s{step}.pt, SELECT=argmaxq, HOPPOL={HOP}, QFDEPTH={d2}, QFBETA=0.{b2}, QFILTER=8, QFPES=0, QFGATE=0, QFCRN=1, QFPART=16"
48
+ print(run("stage3", f"RSMc{crun}", env, "DL", f"{R}/BCdemo_f/policy_last.pt"))
49
+ st[key]["confirmed"] = step; save()
50
+ # ---- stage 2 -> stage 3
51
+ if "stage2" in st and "stage3" not in st:
52
+ b, d = st["stage2"]["beta"], st["stage2"]["depth"]
53
+ s2 = [f"RSMb{b}d{d}{x}" for x in ("n32", "n16", "q90", "q90n32", "near4", "fold", "pes1", "nocrn", "cL")] + [f"RSMb{b}d{d}" + ("p256" if st["stage2"].get("part") == "256" else "")]
54
+ pc = sorted([a for a in V if a.startswith("plainC")], key=lambda a: -V[a]["sr"])
55
+ if all(a in V for a in s2) and (("bcsel" in st and pc and len(pc) >= 12) or plain):
56
+ top = sorted(s2, key=lambda a: -(V[a]["sr"] + 0.1 * V[a]["thr"]))[:2]
57
+ bc_ckpt = f"{R}/BCdemo_c/policy_s{pc[0][6:]}.pt" if pc else f"{R}/BCdemo_f/policy_last.pt"
58
+ prop = "DC" if pc else "DL"
59
+ print(f"stage2 complete -> confirming {top} on A/B x3 seeds against BC ckpt {bc_ckpt}")
60
+ CB = f"{R}/qsg_f/ckpt_best.pt"; HOP = f"{R}/HOPdemo_f/policy_r1.pt"
61
+ pp = st["stage2"].get("part", "256")
62
+ def env_for(a):
63
+ x = a[len(f"RSMb{b}d{d}"):].replace("p256", "")
64
+ e = f"CRITIC={CB}, HOPPOL={HOP}, QFDEPTH={d}, QFBETA=0.{b}, QFGATE=0, QFCRN=1, QFPART={pp}, QFPES=0, QFILTER=8, SELECT=argmaxq"
65
+ if x == "n32": e = e.replace("QFILTER=8", "QFILTER=32")
66
+ if x == "n16": e = e.replace("QFILTER=8", "QFILTER=16")
67
+ if x == "q90": e = e.replace("SELECT=argmaxq", "SELECT=quantile, SELQ=0.9")
68
+ if x == "q90n32": e = e.replace("SELECT=argmaxq", "SELECT=quantile, SELQ=0.9").replace("QFILTER=8", "QFILTER=32")
69
+ if x == "near4": e = e.replace("SELECT=argmaxq", "SELECT=qnear, QNEARK=4")
70
+ if x == "fold": e += ", QFMODE=fold"
71
+ if x == "pes1": e = e.replace("QFPES=0", "QFPES=1")
72
+ if x == "nocrn": e = e.replace("QFCRN=1", "QFCRN=0")
73
+ if x == "cL": e = e.replace(CB, f"{R}/qsg_f/ckpt.pt")
74
+ return e
75
+ for a in top: print(run("stage3", a, env_for(a), prop, bc_ckpt))
76
+ print(run("stage3", "plain", "QFILTER=0", prop, bc_ckpt))
77
+ print(run("stage3", "medoid8", "SELECT=medoid, QFILTER=8, QFDEPTH=1, QFBETA=0.98, QFPES=0, QFGATE=0", prop, bc_ckpt))
78
+ st["stage3"] = {"arms": top, "bc_ckpt": bc_ckpt}; save()
frozen/rsm_libero_freeze_20261002/awr.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Policy improvement by advantage-weighted regression on the IS-corrected Q,
2
+ and the evaluation <-> improvement loop.
3
+
4
+ A(z,A) = Q^pi(z,A) - V(z), V(z) = mean over M chunks drawn from pi itself
5
+ loss = -E[ w * log pi(A_data | z) ], w = clip(exp(beta*A), 0, w_max)
6
+
7
+ Why this can carry signal where the smolvla run's could not: that critic was fit
8
+ on demonstrations only, so Q(demo action) ~= Q(actor's own action) and the mean
9
+ absolute advantage was 0.019 -- no gradient. Here half the corpus is failure, so
10
+ the advantage has real spread, and the weights are additionally corrected toward
11
+ pi by the endpoint ratio rather than left at the behaviour policy's value.
12
+
13
+ The loop is deliberately short (2-3 rounds). Each round re-fits the ratio nets,
14
+ because the target policy has moved and a stale ratio silently evaluates the
15
+ wrong policy -- the notes flag exactly this.
16
+ """
17
+ from __future__ import annotations
18
+ import sys as _sys, os as _os
19
+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
20
+ import argparse, json
21
+ from pathlib import Path
22
+ import numpy as np
23
+ import torch
24
+
25
+ from model import BCHead, FlowPolicy
26
+ from data import LiberoRSMData
27
+ from is_ope import (
28
+ policy_features, load_critic, train_bc, train_ratio, train_endpoint_ratio,
29
+ q_recursive, make_policy, policy_nll)
30
+ from train_rsm import auc
31
+
32
+
33
+ def awr_step(d, enc, pol, *, rew, flow, rms, wend, args, device, steps, M=4,
34
+ pfeat=None, d_policy=None, cont_pol=None):
35
+ """One improvement round. Returns a NEW policy; `pol` is left untouched.
36
+
37
+ `awr_pool` controls which episodes the regression draws from. Standard AWR
38
+ uses ALL data and relies on the advantage to downweight bad actions. Measured
39
+ consequence when the advantage is weak: pi_0 was cloned on SUCCESSES, one AWR
40
+ round over all data collapsed its success-vs-failure separation from 0.0170
41
+ to 0.00046, and the loss on FAILED chunks improved from 0.1876 to 0.1713 --
42
+ i.e. it walked the policy back toward cloning the full half-failure corpus.
43
+ That is the offline echo of this lane's own bcall=0.108 vs bcdemos=0.584.
44
+ `awr_pool=succ` restricts the pool so AWR can only sharpen within the slice
45
+ pi_0 was fit on, which isolates dilution from genuine improvement."""
46
+ pf = enc if pfeat is None else pfeat
47
+ # q_recursive rolls hops through the occupancy model and must re-draw a
48
+ # continuation action at each hop CONDITIONED ON THE PREDICTED LATENT z'.
49
+ # Once the extracted policy reads raw 4104-d observations it cannot be
50
+ # queried there -- there is no observation for a latent the flow imagined.
51
+ # `cont_pol` is a small BC policy living in the critic's latent space used
52
+ # only inside the recursion; the policy AWR actually improves is `new`.
53
+ roll = cont_pol if cont_pol is not None else pol
54
+ new = make_policy(args, d, device, d_z=d_policy)
55
+ new.load_state_dict(pol.state_dict())
56
+ opt = torch.optim.AdamW(new.parameters(), lr=1e-4, weight_decay=0.01)
57
+ rng = np.random.default_rng(args.seed + 11)
58
+ stats = []
59
+ _ap = getattr(args, "awr_pool", "all")
60
+ for step in range(1, steps + 1):
61
+ b = d.sample_frames(args.batch, rng, "train", device)
62
+ if _ap != "all":
63
+ keep = (b["succ"] > 0.5) if _ap == "succ" else (b["demo"] > 0.5)
64
+ if keep.sum() < 8:
65
+ continue
66
+ b = {k: (v[keep.cpu().numpy()] if isinstance(v, np.ndarray)
67
+ else (v[keep] if torch.is_tensor(v) else v))
68
+ for k, v in b.items()}
69
+ with torch.no_grad():
70
+ z = enc(b["x"]) # critic latent -> advantage
71
+ zp = pf(b["x"]) # policy features -> action head
72
+ q_data, _ = q_recursive(z, b["a"], b["task"], rew=rew, flow=flow, rms=rms,
73
+ pol=roll, wend=wend, beta=args.beta_q,
74
+ gamma=args.gamma, depth=args.depth,
75
+ n_particles=args.particles, use_is=args.use_is,
76
+ pessimism=args.q_pessimism)
77
+ # V(z) = Monte-Carlo baseline over the policy's own chunks
78
+ v = torch.zeros_like(q_data)
79
+ for _ in range(M):
80
+ a_pi = new.sample(zp, b["task"])
81
+ qi, _ = q_recursive(z, a_pi, b["task"], rew=rew, flow=flow, rms=rms,
82
+ pol=roll, wend=wend, beta=args.beta_q,
83
+ gamma=args.gamma, depth=args.depth,
84
+ n_particles=args.particles, use_is=args.use_is,
85
+ pessimism=args.q_pessimism)
86
+ v += qi
87
+ v /= M
88
+ adv = q_data - v
89
+ # Standardise the advantage before exponentiating. Measured on this
90
+ # corpus the raw advantage has std ~8, so at beta=3 the exponent is
91
+ # ~24 per standard deviation: every positive sample saturates the
92
+ # clip and every negative one underflows to zero. The "soft" weight
93
+ # degenerates into a hard sign filter that throws away half the data
94
+ # and hands the decision entirely to the critic's sign -- whose
95
+ # held-out action win rate is only 0.568. That is why AWR moved the
96
+ # IQL arm from 0.470 down to 0.380. Standardising makes beta mean
97
+ # what it is supposed to mean: weights span exp(+-beta) per sigma.
98
+ if args.adv_norm == "std":
99
+ adv = (adv - adv.mean()) / adv.std().clamp_min(1e-6)
100
+ w = (args.awr_beta * adv).exp().clamp(0, args.w_max)
101
+ w = w / w.mean().clamp_min(1e-6)
102
+ # AWR on a flow policy weights the PER-SAMPLE flow-matching loss, since
103
+ # a flow head has no tractable log-density.
104
+ loss = (w * policy_nll(new, zp, b["task"], b["a"], reduce=False)).mean()
105
+ opt.zero_grad(); loss.backward()
106
+ torch.nn.utils.clip_grad_norm_(new.parameters(), 1.0); opt.step()
107
+ if step % 500 == 0:
108
+ rec = {"step": step, "loss": float(loss), "mean_abs_adv": float(adv.abs().mean()),
109
+ "adv_std": float(adv.std()), "w_max_batch": float(w.max())}
110
+ stats.append(rec)
111
+ print(f"[awr] {step} loss={rec['loss']:.3f} |adv|={rec['mean_abs_adv']:.4f} "
112
+ f"adv_std={rec['adv_std']:.4f} w_max={rec['w_max_batch']:.2f}", flush=True)
113
+ new.eval()
114
+ return new, stats
115
+
116
+
117
+ @torch.no_grad()
118
+ def offline_score(d, enc, pol, rng, device, n=4096, pfeat=None):
119
+ """Offline proxies, reported together and never individually as a win:
120
+ bc_nll_succ : negative log-likelihood of SUCCESSFUL logged chunks
121
+ act_gap : how much more likely a success chunk is than a failure chunk
122
+ Neither is closed-loop success; they are screens, not the result."""
123
+ ok = np.array([e for e in d.val_eps if d.ep_success[e]], dtype=np.int64)
124
+ bad = np.array([e for e in d.val_eps if not d.ep_success[e]], dtype=np.int64)
125
+ def nll(pool):
126
+ # A demonstrations-only cache has no failures at all, so this pool is
127
+ # empty; report nan rather than indexing with an empty float array.
128
+ if len(pool) == 0:
129
+ return float("nan")
130
+ w = d.ep_len[pool].astype(np.float64); w /= w.sum()
131
+ e = rng.choice(pool, size=n, p=w)
132
+ lo, hi = d.ep_from[e], d.ep_to[e]
133
+ t = lo + (rng.random(n) * (hi - lo)).astype(np.int64)
134
+ x = torch.from_numpy(d._feat(t)).to(device)
135
+ a = torch.from_numpy(d._chunk_at(t, e)).to(device)
136
+ tk = torch.from_numpy(d.ep_task[e]).long().to(device)
137
+ return float(policy_nll(pol, (enc if pfeat is None else pfeat)(x), tk, a))
138
+ s, f = nll(ok), nll(bad)
139
+ return {"bc_nll_success": s, "bc_nll_failure": f, "act_gap": f - s}
140
+
141
+
142
+ def main():
143
+ ap = argparse.ArgumentParser()
144
+ ap.add_argument("--cache", required=True)
145
+ ap.add_argument("--norm-pool", default="all", choices=["all", "demos"],
146
+ help="frames the feature statistics come from. demos is worth +0.15 closed-loop over rollout-dominated statistics.")
147
+
148
+ ap.add_argument("--q-pessimism", type=float, default=2.0,
149
+ help="subtract this many particle standard deviations from Q. "
150
+ "Probed on the deployed critic, the held-out within-task "
151
+ "action win rate goes 0.549 (0.0) -> 0.570 (2.0).")
152
+
153
+ ap.add_argument("--adv-norm", default="std", choices=["std", "none"],
154
+ help="standardise the advantage inside the AWR weight. "
155
+ "Without it beta is uninterpretable and the weight "
156
+ "collapses to a hard sign filter.")
157
+
158
+ ap.add_argument("--init-pool", default="succ",
159
+ choices=["succ", "demos", "demos_succ", "all"],
160
+ help="episodes the pi_0 clone is fit on. Both critic arms must "
161
+ "use the SAME value or the comparison measures the initialisation rather than the critic.")
162
+
163
+ ap.add_argument("--lr", type=float, default=3e-4)
164
+
165
+ ap.add_argument("--feat-scale", default="zscore", choices=["zscore", "center"],
166
+ help="how the POLICY sees the observation. zscore matches the "
167
+ "lane BC recipe that reaches 0.584; center keeps relative "
168
+ "dim importance. Ranked on held-out sampled action MSE, "
169
+ "never on the CFM loss.")
170
+
171
+ ap.add_argument("--critic", required=True)
172
+ ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"],
173
+ help="what the POLICY reads. raw = the full 4104-d observation "
174
+ "(what a BC baseline sees); latent = the critic's "
175
+ "reward-predictive bottleneck, which discards action "
176
+ "detail and produced the 0%% closed-loop cliff. The "
177
+ "ADVANTAGE always comes from the critic latent either way.")
178
+
179
+ ap.add_argument("--out", required=True)
180
+ ap.add_argument("--rounds", type=int, default=2)
181
+ ap.add_argument("--batch", type=int, default=256)
182
+ ap.add_argument("--beta-q", type=float, default=0.98)
183
+ ap.add_argument("--gamma", type=float, default=0.99)
184
+ ap.add_argument("--depth", type=int, default=2)
185
+ ap.add_argument("--particles", type=int, default=8)
186
+ ap.add_argument("--awr-beta", type=float, default=1.0)
187
+ ap.add_argument("--w-max", type=float, default=20.0)
188
+ ap.add_argument("--awr-steps", type=int, default=4000)
189
+ ap.add_argument("--bc-steps", type=int, default=8000)
190
+ ap.add_argument("--ratio-steps", type=int, default=4000)
191
+ ap.add_argument("--wend-steps", type=int, default=4000)
192
+ ap.add_argument("--use-is", type=int, default=1)
193
+ ap.add_argument("--chunk", type=int, default=10,
194
+ help="MUST match the critic's training chunk; the action\n dim is chunk*7 and a mismatch silently breaks loading")
195
+ ap.add_argument("--ratio-chunk", type=int, default=0,
196
+ help="action length the IS ratio scores; 0 = same as --chunk. "
197
+ "Set to the BEHAVIOUR POLICY decision period (10 for pi0.5). "
198
+ "The occupancy may condition on a much longer window; the "
199
+ "ratio is a product over DECISIONS and must not.")
200
+ ap.add_argument("--success-gamma", type=float, default=0.98,
201
+ help="discount for reward-mode=soft: the label is "
202
+ "success_gamma ** (frames until success)")
203
+ ap.add_argument("--reward-mode", default="dense", choices=["dense","terminal","soft"],
204
+ help="dense = P(task succeeds|z), every frame of a success is a "
205
+ "positive (~50%%). terminal = last k frames only (~0.5%%), which "
206
+ "leaves Q near-constant in the action.")
207
+ ap.add_argument("--seed", type=int, default=0)
208
+ ap.add_argument("--in-ram", type=int, default=1)
209
+ ap.add_argument("--policy-family", default="concat", choices=["concat", "flow", "gauss"])
210
+ ap.add_argument("--awr-pool", default="all", choices=["all", "succ", "demos"],
211
+ help="which episodes AWR regresses on; 'succ' isolates dilution")
212
+ ap.add_argument("--ratio-smooth", type=float, default=0.0,
213
+ help="Gaussian kernel width applied to BOTH action classes before "
214
+ "the ratio classifier; buys overlap at the cost of a blurred ratio")
215
+ args = ap.parse_args()
216
+ args.use_is = bool(args.use_is)
217
+
218
+ # Seed torch too, not just numpy: the policy head init and the
219
+ # flow-matching noise are torch RNG. Without this two arms meant to
220
+ # differ in ONE flag start from different policies -- observed as
221
+ # pi_0 separation gaps of 0.0170 (IS on) vs 0.0089 (IS off).
222
+ torch.manual_seed(args.seed)
223
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
224
+ out = Path(args.out); out.mkdir(parents=True, exist_ok=True)
225
+ d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed,
226
+ in_ram=bool(args.in_ram), reward_mode=args.reward_mode,
227
+ success_gamma=getattr(args, 'success_gamma', 0.98),
228
+ norm_pool=args.norm_pool)
229
+ enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d)
230
+ args.d_z = cfg["d_z"]
231
+ pfeat, d_pol = policy_features(args, enc, d, cfg, dev)
232
+ print(f"[loop] policy reads {args.policy_features} ({d_pol}-d); "
233
+ f"advantage reads critic latent ({cfg['d_z']}-d)", flush=True)
234
+ rng = np.random.default_rng(args.seed + 23)
235
+
236
+ pol = train_bc(d, enc, args, dev, only_success=args.init_pool, steps=args.bc_steps,
237
+ pfeat=pfeat, d_policy=d_pol,
238
+ resume_path=str(Path(args.out) / 'bc_resume.pt'))
239
+ # Continuation policy for the recursion only (critic-latent space). Cheap:
240
+ # it never has to be a good controller, only a plausible next-action model
241
+ # so the imagined hops stay on the behaviour manifold.
242
+ cont_pol = (pol if args.policy_features != "raw"
243
+ else train_bc(d, enc, args, dev, only_success=True,
244
+ steps=max(args.bc_steps // 6, 2000),
245
+ pfeat=enc, d_policy=cfg["d_z"]))
246
+ log = {"config": vars(args), "rounds": []}
247
+ log["pi_0"] = offline_score(d, enc, pol, rng, dev, pfeat=pfeat)
248
+ print(f"[loop] pi_0 {log['pi_0']}", flush=True)
249
+
250
+ for r in range(1, args.rounds + 1):
251
+ if args.use_is:
252
+ # Re-fit every round: the target policy has moved, and a stale ratio
253
+ # silently evaluates the wrong policy.
254
+ print(f"=== round {r}: re-fit ratio for the CURRENT policy ===", flush=True)
255
+ ratio = train_ratio(d, enc, cont_pol, args, dev, steps=args.ratio_steps)
256
+ wend = train_endpoint_ratio(d, enc, ratio, args, dev, steps=args.wend_steps)
257
+ else:
258
+ # q_recursive ignores wend when use_is is False, so fitting it is
259
+ # pure waste in the ablation arm.
260
+ print(f"=== round {r}: IS off, skipping ratio fit ===", flush=True)
261
+ wend = None
262
+ pol, stats = awr_step(d, enc, pol, rew=rew, flow=flow, rms=rms, wend=wend,
263
+ args=args, device=dev, steps=args.awr_steps,
264
+ pfeat=pfeat, d_policy=d_pol, cont_pol=cont_pol)
265
+ sc = offline_score(d, enc, pol, rng, dev, pfeat=pfeat)
266
+ log["rounds"].append({"round": r, "awr": stats, "score": sc})
267
+ print(f"[loop] round {r} {sc}", flush=True)
268
+ torch.save({"pol": pol.state_dict(), "round": r, "config": vars(args)},
269
+ out / f"policy_r{r}.pt")
270
+ (out / "loop.json").write_text(json.dumps(log, indent=2))
271
+ print(json.dumps(log["rounds"][-1]["score"], indent=2), flush=True)
272
+
273
+
274
+ if __name__ == "__main__":
275
+ main()
frozen/rsm_libero_freeze_20261002/bc_arm.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Behaviour-cloning arms: the bars an RSM recipe has to clear.
2
+
3
+ Two pools, one script:
4
+ --pool demos -> A_bc_demos, cloning the 500 human demonstrations. This is the
5
+ headline baseline: the lane's own bcdemos bar is 0.584.
6
+ --pool succ -> B_bc_succ, cloning the SUCCESSFUL rollouts of the behaviour
7
+ policy. This is behaviour-policy extraction with no critic at
8
+ all, which is what "RSM adds value" has to beat.
9
+
10
+ No critic is loaded when the policy reads raw features, so these arms are
11
+ independent of the RSM run and can train in parallel with it. The policy class,
12
+ chunk, optimiser and seed are identical to the AWR arms so the only thing that
13
+ differs across the four arms is where the improvement signal comes from.
14
+ """
15
+ from __future__ import annotations
16
+ import sys as _sys, os as _os
17
+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
18
+ import argparse, json
19
+ from pathlib import Path
20
+ import numpy as np
21
+ import torch
22
+
23
+ from data import LiberoRSMData
24
+ from is_ope import train_bc, policy_features
25
+ from awr import offline_score
26
+
27
+
28
+ def main():
29
+ ap = argparse.ArgumentParser()
30
+ ap.add_argument("--cache", required=True)
31
+ ap.add_argument("--norm-pool", default="all", choices=["all", "demos"],
32
+ help="frames the feature statistics come from. demos is worth +0.15 closed-loop over rollout-dominated statistics.")
33
+
34
+ ap.add_argument("--lr", type=float, default=3e-4)
35
+
36
+ ap.add_argument("--feat-scale", default="zscore", choices=["zscore", "center"],
37
+ help="how the POLICY sees the observation. zscore matches the "
38
+ "lane BC recipe that reaches 0.584; center keeps relative "
39
+ "dim importance. Ranked on held-out sampled action MSE, "
40
+ "never on the CFM loss.")
41
+
42
+ ap.add_argument("--out", required=True)
43
+ ap.add_argument("--pool", required=True,
44
+ choices=["demos", "succ", "rollsucc", "rollsucc_mix", "demos_succ", "all"],
45
+ help="rollsucc = successful ROLLOUTS with demos excluded; "
46
+ "succ silently includes all 500 demos.")
47
+ ap.add_argument("--critic", default="",
48
+ help="only needed when --policy-features latent")
49
+ ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"])
50
+ ap.add_argument("--policy-family", default="concat", choices=["concat", "flow", "gauss"])
51
+ ap.add_argument("--chunk", type=int, default=10)
52
+ ap.add_argument("--pol-width", type=int, default=1024, help="policy MLP width (1024 -> 7.7M params; 3072x8 -> ~90M)")
53
+ ap.add_argument("--pol-depth", type=int, default=4)
54
+ ap.add_argument("--demo-weight", type=float, default=1.0,
55
+ help="sampling weight multiplier for demonstration episodes in a mixed pool")
56
+ ap.add_argument("--save-every", type=int, default=0,
57
+ help="save policy_s<step>.pt every N steps (checkpoint selection on validation inits)")
58
+ ap.add_argument("--bc-steps", type=int, default=30000)
59
+ ap.add_argument("--batch", type=int, default=1024)
60
+ ap.add_argument("--in-ram", type=int, default=0)
61
+ ap.add_argument("--success-gamma", type=float, default=0.98,
62
+ help="discount for reward-mode=soft: the label is "
63
+ "success_gamma ** (frames until success)")
64
+ ap.add_argument("--reward-mode", default="dense", choices=["dense", "terminal", "soft"])
65
+ ap.add_argument("--demos-per-task", type=int, default=5,
66
+ help="pool=rollsucc_mix only: demonstrations added per task on top "
67
+ "of the rollout successes. 0 reduces to pool=rollsucc.")
68
+ ap.add_argument("--success-mask", default="",
69
+ help="npz with keep[] from merge_verify.py. Drops logged successes whose replay did not reproduce.")
70
+ ap.add_argument("--eps-per-task", type=int, default=0,
71
+ help="cap distinct initial conditions per task (0 = all). Each "
72
+ "episode is an independent BDDL draw, so this is a direct "
73
+ "coverage-density knob at FIXED data quality.")
74
+ ap.add_argument("--qfilter-frac", type=float, default=0.0,
75
+ help="clone only the top fraction of each oversampled batch "
76
+ "by critic advantage (the port's qfilter_frac=0.25). "
77
+ "Requires --critic. A third way to use the critic: data "
78
+ "selection, not action selection or gradient weighting.")
79
+ ap.add_argument("--beta-q", type=float, default=0.98)
80
+ ap.add_argument("--seed", type=int, default=0)
81
+ ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", ""),
82
+ help="W&B entity; '' (default) = no W&B. rsm_rise sets RSM_WANDB_ENTITY via wandb_env.sh.")
83
+ ap.add_argument("--wandb-project", default=_os.environ.get("RSM_WANDB_PROJECT", "rsm_rise"))
84
+ ap.add_argument("--wandb-name", default="", help="run name (default: basename of --out)")
85
+ ap.add_argument("--wandb-mode", default="online", choices=["online", "offline", "disabled"])
86
+ args = ap.parse_args()
87
+
88
+ # ---- W&B (same pattern as train_rsm.py: off unless RSM_WANDB_ENTITY is set; run id from --out) ----
89
+ if args.wandb_entity and args.wandb_mode != "disabled":
90
+ try:
91
+ import wandb, hashlib
92
+ import is_ope as _isope
93
+ _rid = hashlib.md5(str(Path(args.out).resolve()).encode()).hexdigest()[:16]
94
+ _isope.WANDB_RUN = wandb.init(entity=args.wandb_entity, project=args.wandb_project,
95
+ name=args.wandb_name or Path(args.out).name, id=_rid,
96
+ resume="allow", mode=args.wandb_mode, config=vars(args),
97
+ dir=str(Path(args.out)))
98
+ print(f"[bc_arm] wandb: {_isope.WANDB_RUN.url}", flush=True)
99
+ except Exception as e:
100
+ print(f"[bc_arm] wandb disabled: {e}", flush=True)
101
+
102
+ torch.manual_seed(args.seed)
103
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
104
+ d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed,
105
+ in_ram=bool(args.in_ram), reward_mode=args.reward_mode,
106
+ success_gamma=getattr(args, 'success_gamma', 0.98),
107
+ norm_pool=args.norm_pool,
108
+ success_mask=getattr(args, 'success_mask', '') or '')
109
+
110
+ enc, cfg = None, {"d_z": 0}
111
+ if args.policy_features == "latent":
112
+ if not args.critic:
113
+ raise SystemExit("--policy-features latent needs --critic")
114
+ from is_ope import load_critic
115
+ enc, _r, _f, _rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task,
116
+ dev, data=d)
117
+ args.d_z = cfg["d_z"]
118
+ pfeat, d_pol = policy_features(args, enc, d, cfg, dev)
119
+ print(f"[bc_arm] pool={args.pool} eps={d.n_ep} chunk={d.chunk} "
120
+ f"policy reads {args.policy_features} ({d_pol}-d)", flush=True)
121
+
122
+ Path(args.out).mkdir(parents=True, exist_ok=True)
123
+ pool = {"demos": "demos", "succ": True, "rollsucc": "rollsucc",
124
+ "rollsucc_mix": "rollsucc_mix",
125
+ "demos_succ": "demos_succ", "all": False}[args.pool]
126
+ pol = train_bc(d, enc, args, dev, only_success=pool, steps=args.bc_steps,
127
+ pfeat=pfeat, d_policy=d_pol,
128
+ resume_path=str(Path(args.out) / 'bc_resume.pt'))
129
+
130
+ # Save FIRST: a defect in the offline proxies must never discard an hour of
131
+ # training that already produced a usable policy.
132
+ out = Path(args.out); out.mkdir(parents=True, exist_ok=True)
133
+ torch.save({"pol": pol.state_dict(), "round": 1, "config": vars(args),
134
+ "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")},
135
+ out / "policy_r1.pt")
136
+ rng = np.random.default_rng(args.seed + 23)
137
+ sc = offline_score(d, enc, pol, rng, dev, pfeat=pfeat)
138
+ sc["sampled_action_mse"] = getattr(pol, "best_sampled_mse", float("nan"))
139
+ print(f"[bc_arm] {args.pool} {sc}", flush=True)
140
+ (out / "loop.json").write_text(json.dumps(
141
+ {"config": vars(args), "pi_0": sc, "rounds": []}, indent=2))
142
+ import is_ope as _isope
143
+ if _isope.WANDB_RUN is not None:
144
+ try:
145
+ _isope.WANDB_RUN.log({f"final/{k}": v for k, v in sc.items() if isinstance(v, (int, float))})
146
+ _isope.WANDB_RUN.finish()
147
+ except Exception as e:
148
+ print(f"[bc_arm] wandb finish failed: {e}", flush=True)
149
+ print("[bc_arm] DONE", flush=True)
150
+
151
+
152
+ if __name__ == "__main__":
153
+ main()
frozen/rsm_libero_freeze_20261002/calib_dwm.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Temperature calibration of a DWM checkpoint's dense reward head on HELD-OUT frames (orchestrator, 13:20 UTC).
2
+
3
+ Fits a scalar T minimising BCE(sigmoid(logit / T), dense label) over the val episodes' frames (EMA head on real
4
+ frames, z-scored tokens/proprio exactly as in training) and writes <ckpt dir>/calib.json:
5
+ {T, ckpt, step, n_val, bce_before, bce_after, ece_before, ece_after, frac_p_gt_0.99_before/after, label_rate,
6
+ train: {same numbers on a train-frame sample}}.
7
+ DWMCritic then uses q = mean_i sigmoid(logit_i / T) (load_critic_dwm reads calib.json). T >> 1 = overconfident head.
8
+
9
+ python calib_dwm.py --cache cache/<task> --ckpt runs/<task>/rsm/DWM/ckpt_best.pt [--max-frames 20000]
10
+ """
11
+ from __future__ import annotations
12
+ import sys as _sys, os as _os
13
+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
14
+ import argparse, json, time
15
+ from pathlib import Path
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn.functional as F
19
+
20
+ from dwm_model import TokenRSMData
21
+ from dwm_readout import load_critic_dwm
22
+ from train_rsm import auc
23
+
24
+
25
+ def ece(p, y, n_bins=15):
26
+ p = np.asarray(p, np.float64); y = np.asarray(y, np.float64)
27
+ bins = np.linspace(0, 1, n_bins + 1); e = 0.0
28
+ for lo, hi in zip(bins[:-1], bins[1:]):
29
+ m = (p > lo) & (p <= hi) if lo > 0 else (p >= lo) & (p <= hi)
30
+ if m.any():
31
+ e += m.mean() * abs(p[m].mean() - y[m].mean())
32
+ return float(e)
33
+
34
+
35
+ def fit_T(logit, y, iters=200):
36
+ """1-D BCE minimisation over log T (Newton-free: golden-section on [1/16, 64])."""
37
+ lo, hi = np.log(1 / 16), np.log(64.0)
38
+ f = lambda t: float(F.binary_cross_entropy_with_logits(logit / np.exp(t), y))
39
+ r = (np.sqrt(5) - 1) / 2
40
+ a, b = lo, hi; c = b - r * (b - a); d = a + r * (b - a); fc, fd = f(c), f(d)
41
+ for _ in range(iters):
42
+ if fc < fd:
43
+ b, d, fd = d, c, fc; c = b - r * (b - a); fc = f(c)
44
+ else:
45
+ a, c, fc = c, d, fd; d = a + r * (b - a); fd = f(d)
46
+ if b - a < 1e-5:
47
+ break
48
+ return float(np.exp((a + b) / 2))
49
+
50
+
51
+ def stats(logit, y, T):
52
+ p = torch.sigmoid(logit / T).cpu().numpy(); yn = y.cpu().numpy()
53
+ return {"bce": float(F.binary_cross_entropy_with_logits(logit / T, y)), "ece": ece(p, yn),
54
+ "frac_p_gt_0.99": float((p > 0.99).mean()), "frac_p_gt_0.9": float((p > 0.9).mean()),
55
+ "mean_p": float(p.mean()), "auc": auc(p, yn),
56
+ "mean_p_on_label0": float(p[yn < 0.5].mean()) if (yn < 0.5).any() else float("nan"),
57
+ "mean_p_on_label1": float(p[yn > 0.5].mean()) if (yn > 0.5).any() else float("nan")}
58
+
59
+
60
+ @torch.no_grad()
61
+ def logits_on(crit, d, idx, dev, bs=1024):
62
+ out = []
63
+ for i in range(0, len(idx), bs):
64
+ sl = idx[i:i + bs]
65
+ tok = torch.from_numpy(d._tok(sl)).to(dev); pr = torch.from_numpy(d._pr(sl)).to(dev)
66
+ tz, pz = crit.norm.tok(tok), crit.norm.pr(pr)
67
+ with crit.autocast():
68
+ out.append(crit.rew(tz, pz).float())
69
+ return torch.cat(out)
70
+
71
+
72
+ def main():
73
+ ap = argparse.ArgumentParser()
74
+ ap.add_argument("--cache", required=True); ap.add_argument("--ckpt", required=True)
75
+ ap.add_argument("--reward-mode", default="dense"); ap.add_argument("--seed", type=int, default=0)
76
+ ap.add_argument("--max-frames", type=int, default=20000); ap.add_argument("--out", default="")
77
+ a = ap.parse_args()
78
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
79
+ d = TokenRSMData(a.cache, chunk=8, seed=a.seed, reward_mode=a.reward_mode)
80
+ crit = load_critic_dwm(a.ckpt, dev, calib=None)
81
+ rng = np.random.default_rng(a.seed)
82
+ val_idx = np.concatenate([np.arange(d.ep_from[e], d.ep_to[e]) for e in d.val_eps])
83
+ tr_idx = np.concatenate([np.arange(d.ep_from[e], d.ep_to[e]) for e in d.train_eps])
84
+ if len(val_idx) > a.max_frames:
85
+ val_idx = np.sort(rng.choice(val_idx, a.max_frames, replace=False))
86
+ tr_idx = np.sort(rng.choice(tr_idx, min(a.max_frames, len(tr_idx)), replace=False))
87
+ t0 = time.time()
88
+ lv = logits_on(crit, d, val_idx, dev); yv = torch.from_numpy(d.r[val_idx]).to(dev)
89
+ lt = logits_on(crit, d, tr_idx, dev); yt = torch.from_numpy(d.r[tr_idx]).to(dev)
90
+ T = fit_T(lv, yv)
91
+ rec = {"T": T, "ckpt": str(a.ckpt), "step": crit.step, "label": a.reward_mode, "n_val": int(len(val_idx)),
92
+ "n_train": int(len(tr_idx)), "label_rate_val": float(yv.mean()), "label_rate_train": float(yt.mean()),
93
+ "val_before": stats(lv, yv, 1.0), "val_after": stats(lv, yv, T),
94
+ "train_before": stats(lt, yt, 1.0), "train_after": stats(lt, yt, T),
95
+ "T_fit_on_train_for_reference": fit_T(lt, yt), "seconds": time.time() - t0}
96
+ for k in ("bce", "ece", "frac_p_gt_0.99"):
97
+ rec[f"{k}_before"] = rec["val_before"][k]; rec[f"{k}_after"] = rec["val_after"][k]
98
+ out = Path(a.out) if a.out else Path(a.ckpt).parent / "calib.json"
99
+ out.write_text(json.dumps(rec, indent=1))
100
+ print(f"[calib] T={T:.3f} val bce {rec['bce_before']:.4f}->{rec['bce_after']:.4f} ece {rec['ece_before']:.4f}->"
101
+ f"{rec['ece_after']:.4f} frac p>0.99 {rec['frac_p_gt_0.99_before']:.4f}->{rec['frac_p_gt_0.99_after']:.4f} "
102
+ f"(val auc {rec['val_before']['auc']:.4f}; train T_ref {rec['T_fit_on_train_for_reference']:.3f}) -> {out}", flush=True)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
frozen/rsm_libero_freeze_20261002/capture_cpu.sbatch ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --job-name=capfeat
3
+ #SBATCH --account=vision-pulkitag
4
+ #SBATCH --qos=tig-main
5
+ #SBATCH --partition=tig-cpu
6
+ # EXACTLY label_subgoals.sbatch's resources. 8 cpus / 40G was CANCELLED by uid 0
7
+ # three seconds in, with no output file ever created -- indistinguishable from a
8
+ # crash. groenig nodes are 16 cpu / 64298 MB, so --mem=64G is also rejected outright
9
+ # ("Memory specification can not be satisfied"). Do not widen these without testing.
10
+ #SBATCH --cpus-per-task=4 --mem=32G
11
+ #SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.out
12
+ #SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.err
13
+ set -uo pipefail
14
+ B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation
15
+ S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion
16
+ export REPO_PATH=$B/external/rlinf PYTHONPATH="$B/external/rlinf:${PYTHONPATH:-}"
17
+ export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard
18
+ # CPU rendering: only the FIRST observation of each episode is needed, so there is
19
+ # no rollout and no GPU. osmesa is the same backend verify_successes.py used.
20
+ export MUJOCO_GL=osmesa PYOPENGL_PLATFORM=osmesa
21
+ export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1
22
+ export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1
23
+ export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "")
24
+ export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN
25
+ export FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')"
26
+ export CUDA_VISIBLE_DEVICES=""
27
+ G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero
28
+ $B/venvs/rlinf-libero-eval-venv/bin/python $G/capture_init_feats.py \
29
+ --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \
30
+ --norm-pool demos --tasks "${TASKS:-0,1,2,3,4,6,7,8,9}" --n-init "${NINIT:-5}" \
31
+ --fresh "${FRESH:-0}" --out "${OUT:?set OUT}"
32
+ echo "[cap] rc=$? $(date -u +%T)"
frozen/rsm_libero_freeze_20261002/capture_init_feats.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture the evaluator's t=0 feature vector without rolling out.
2
+
3
+ The question this answers: are the features the closed-loop evaluator actually
4
+ feeds the policy in the DEMO region of the cache or the ROLLOUT region? It decides
5
+ whether a critic trained on a 90%-rollout corpus is read on-support at eval time.
6
+
7
+ Only the first observation of each episode is needed, so no policy and no GPU are
8
+ required -- reset, one zero step, encode, done. Uses the SAME featurization path as
9
+ eval_closed_loop.py (to224 quantisation, axis-angle proprio, cache normalisation);
10
+ any deviation would make the comparison meaningless.
11
+ """
12
+ from __future__ import annotations
13
+ import argparse, importlib.util, sys, os
14
+ from pathlib import Path
15
+ import numpy as np
16
+ import torch
17
+
18
+ HERE = Path(__file__).resolve().parent
19
+ sys.path.insert(0, str(HERE))
20
+ from eval_closed_loop import to224, _eef_ori, BUILDER # identical transforms
21
+
22
+ _spec = importlib.util.spec_from_file_location("ogpo_cap", BUILDER)
23
+ ogpo = importlib.util.module_from_spec(_spec)
24
+ sys.modules["ogpo_cap"] = ogpo
25
+ _spec.loader.exec_module(ogpo)
26
+
27
+
28
+ def main():
29
+ ap = argparse.ArgumentParser()
30
+ ap.add_argument("--cache", required=True, help="cache whose feat stats the policy used")
31
+ ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"])
32
+ ap.add_argument("--tasks", default="0,1,2,3,4,6,7,8,9")
33
+ ap.add_argument("--n-init", type=int, default=5)
34
+ ap.add_argument("--fresh", type=int, default=0)
35
+ ap.add_argument("--seed", type=int, default=0)
36
+ ap.add_argument("--out", required=True)
37
+ args = ap.parse_args()
38
+
39
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
40
+ print(f"[cap] device {dev}", flush=True)
41
+ tower = ogpo.build_paligemma(dev)
42
+ from libero.libero import benchmark, get_libero_path
43
+ from libero.libero.envs import OffScreenRenderEnv
44
+ bench = benchmark.get_benchmark_dict()["libero_10"]()
45
+
46
+ sname = "feat_stats.npz" if args.norm_pool == "all" else f"feat_stats_{args.norm_pool}.npz"
47
+ st = np.load(str(Path(args.cache) / sname))
48
+ nmu = torch.tensor(st["mu"], dtype=torch.float32, device=dev)
49
+ nsd = torch.tensor(st["sd"], dtype=torch.float32, device=dev)
50
+ print(f"[cap] normalisation {sname} dim={int(st['dim'])}", flush=True)
51
+
52
+ tasks, feats = [], []
53
+ for tid in [int(t) for t in args.tasks.split(",")]:
54
+ task = bench.get_task(tid)
55
+ ids = ogpo.tokenize_prompt(task.language)
56
+ inits = bench.get_task_init_states(tid)
57
+ env = OffScreenRenderEnv(
58
+ bddl_file_name=str(Path(get_libero_path("bddl_files"))
59
+ / task.problem_folder / task.bddl_file),
60
+ camera_heights=128, camera_widths=128)
61
+ for k in range(args.n_init):
62
+ np.random.seed(args.seed * 100003 + tid * 1009 + k)
63
+ if hasattr(env, "seed"):
64
+ env.seed(args.seed * 100003 + tid * 1009 + k)
65
+ env.reset()
66
+ if not args.fresh:
67
+ env.set_init_state(inits[k % len(inits)])
68
+ obs, _, _, _ = env.step(np.zeros(7))
69
+ cams = []
70
+ for key in ("agentview_image", "robot0_eye_in_hand_image"):
71
+ cams.append(to224(obs[key][::-1, ::-1])[None])
72
+ z = np.concatenate(
73
+ [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0]
74
+ prop = np.concatenate([
75
+ obs["robot0_eef_pos"], _eef_ori(obs), obs["robot0_gripper_qpos"],
76
+ ]).astype(np.float32)
77
+ x = torch.tensor(np.concatenate([z, prop])[None], dtype=torch.float32, device=dev)
78
+ x = (x - nmu) / nsd
79
+ tasks.append(tid); feats.append(np.asarray(x[0].cpu(), np.float32))
80
+ print(f"[cap] task {tid} init {k}: |x|={float(x.norm()):.2f}", flush=True)
81
+ env.close()
82
+ np.savez_compressed(args.out, task=np.array(tasks), x=np.stack(feats),
83
+ norm_pool=args.norm_pool, fresh=args.fresh)
84
+ print(f"[cap] wrote {len(tasks)} features -> {args.out}", flush=True)
85
+
86
+
87
+ if __name__ == "__main__":
88
+ main()
frozen/rsm_libero_freeze_20261002/crn_diag.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Does the Q arg-max over N near-copy candidates track the critic or the Monte-Carlo
2
+ noise? Score the same N candidates twice with fresh seeds, with independent draws and
3
+ with common random numbers (crn), and report arg-max agreement and the ratio of
4
+ between-candidate Q spread to between-seed Q noise. CPU/GPU, no env.
5
+ usage: crn_diag.py --critic ckpt --policy proposer.pt --hop hop.pt [--depth 3] [--n 8] [--states 200]
6
+ """
7
+ import argparse, numpy as np, torch
8
+ from data import LiberoRSMData
9
+ from is_ope import load_critic, q_recursive, make_policy
10
+ from eval_closed_loop import load_policy, _resolve_cache
11
+
12
+ ap = argparse.ArgumentParser()
13
+ ap.add_argument("--critic", required=True); ap.add_argument("--policy", required=True)
14
+ ap.add_argument("--hop", default=""); ap.add_argument("--depth", type=int, default=3)
15
+ ap.add_argument("--n", type=int, default=8); ap.add_argument("--states", type=int, default=200)
16
+ ap.add_argument("--particles", type=int, default=16); ap.add_argument("--beta", type=float, default=0.98)
17
+ a = ap.parse_args()
18
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
19
+ pcfg = torch.load(a.policy, map_location="cpu", weights_only=False)["config"]
20
+ d = LiberoRSMData(_resolve_cache(pcfg["cache"]), chunk=pcfg.get("chunk", 10), seed=0, in_ram=False,
21
+ reward_mode="dense", norm_pool=pcfg.get("norm_pool", "all"))
22
+ pfeat, pol, chunk, ccfg, pmode, d_lat, _ = load_policy(a.critic, a.policy, d.n_task, dev)
23
+ q_enc, q_rew, q_flow, q_rms, q_cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d)
24
+ hop = None
25
+ if a.depth >= 2:
26
+ hk = torch.load(a.hop, map_location=dev, weights_only=False)
27
+ hop = make_policy(hk["config"], d, dev, d_z=q_cfg["d_z"]); hop.load_state_dict(hk["pol"]); hop.eval()
28
+ rng = np.random.default_rng(0)
29
+ # demo frames from the pool the proposer was trained on
30
+ eps = np.where(d.ep_demo)[0]; rows = []
31
+ tasks = []
32
+ for e in rng.choice(eps, size=a.states, replace=True):
33
+ s, l = int(d.ep_from[e]), int(d.ep_len[e]); rows.append(s + int(rng.integers(0, max(1, l - chunk)))); tasks.append(int(d.ep_task[e]))
34
+ agree = {0: [], 1: []}; ratio = {0: [], 1: []}; agree_x = []
35
+ with torch.no_grad():
36
+ for i, ti in zip(rows, tasks):
37
+ x = torch.as_tensor(d._feat(i)[None], device=dev).float(); tt = torch.tensor([ti], device=dev)
38
+ torch.manual_seed(1234 + i)
39
+ cand = pol.sample(pfeat(x).expand(a.n, -1), tt.expand(a.n))
40
+ z = q_enc(x).expand(a.n, -1)
41
+ qs = {}
42
+ for crn in (0, 1):
43
+ out = []
44
+ for seed in (1, 2):
45
+ torch.manual_seed(seed)
46
+ q, _ = q_recursive(z, cand, tt.expand(a.n), rew=q_rew, flow=q_flow, rms=q_rms, pol=hop,
47
+ wend=None, beta=a.beta, gamma=0.99, depth=a.depth, n_particles=a.particles,
48
+ use_is=False, crn=bool(crn))
49
+ out.append(q.cpu().numpy())
50
+ q1, q2 = out; qs[crn] = (q1, q2)
51
+ agree[crn].append(float(q1.argmax() == q2.argmax()))
52
+ spread = 0.5 * (q1.std() + q2.std()); noise = np.abs(q1 - q2).mean() / np.sqrt(2)
53
+ ratio[crn].append(spread / max(noise, 1e-9))
54
+ agree_x.append(float(qs[0][0].argmax() == qs[1][0].argmax()))
55
+ for crn in (0, 1):
56
+ print(f"crn={crn}: argmax agreement across seeds {np.mean(agree[crn]):.3f} "
57
+ f"median (between-candidate spread / between-seed noise) {np.median(ratio[crn]):.2f}")
58
+ print(f"chance agreement = {1/a.n:.3f}; independent-vs-crn argmax agreement {np.mean(agree_x):.3f}")
frozen/rsm_libero_freeze_20261002/data.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch sampling over the packed LIBERO-10 rollout cache."""
2
+ from __future__ import annotations
3
+ from pathlib import Path
4
+ import json as _json # was only imported inside the cam_res loop below, so the encoder
5
+ # tag lookup (which runs first) always hit NameError and kept the
6
+ # legacy default; importing it here makes PACK.json's encoder tag load
7
+ import numpy as np
8
+ import torch
9
+
10
+
11
+ def truncated_geometric_future(rows, ep_ends, discounts, uniforms):
12
+ """Ported verbatim from gen_q ogbench_genq/rsm.py (via the CLM fast-critic port).
13
+
14
+ Draws k ~ Geom(1-discount) truncated to the episode end, so the sampled future
15
+ is always a REAL logged frame -- the Monte-Carlo occupancy target with no
16
+ bootstrap anywhere.
17
+ """
18
+ length = (ep_ends - rows)
19
+ log_d = np.log(discounts)
20
+ finite_mass = np.maximum(1.0 - np.exp(length * log_d), 1e-12)
21
+ offset = np.ceil(np.log1p(-uniforms * finite_mass) / log_d).astype(np.int64) - 1
22
+ offset = np.clip(offset, 0, length - 1)
23
+ return rows + offset
24
+
25
+
26
+ class LiberoRSMData:
27
+ def __init__(self, root, chunk: int = 10, k_success: int = 10,
28
+ val_frac: float = 0.1, seed: int = 0, in_ram: bool = True,
29
+ success_mask: str = "",
30
+ subgoal_dir: str = "",
31
+ reward_mode: str = "dense", success_gamma: float = 0.98,
32
+ reward_npy: str = "",
33
+ weight_npy: str = "",
34
+ normalize: bool = True,
35
+ norm_pool: str = "all",
36
+ stratify_success: bool = False,
37
+ action_augment: float = 0.0,
38
+ augment_mode: str = "contrastive",
39
+ augment_table: str = "",
40
+ augment_neighbors: int = 15,
41
+ augment_frac_cap: float = 0.0):
42
+ root = Path(root)
43
+ self.root = root
44
+ m = np.load(root / "meta.npz", allow_pickle=True)
45
+ self.z = np.load(root / "z.f16.npy", mmap_mode="r")
46
+ self.act = np.load(root / "act.f32.npy", mmap_mode="r")
47
+ pp = root / "proprio.f32.npy"
48
+ self.proprio = np.load(pp, mmap_mode="r") if pp.exists() else None
49
+ # Measured on this corpus: over 5 frames the executed action correlates
50
+ # with the PROPRIO delta at max |r| 0.98, but with the visual-latent delta
51
+ # at only 0.49 (mean 0.10). A mean-pooled PaliGemma embedding barely
52
+ # resolves the motion a 10-step chunk produces, which is why the occupancy
53
+ # could rank states (0.66-0.69 AUC) but never actions (~chance pooled).
54
+ # Concatenating proprio puts the action-sensitive channel INTO the latent
55
+ # the successor has to predict.
56
+ self.use_proprio = self.proprio is not None
57
+ if in_ram:
58
+ # training draws ~512 RANDOM rows per step; over NFS that is 512
59
+ # separate 8 kB reads and caps throughput at a few it/s. The cache is
60
+ # small enough to hold, so pull it in once.
61
+ gb = self.z.nbytes / 1e9
62
+ print(f"[data] loading {gb:.1f} GB of latents into RAM", flush=True)
63
+ self.z = np.ascontiguousarray(self.z)
64
+ self.act = np.ascontiguousarray(self.act)
65
+ if self.proprio is not None:
66
+ self.proprio = np.ascontiguousarray(self.proprio)
67
+ self.ep_from = m["ep_from"]; self.ep_to = m["ep_to"]; self.ep_len = m["ep_len"]
68
+ self.ep_task = m["ep_task"]; self.ep_success = m["ep_success"]
69
+ # ADMISSIBILITY (see CLAUDE.md): a logged success whose actions do not
70
+ # reproduce in the eval environment is not a success here. Applied before any
71
+ # reward is built, so the critic never sees a progress curve toward an event
72
+ # that will not occur in the environment it is scored in.
73
+ if success_mask:
74
+ _keep = np.load(success_mask)["keep"].astype(bool)
75
+ _n0 = int(self.ep_success.sum())
76
+ self.ep_success = self.ep_success.astype(bool) & _keep
77
+ print(f"[data] admissibility mask: {_n0} -> {int(self.ep_success.sum())} "
78
+ f"successes ({_n0-int(self.ep_success.sum())} dropped as "
79
+ f"non-reproducing)", flush=True)
80
+ self.ep_demo = m["ep_demo"] if "ep_demo" in m else np.zeros(len(self.ep_task), bool)
81
+ # Declared render resolution of the latents (RENDER.json, else PACK.json). Stored
82
+ # into every checkpoint config so the evaluator can refuse a mismatch (i251).
83
+ self.cam_res = "UNKNOWN"
84
+ self.encoder = "pi05_base_pytorch" # legacy caches predate the tag
85
+ for _f in ("PACK.json", "RENDER.json"):
86
+ try:
87
+ _e = _json.load(open(f"{root}/{_f}")).get("encoder")
88
+ if _e: self.encoder = _e; break
89
+ except Exception:
90
+ pass
91
+ for _f in ("RENDER.json", "PACK.json"):
92
+ try:
93
+ _v = _json.load(open(f"{root}/{_f}")).get("cam_res")
94
+ if _v is not None:
95
+ self.cam_res = _v; break
96
+ except Exception:
97
+ pass
98
+ self.tasks = [str(t) for t in m["tasks"]]
99
+ self.dim = int(m["dim"]); self.adim = int(m["adim"])
100
+ self.chunk = chunk; self.k_success = k_success
101
+ self.n_task = len(self.tasks)
102
+ self.n_ep = len(self.ep_len)
103
+
104
+ # episode-level split: adjacent frames cannot leak across the boundary
105
+ rng = np.random.default_rng(seed)
106
+ n_val = max(1, int(val_frac * self.n_ep))
107
+ if stratify_success:
108
+ # STRATIFY ON ep_success (gen_q#261). An unstratified 10% split of the real cooking
109
+ # corpus put 2 of the 50 rewarded episodes in val. Under a sparse reward label that is
110
+ # 80 positive val frames, so a 256-anchor val eval draws well under one positive and the
111
+ # printed `val auc` is noise rather than evidence (measured: 0.9960 sampled vs 0.9983
112
+ # over the exact full split). Holding out the SAME FRACTION of rewarded and unrewarded
113
+ # episodes makes a held-out reward metric estimable at all. Off by default so every
114
+ # existing run's split is bit-identical.
115
+ _s = np.asarray(self.ep_success, bool)
116
+ _parts = []
117
+ for _grp in (np.nonzero(_s)[0], np.nonzero(~_s)[0]):
118
+ if len(_grp) == 0:
119
+ continue
120
+ _pg = _grp[rng.permutation(len(_grp))]
121
+ _k = max(1, int(round(val_frac * len(_grp)))) if len(_grp) > 1 else 0
122
+ _parts.append(_pg[:_k])
123
+ self.val_eps = np.sort(np.concatenate(_parts)) if _parts else np.array([], np.int64)
124
+ self.train_eps = np.sort(np.setdiff1d(np.arange(self.n_ep), self.val_eps))
125
+ print(f"[data] success-stratified split: {len(self.val_eps)} val "
126
+ f"({int(_s[self.val_eps].sum())} rewarded) / {len(self.train_eps)} train "
127
+ f"({int(_s[self.train_eps].sum())} rewarded)", flush=True)
128
+ else:
129
+ perm = rng.permutation(self.n_ep)
130
+ self.val_eps = np.sort(perm[:n_val])
131
+ self.train_eps = np.sort(perm[n_val:])
132
+
133
+ # Feature normalisation (see _feat for why this matters).
134
+ self.norm_mu = self.norm_sd = None
135
+ self.z_clip = 0.0 # set from feat_stats.npz (rsm_rise caches store z_clip=10)
136
+ self.norm_pool = norm_pool
137
+ if normalize:
138
+ self._fit_norm()
139
+
140
+ # ---- RISE-style COUNTERFACTUAL ACTION AUGMENTATION (rsm_rise AUG_SUCC, gen_q#279) ------
141
+ #
142
+ # WHY. This model only ever sees (s, a_logged, future) triples, so its value OFF the logged
143
+ # action at s is unconstrained. Measured consequence (status/real/RANK_CTRL.md): anchored
144
+ # inside a failure episode at the S2 junction it ranks the goal-bound chunk at the 23rd
145
+ # percentile, below its own permuted control. RISE's augmentation
146
+ # (rise_robomimic/robomimic/utils/dataset.py:build_state_augmentation_data) is built to
147
+ # supply exactly the missing pair: for state i it takes a neighbour j from a DIFFERENT
148
+ # trajectory within `distance_threshold` in STATE space and emits
149
+ # obs = i's obs | actions = j's action | rewards = j's reward | next_obs = i's OWN next_obs.
150
+ #
151
+ # TWO READINGS, both implemented, selected by `augment_mode`:
152
+ # "invariant" the literal transcription: the neighbour's action is asserted to lead to
153
+ # the ANCHOR's own occupancy. This trains INVARIANCE to the action over the
154
+ # neighbourhood. Safe only if the neighbourhood is strictly smaller than the
155
+ # action gap the value has to resolve -- measured by
156
+ # scripts/real/aug_feasibility.py, which reports the straddle fraction.
157
+ # "contrastive" the faithful lift of RISE's INTENT to an occupancy model: the counterfactual
158
+ # action carries the NEIGHBOUR's own future, so the read-out
159
+ # Qbar(s_anchor, a_neighbour) = E_{f ~ m(.|s_i,a_j)} r(f) reads the
160
+ # neighbour's route. This is the pair whose absence explains the failure above.
161
+ #
162
+ # WHY `contrastive` CANNOT BE "anchor's future + neighbour's reward label" HERE. The reward
163
+ # head in this architecture is a function of the STATE ALONE (model.py: rew(z, task)); the
164
+ # action enters only through the occupancy. Asserting the anchor's own future for the
165
+ # counterfactual action therefore makes Qbar(s_i, a_j) == Qbar(s_i, a_i) identically, and no
166
+ # relabelling of r can change it -- while overriding r at an unchanged x_now would be pure
167
+ # label noise on the one head that generalises. RISE escapes this because its contrastiveness
168
+ # lives in the r term of a one-step Q(s,a) <- r + gamma V(s'), which a state-only reward plus an
169
+ # action-conditioned occupancy cannot express while also asserting s' = s'_anchor.
170
+ # In BOTH modes the reward-head target r_now stays the ANCHOR's own label, for that reason.
171
+ #
172
+ # The RISE knobs carry over verbatim: `augment_neighbors` = num_neighbors (the cap is applied
173
+ # to the NEAREST different-episode frames FIRST, exactly as RISE does), `action_augment` =
174
+ # distance_threshold, different-trajectory-only and skip-self are baked into the table
175
+ # (scripts/real/build_aug_knn.py), which is built over the TRAIN episodes only.
176
+ #
177
+ # MIXING IS PROPORTIONAL, NOT ALTERNATING. RISE's `epoch % 2 == 0` scheme hands the augmented
178
+ # pool 50% of all gradient steps at ANY pool size (on one sim task a 14-row pool was replayed
179
+ # 457x per epoch). Here the per-row probability is n_aug_pairs / (n_aug_pairs + n_train_frames),
180
+ # so a starved pool contributes in proportion to its size and `aug_frac` reports the realised
181
+ # number every batch.
182
+ self.aug = None
183
+ self.aug_mode = augment_mode
184
+ self.aug_thr = float(action_augment)
185
+ self.aug_k = int(augment_neighbors)
186
+ self.aug_p = 0.0
187
+ self.aug_cap = 0.0
188
+ if self.aug_thr > 0:
189
+ if augment_mode not in ("contrastive", "invariant"):
190
+ raise ValueError(f"--augment-mode must be contrastive|invariant, got {augment_mode}")
191
+ tbl_path = augment_table or str(root / "aug_knn_feat.npz")
192
+ tbl = np.load(tbl_path, allow_pickle=True)
193
+ nbr_row = tbl["nbr_row"][:, : self.aug_k]
194
+ nbr_dist = tbl["nbr_dist"][:, : self.aug_k]
195
+ anc_row = tbl["rows"]
196
+ # the table must have been built on THIS split, or an augmented pair reaches into the
197
+ # held-out episodes through the action channel
198
+ t_train = set(int(x) for x in tbl["train_eps"]) if "train_eps" in tbl.files else None
199
+ if t_train is not None and t_train != set(int(x) for x in self.train_eps):
200
+ raise RuntimeError(
201
+ f"{tbl_path} was built on a DIFFERENT train split "
202
+ f"({len(t_train)} eps) than this run ({len(self.train_eps)} eps); "
203
+ f"rebuild it with matching --seed/--val-frac/--stratify-success")
204
+ keep = nbr_dist <= self.aug_thr
205
+ ai, aj = np.nonzero(keep)
206
+ self.aug_anchor = anc_row[ai].astype(np.int64)
207
+ self.aug_nbr = nbr_row[ai, aj].astype(np.int64)
208
+ self.aug_dist = nbr_dist[ai, aj].astype(np.float32)
209
+ n_pairs = len(self.aug_anchor)
210
+ n_frames_tr = int(sum(int(self.ep_to[e]) - int(self.ep_from[e]) for e in self.train_eps))
211
+ self.aug = n_pairs > 0
212
+ self.aug_p = n_pairs / max(n_pairs + n_frames_tr, 1)
213
+ # AUGMENTED-FRACTION CAP (AUG_SUCC run 5). Proportional mixing is the right default --
214
+ # RISE's `epoch % 2` alternation hands the augmented pool 50% of all gradient steps at ANY
215
+ # pool size, which on one sim task replayed a 14-row pool 457x per epoch. But at the other
216
+ # end it bites: on this corpus the k=15 pool is 15x the logged corpus, so proportional
217
+ # mixing put 93% of gradient steps on counterfactual rows, the logged pair (s_i, a_i) was
218
+ # seen on 7% of steps, and the 30k `contrastive` gate number came with an INVERTED
219
+ # own-chunk preference and a +30% minmse -- i.e. plausibly a chunk prior rather than
220
+ # goal-direction. `aug_frac`, not threshold, was the explanatory variable of that ladder.
221
+ # This cap is the one change that separates the two: it fixes the augmented share at a
222
+ # stated value (RISE's own scheme is 0.5) while leaving the pool, the pairing and the mode
223
+ # untouched. 0 = off = pure proportional, so every prior run reproduces bit-for-bit.
224
+ self.aug_cap = float(augment_frac_cap)
225
+ if self.aug_cap > 0:
226
+ self.aug_p = min(self.aug_p, self.aug_cap)
227
+ # global row -> episode index, needed to read the neighbour's episode bounds
228
+ self.row_ep = np.zeros(int(self.ep_to[-1]), np.int32)
229
+ for _e in range(self.n_ep):
230
+ self.row_ep[int(self.ep_from[_e]):int(self.ep_to[_e])] = _e
231
+ self._aug_rng = np.random.default_rng(seed + 777)
232
+ _cov = len(np.unique(self.aug_anchor)) / max(n_frames_tr, 1)
233
+ print(f"[data] action augmentation: metric={str(tbl['metric'])} "
234
+ f"mode={self.aug_mode} thr={self.aug_thr} k={self.aug_k} -> {n_pairs} pairs "
235
+ f"over {n_frames_tr} train frames ({_cov:.3%} of anchors get >=1), "
236
+ f"proportional mix p={self.aug_p:.4f}"
237
+ + (f" (CAPPED at {self.aug_cap:.3f})" if self.aug_cap > 0 else ""), flush=True)
238
+ if n_pairs == 0:
239
+ print("[data] STARVED: the threshold admits NO pairs; training is unchanged", flush=True)
240
+
241
+ # Per-frame reward label.
242
+ #
243
+ # "terminal": 1 on the last k frames of successful episodes. SPARSE --
244
+ # positives are ~0.5% of frames, so nearly every sampled future reads ~0,
245
+ # Q is near-constant in the action, and there is nothing to rank. This is
246
+ # the likely reason action ranking stayed near chance.
247
+ #
248
+ # "dense": 1 on EVERY frame of a successful episode, i.e. P(episode
249
+ # succeeds | z). Dense and well-posed, but it is an OUTCOME predictor and
250
+ # carries almost no action information: a supervised Q(z,a) beats a
251
+ # state-only V(z) by AUC 0.9550 vs 0.9539 (+0.0012). Whether an episode
252
+ # succeeds is a property of the state, not of the next 10 frames.
253
+ #
254
+ # "soft" (RECOMMENDED): gamma_s ** (frames until this episode's success),
255
+ # and 0 for episodes that never succeed. Both binary labels above are
256
+ # FLAT in the sense that matters -- neither varies with PROGRESS, so
257
+ # moving one chunk closer to the goal does not change the target, and an
258
+ # action therefore cannot move the value. The soft label is monotone in
259
+ # time-to-success, so it does. This is the fix the OCBench port
260
+ # identifies for exactly this symptom: its binary `indicator` target
261
+ # leaves the readout ~0 on almost every state (q_mean 0.02-0.07, "so the
262
+ # Q is flat") while the soft target raises q_mean to ~0.43 and "makes the
263
+ # readout vary with progress".
264
+ self.r = np.zeros(int(self.ep_to[-1]), dtype=np.float32)
265
+ # PER-FRAME REWARD-LOSS WEIGHT (gen_q #271 scheme C). A float32 [n_frames] array of
266
+ # non-negative sample weights for the reward BCE ONLY; 1.0 everywhere when unset, so the
267
+ # loss is bit-identical to the unweighted path. Scheme C puts w_neg on the frames whose
268
+ # reached_state_id is a failure terminal (S5/S6) to make them hard negatives.
269
+ self.w = None
270
+ if weight_npy:
271
+ _wv = np.load(weight_npy).astype(np.float32).ravel()
272
+ assert len(_wv) == len(self.r), (len(_wv), len(self.r))
273
+ assert (_wv >= 0).all(), "negative reward-loss weight"
274
+ self.w = _wv
275
+ print(f"[data] reward-loss weights {weight_npy}: mean w={self.w.mean():.4f}, "
276
+ f"{int((self.w != 1.0).sum())} reweighted frames of {len(self.w)}", flush=True)
277
+ if reward_npy:
278
+ # EXTERNAL PER-FRAME REWARD (rsm_rise #261 reward-head study). A float32 array of
279
+ # exactly n_frames entries replaces every rule above, so a label defined outside this
280
+ # file (e.g. the goal-transition label from the dataset's own per-frame stage
281
+ # annotations, scripts/real/make_goal_reward.py) is trained with a bit-identical
282
+ # pipeline to the provenance label. Nothing else changes.
283
+ _rv = np.load(reward_npy).astype(np.float32).ravel()
284
+ assert len(_rv) == len(self.r), (len(_rv), len(self.r))
285
+ self.r[:] = _rv
286
+ print(f"[data] external reward {reward_npy}: mean r={self.r.mean():.6f}, "
287
+ f"{int((self.r > 0).sum())} positive frames of {len(self.r)}", flush=True)
288
+ return
289
+ if reward_mode in ("subgoal", "subgoal_ind"):
290
+ # r(s) = satisfied BDDL conjuncts / K. A genuine function of the state:
291
+ # identical configurations get identical targets, and every frame of every
292
+ # episode is labelled -- including failures, which under the soft label
293
+ # contributed only zeros (50.5% of the corpus, no gradient at all).
294
+ import glob as _g
295
+ n_lab = 0
296
+ for _f in sorted(_g.glob(f"{subgoal_dir}/task*.npz")):
297
+ _z = np.load(_f, allow_pickle=True)
298
+ _K = int(_z["K"])
299
+ for _e, _v in zip(_z["ep"], _z["vals"]):
300
+ _a, _b = int(self.ep_from[_e]), int(self.ep_to[_e])
301
+ _v = np.asarray(_v, np.float32)
302
+ _v[_v < 0] = 0.0 # unresolvable -> no credit
303
+ _val = (_v >= _K).astype(np.float32) if reward_mode == "subgoal_ind" \
304
+ else _v / max(_K, 1)
305
+ self.r[_a:_a + min(len(_val), _b - _a)] = _val[:_b - _a]
306
+ n_lab += 1
307
+ # demonstrations complete the task by construction
308
+ for _i in np.where(self.ep_demo)[0]:
309
+ self.r[int(self.ep_from[_i]):int(self.ep_to[_i])] = 1.0
310
+ print(f"[data] {reward_mode} reward: {n_lab} rollouts labelled from "
311
+ f"{subgoal_dir}, mean r={self.r.mean():.4f}", flush=True)
312
+ return
313
+ for i in range(self.n_ep):
314
+ if not self.ep_success[i]:
315
+ continue
316
+ lo, hi = int(self.ep_from[i]), int(self.ep_to[i])
317
+ if reward_mode == "dense":
318
+ self.r[lo:hi] = 1.0
319
+ elif reward_mode == "soft":
320
+ # discounted time-to-success, measured from the last frame
321
+ n = hi - lo
322
+ self.r[lo:hi] = (success_gamma
323
+ ** np.arange(n - 1, -1, -1, dtype=np.float64)
324
+ ).astype(np.float32)
325
+ else:
326
+ self.r[max(lo, hi - k_success):hi] = 1.0
327
+
328
+ def _feat(self, idx):
329
+ """Observation every head sees: visual latent, optionally with proprio,
330
+ z-scored per dimension.
331
+
332
+ Normalisation is not cosmetic here. Measured on this corpus, the mean
333
+ feature vector has norm 51.1 while the per-frame deviation from it has
334
+ norm 9.0 -- 85% of the input magnitude is a constant offset carrying no
335
+ information, and the per-dim |mean|/std ratio is 3.14 median / 8.0 at p90.
336
+ Fed raw, the informative variation is a small perturbation riding on a
337
+ large common mode, which is exactly the conditioning an MLP handles
338
+ worst. Proprio is worse still: its per-dim std spans 0.014 to 1.372, so
339
+ the gripper channel is invisible next to the wrist angle.
340
+
341
+ Stats are computed once and cached in the cache directory so that
342
+ training and the closed-loop evaluator apply the IDENTICAL transform; a
343
+ policy evaluated under different statistics is off-distribution and
344
+ indistinguishable from a bad policy."""
345
+ z = np.asarray(self.z[idx], np.float32)
346
+ if self.proprio is not None:
347
+ z = np.concatenate([z, np.asarray(self.proprio[idx], np.float32)], -1)
348
+ if self.norm_mu is None:
349
+ return z
350
+ z = (z - self.norm_mu) / self.norm_sd
351
+ # rsm_rise STATE DEFINITION: x = clip((feat - mu) / max(sd, sd_floor), -z_clip, z_clip).
352
+ # A GeM channel whose patch tokens are almost always negative collapses to the 1e-6
353
+ # clamp on nearly every frame (sd ~1e-3) and then takes |x| = 30-70 on the few frames
354
+ # where it is not; the flow is queried far off-support on those rows and the val
355
+ # min-MSE read 2e5 (mug M, step 5000). z_clip comes from feat_stats.npz (0 = off).
356
+ if self.z_clip:
357
+ z = np.clip(z, -self.z_clip, self.z_clip, out=z)
358
+ return z
359
+
360
+ def _fit_norm(self, stride=97):
361
+ """Per-dim mean/std over a strided pass, cached next to the data.
362
+
363
+ `norm_pool` selects WHICH frames the statistics come from, and it matters
364
+ a great deal. Measured: behaviour cloning on demonstrations scores 0.580
365
+ closed-loop when centred with demonstration statistics and 0.430 with
366
+ statistics dominated by the 4500 rollout episodes -- same policy, same
367
+ data, same budget. The rollout corpus is a different distribution (a
368
+ noisy pi0.5 with SDE noise 0.5, half of it failures), so its mean is the
369
+ wrong origin for a policy that acts like a demonstrator.
370
+ """
371
+ tag = "" if self.norm_pool == "all" else f"_{self.norm_pool}"
372
+ f = self.root / f"feat_stats{tag}.npz"
373
+ if f.exists():
374
+ c = np.load(f)
375
+ if int(c["dim"]) == self.feat_dim:
376
+ self.norm_mu, self.norm_sd = c["mu"], c["sd"]
377
+ self.z_clip = float(c["z_clip"]) if "z_clip" in c.files else 0.0
378
+ print(f"[data] feature normalisation loaded from {f.name}"
379
+ f" (sd min {float(self.norm_sd.min()):.1e}, z_clip {self.z_clip})", flush=True)
380
+ return
381
+ if self.norm_pool == "demos":
382
+ keep = np.zeros(len(self.z), bool)
383
+ for e in np.where(self.ep_demo)[0]:
384
+ keep[self.ep_from[e]:self.ep_to[e]] = True
385
+ idx = np.where(keep)[0][::max(1, stride // 8)]
386
+ else:
387
+ idx = np.arange(0, len(self.z), stride)
388
+ x = np.asarray(self.z[idx], np.float32)
389
+ if self.proprio is not None:
390
+ x = np.concatenate([x, np.asarray(self.proprio[idx], np.float32)], -1)
391
+ mu = x.mean(0)
392
+ sd = np.maximum(x.std(0), 1e-3) # floor: a dead dim must not be amplified
393
+ self.norm_mu, self.norm_sd = mu.astype(np.float32), sd.astype(np.float32)
394
+ try:
395
+ np.savez(f, mu=self.norm_mu, sd=self.norm_sd, dim=self.feat_dim,
396
+ n=len(idx))
397
+ print(f"[data] feature normalisation fitted on {len(idx)} frames "
398
+ f"-> {f.name}", flush=True)
399
+ except OSError as e: # read-only cache dir: still normalise in-process
400
+ print(f"[data] normalisation fitted but not cached ({e})", flush=True)
401
+
402
+ @property
403
+ def feat_dim(self):
404
+ return self.dim + (0 if self.proprio is None else self.proprio.shape[1])
405
+
406
+ def _chunk_at(self, idx, ep_i, chunk_len=None):
407
+ """Flattened next-`chunk_len` executed actions, padded by repeating the last.
408
+
409
+ `chunk_len` defaults to the occupancy conditioning window, but the IS
410
+ ratio must use the BEHAVIOUR POLICY'S DECISION granularity instead. The
411
+ notes define W as a product over interior DECISIONS; pi0.5 re-decided
412
+ every 10 frames. Scoring 100-frame windows makes the two policies
413
+ perfectly separable (classifier acc 1.000 at 700 dims vs 0.934 at 70),
414
+ which destroys the ratio the correction needs.
415
+ """
416
+ cl = self.chunk if chunk_len is None else chunk_len
417
+ idx = np.asarray(idx, np.int64); ep_i = np.asarray(ep_i, np.int64)
418
+ if isinstance(self.act, np.ndarray) and not isinstance(self.act, np.memmap):
419
+ # in-RAM fast path (same result as the loop below): frames past the episode
420
+ # end are clamped to its last frame, which IS "pad by repeating the last
421
+ # action". At batch 4096 the Python loop was the step-time bottleneck.
422
+ fr = idx[:, None] + np.arange(cl)[None, :]
423
+ fr = np.minimum(fr, self.ep_to[ep_i][:, None] - 1)
424
+ return np.asarray(self.act[fr], np.float32).reshape(len(idx), cl * self.adim)
425
+ out = np.empty((len(idx), cl * self.adim), np.float32)
426
+ for j, (t, e) in enumerate(zip(idx, ep_i)):
427
+ hi = int(self.ep_to[e])
428
+ take = min(cl, hi - t)
429
+ a = np.asarray(self.act[t:t + take], np.float32)
430
+ if take < cl:
431
+ a = np.concatenate([a, np.repeat(a[-1:], cl - take, 0)], 0)
432
+ out[j] = a.reshape(-1)
433
+ return out
434
+
435
+ def sample(self, batch: int, rng, beta_lo: float, beta_hi: float,
436
+ split: str = "train", device="cuda", beta_trunc_eps: float = 0.02,
437
+ with_next: bool = False, augment: bool = True):
438
+ # `augment=False` forces the LOGGED sampler even when --action-augment is on. The
439
+ # minmse / staymse / NN-L1 diagnostics are the training gate this stream has to report
440
+ # against the un-augmented R_M cell, and under `contrastive` an augmented row's x_fut comes
441
+ # from the NEIGHBOUR's trajectory -- so letting augmented rows into those evaluations would
442
+ # silently change what the gate measures instead of measuring the same thing on a new model.
443
+ eps_pool = self.train_eps if split == "train" else self.val_eps
444
+ w = self.ep_len[eps_pool].astype(np.float64); w /= w.sum()
445
+ e = rng.choice(eps_pool, size=batch, p=w)
446
+ lo = self.ep_from[e]; hi = self.ep_to[e]
447
+ t = lo + (rng.random(batch) * (hi - lo)).astype(np.int64)
448
+ # BETA MEANS ONE THING (gen_q#262). k ~ Geom(1-beta) is truncated at the episode end, and
449
+ # E[k | k<L] depends on L -- at beta=0.995 with 150 frames remaining, 47% of the geometric
450
+ # falls past the end and the realised mean offset is 65 instead of 199. Drawing beta before
451
+ # looking at L therefore trains the model on "beta=0.995" paired with horizons anywhere from
452
+ # ~23 to ~180 frames, blurring the conditioning exactly where the horizon is longest.
453
+ #
454
+ # Cap beta per anchor so the truncated tail is a CONSTANT eps for every sample:
455
+ # beta_cap**L == eps => beta_cap = eps**(1/L)
456
+ # Anchors with a long remaining horizon (a full episode from its initial condition) get the
457
+ # whole band; short-remaining anchors get a correspondingly narrower one, because a
458
+ # long-horizon target genuinely does not exist there.
459
+ L = np.maximum(hi - t, 1).astype(np.float64)
460
+ beta_cap = np.power(beta_trunc_eps, 1.0 / L)
461
+ beta_hi_eff = np.clip(beta_cap, beta_lo, beta_hi)
462
+ beta = beta_lo + rng.random(batch) * (beta_hi_eff - beta_lo)
463
+ fut = truncated_geometric_future(t, hi, beta, rng.random(batch))
464
+
465
+ # ---- counterfactual action augmentation (see the block in __init__) -------------------
466
+ # Nothing here touches `rng`: with augmentation off the draws above ARE the whole sampler and
467
+ # every existing run reproduces bit-for-bit. `t_act` is the row the ACTION chunk comes from
468
+ # and is identical to `t` on every non-augmented row.
469
+ t_act, e_act = t, e
470
+ aug_mask = np.zeros(batch, bool)
471
+ if self.aug and augment and split == "train":
472
+ if with_next:
473
+ raise NotImplementedError(
474
+ "--action-augment with --occupancy-target td is not implemented: the TD "
475
+ "right-hand side needs s_{t+1} and a_{t+1} for the COUNTERFACTUAL action, which "
476
+ "the logged corpus does not contain. Use the MC occupancy target.")
477
+ ar = self._aug_rng
478
+ n_aug = int(ar.binomial(batch, self.aug_p))
479
+ if n_aug > 0:
480
+ t_act = t.copy(); e_act = e.copy()
481
+ pos = ar.choice(batch, size=min(n_aug, batch), replace=False)
482
+ pi = ar.integers(len(self.aug_anchor), size=len(pos))
483
+ i_row = self.aug_anchor[pi] # the ANCHOR state (x_now)
484
+ j_row = self.aug_nbr[pi] # the NEIGHBOUR: its action is the counterfactual
485
+ # "invariant" asserts the anchor's OWN occupancy for the counterfactual action;
486
+ # "contrastive" gives the counterfactual action the NEIGHBOUR's own future.
487
+ src = i_row if self.aug_mode == "invariant" else j_row
488
+ e_src = self.row_ep[src].astype(np.int64)
489
+ hi_s = self.ep_to[e_src]
490
+ L_s = np.maximum(hi_s - src, 1).astype(np.float64)
491
+ b_cap = np.power(beta_trunc_eps, 1.0 / L_s) # the SAME beta band and the SAME
492
+ b_hi = np.clip(b_cap, beta_lo, beta_hi) # truncation cap as the logged rows
493
+ b_new = beta_lo + ar.random(len(pos)) * (b_hi - beta_lo)
494
+ fut_new = truncated_geometric_future(src, hi_s, b_new, ar.random(len(pos)))
495
+ # x_now, r_now, task, succ, demo all stay the ANCHOR's (the reward head is
496
+ # state-only, so relabelling r at an unchanged x_now would be label noise)
497
+ e[pos] = self.row_ep[i_row]
498
+ t[pos] = i_row
499
+ beta[pos] = b_new
500
+ fut[pos] = fut_new
501
+ t_act[pos] = j_row
502
+ e_act[pos] = self.row_ep[j_row]
503
+ aug_mask[pos] = True
504
+
505
+ x_now = torch.from_numpy(self._feat(t)).to(device)
506
+ x_fut = torch.from_numpy(self._feat(fut)).to(device)
507
+ a_now = torch.from_numpy(self._chunk_at(t_act, e_act)).to(device)
508
+ out = {
509
+ "x_now": x_now, "x_fut": x_fut, "a_now": a_now,
510
+ "task": torch.from_numpy(self.ep_task[e]).long().to(device),
511
+ "beta": torch.from_numpy(beta).float().to(device),
512
+ "r_now": torch.from_numpy(self.r[t]).to(device),
513
+ "r_fut": torch.from_numpy(self.r[fut]).to(device),
514
+ "succ": torch.from_numpy(self.ep_success[e].astype(np.float32)).to(device),
515
+ "demo": torch.from_numpy(self.ep_demo[e].astype(np.float32)).to(device),
516
+ "t_idx": t, "ep": e, "fut_idx": fut,
517
+ }
518
+ # BUGFIX 2026-09-23 (pack 1881632 crashed here): `aug_frac` is a SCALAR, and nnl1_eval slices
519
+ # every value of the batch dict by a row index. Emit the two bookkeeping keys ONLY on a batch
520
+ # that actually went through the augmented path, so the diagnostic samplers (augment=False) and
521
+ # every run with the flag off see EXACTLY the pre-change key set. Both readers in train_rsm.py
522
+ # already use b.get(..., 0.0).
523
+ if self.aug and augment and split == "train":
524
+ out["aug_mask"] = aug_mask
525
+ out["aug_frac"] = float(aug_mask.mean())
526
+ if self.w is not None:
527
+ out["w_now"] = torch.from_numpy(self.w[t]).to(device)
528
+ if with_next:
529
+ # TD-FLOW (gen_q#268). The Bellman right-hand side of the occupancy identity
530
+ # m_beta(. | s,a) = (1-beta) P(. | s,a) + beta E_{s'}[ m_beta(. | s', pi(s')) ]
531
+ # needs the ONE-STEP successor s' and the action the behaviour policy takes there.
532
+ # This lane fits the occupancy of the DATASET policy (train_rsm.py has no actor), so
533
+ # a' is the logged chunk at t+1 -- exactly the analogue of a' = pi(s') for the policy
534
+ # the Monte-Carlo path already integrates along.
535
+ # Clamped to hi-1, i.e. the terminal frame is its own successor; the mixture coin is
536
+ # drawn per row in train_rsm.py, so a terminal anchor that takes the bootstrap branch
537
+ # bootstraps from itself rather than from a frame of the next episode.
538
+ # NOTHING here draws from `rng`: with with_next=False (the default) this block does not
539
+ # run at all, and with it True the MC draws above are bit-for-bit unchanged.
540
+ nxt = np.minimum(t + 1, hi - 1)
541
+ out["x_next"] = torch.from_numpy(self._feat(nxt)).to(device)
542
+ out["a_next"] = torch.from_numpy(self._chunk_at(nxt, e)).to(device)
543
+ out["r_next"] = torch.from_numpy(self.r[nxt]).to(device)
544
+ out["next_idx"] = nxt
545
+ return out
546
+
547
+ def goal_pool(self):
548
+ """Terminal latents of SUCCESSFUL episodes, per task -- the goal set the
549
+ two-tower likelihood scores against. Built once; index by task id."""
550
+ if getattr(self, "_gpool", None) is None:
551
+ pool = {}
552
+ for i in range(self.n_ep):
553
+ if not self.ep_success[i]:
554
+ continue
555
+ hi = int(self.ep_to[i])
556
+ pool.setdefault(int(self.ep_task[i]), []).extend(
557
+ range(max(int(self.ep_from[i]), hi - self.k_success), hi))
558
+ self._gpool = {k: np.array(v, np.int64) for k, v in pool.items()}
559
+ return self._gpool
560
+
561
+ def sample_goals(self, task_ids, rng, device="cuda"):
562
+ """One goal latent per row, drawn from that row's task's terminal states."""
563
+ gp = self.goal_pool()
564
+ idx = np.empty(len(task_ids), np.int64)
565
+ for j, ti in enumerate(np.asarray(task_ids)):
566
+ c = gp.get(int(ti))
567
+ idx[j] = rng.choice(c) if c is not None and len(c) else 0
568
+ return torch.from_numpy(self._feat(idx)).to(device)
569
+
570
+ def sample_frames(self, batch: int, rng, split="train", device="cuda"):
571
+ """(x, action chunk, task, reward, success) with no future -- for the
572
+ reward head, the ratio classifier and behavior cloning."""
573
+ eps_pool = self.train_eps if split == "train" else self.val_eps
574
+ w = self.ep_len[eps_pool].astype(np.float64); w /= w.sum()
575
+ e = rng.choice(eps_pool, size=batch, p=w)
576
+ lo = self.ep_from[e]; hi = self.ep_to[e]
577
+ t = lo + (rng.random(batch) * (hi - lo)).astype(np.int64)
578
+ return {
579
+ "to_end": torch.from_numpy((hi - t).astype(np.float32)).to(device),
580
+ "x": torch.from_numpy(self._feat(t)).to(device),
581
+ "a": torch.from_numpy(self._chunk_at(t, e)).to(device),
582
+ "task": torch.from_numpy(self.ep_task[e]).long().to(device),
583
+ "r": torch.from_numpy(self.r[t]).to(device),
584
+ "succ": torch.from_numpy(self.ep_success[e].astype(np.float32)).to(device),
585
+ "demo": torch.from_numpy(self.ep_demo[e].astype(np.float32)).to(device),
586
+ "t_idx": t, "ep": e,
587
+ }
frozen/rsm_libero_freeze_20261002/df_readout.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Diffusion Forcing as a VALUE ESTIMATOR -- the eval-harness read-out (gen_q#274 / #282, DF_VALUE).
2
+
3
+ WHAT THIS IS
4
+ ------------
5
+ The third column of the world-model family. All three are the same experiment with ONE thing
6
+ changed -- how the horizon is produced:
7
+
8
+ DINO-WM autoregressive latent rollout, chunk after chunk (dinowm_readout.py)
9
+ LeWM autoregressive latent rollout (lewm_readout.py)
10
+ DF ONE joint multi-step generation of the whole horizon, per-token noise levels (here)
11
+
12
+ so this module is deliberately the same shape as the other two: a `*Critic` class with the `q(...)`
13
+ signature `rsm_scorer` calls, plus a `load_critic_df` loader. The scoring MATH is not reimplemented
14
+ here -- it is `df_value.value_of_candidates`, the same function the offline spread gate runs, so an
15
+ eval cell and the gate cannot disagree about what "DF's value of a candidate" means.
16
+
17
+ THE READ-OUT (D1-D4, status/real/DF_VALUE.md; the docstring of df_value.py is the full statement)
18
+ D1 the candidate action chunk is INPAINTED into the action channel of plan token 1 and
19
+ re-imposed after every scheduling step; guidance_fn is None, ALWAYS. There is no guidance
20
+ objective in this route -- that is the planner route, and it is a different stream's.
21
+ D2 past the 8-frame chunk the action channel is LEFT FREE (model-sampled): the value means
22
+ "this chunk, then the behaviour distribution the model was trained on", which is the same
23
+ semantics as RSM's successor measure under the behaviour policy. free_tail=False (zero
24
+ action, i.e. "this chunk then nothing") is the named ablation, exposed as `free_tail`.
25
+ D3 M Monte-Carlo draws, the analogue of RSM's particle count P. See CRN below.
26
+ D4 two aggregations of the predicted reward channel: terminal r_hat at H (mode="mpc") and the
27
+ normalised discounted sum (mode="mpc_disc"). They map onto the two MPC modes the DINO-WM
28
+ and LeWM columns already publish, so the arm grammar is byte-identical across the three.
29
+
30
+ INPUT SPACE. The pooled 1545-d DINOv2 state, z-scored with the task's feat_stats -- literally the
31
+ same vector `rsm_scorer.PooledDinoState.forward` returns and the same map `df_data.obs_rows` applies
32
+ (`x = clip((feat - mu)/sd)`). So DF reads the scorer's DEFAULT state field `x`; unlike DINO-WM it
33
+ needs no patch tokens and unlike LeWM it needs no pixels, and `state_from_obs` needs no new branch.
34
+ The model's SECOND normalisation (the bundle-level z-score over [obs | act | reward]) is applied
35
+ inside df_value via `model.norm`, from the checkpoint's own mean/std.
36
+
37
+ COMMON RANDOM NUMBERS. `rsm_scorer` flattens (B envs x N candidates) into rows and a backend is
38
+ never told N, so drawing noise per row would give every candidate its own noise and make the argmax
39
+ partly a noise draw. This module therefore calls df_value with `crn_rows=True`: ONE noise draw per
40
+ Monte-Carlo index, shared by every row of the call. `crn_seed` from the planner selects it, so a
41
+ cell is reproducible and two candidates differ only by their actions.
42
+
43
+ WHAT IS NOT MATCHED, STATED PLAINLY
44
+ -----------------------------------
45
+ 1. DF's value is NOT a probability. DINO-WM and LeWM push their reward logit through a sigmoid and
46
+ return c_k in [0,1]; DF's reward channel is a REGRESSION onto the provenance label, unnormalised
47
+ and unbounded. It is clamped to [0,1] here ONLY because the planner's argmax and the table's
48
+ health numbers assume that range; `q_raw` carries the unclamped value. No temperature
49
+ calibration exists for it, so `temperature` is accepted and ignored, and `return_logit` returns
50
+ the raw value, NOT a logit. Any read-out that needs a real logit (prob_log, conformal_lcb) is
51
+ refused rather than faked.
52
+ 2. The two aggregations are one rollout used twice, but the scorer asks for one mode per cell, so a
53
+ (mpc, mpc_disc) pair of cells rolls the model twice. That is 2x the compute for a pair of
54
+ numbers that could share it; it is accepted here because sharing would mean caching across calls
55
+ inside a backend the harness may re-instantiate, and a wrong cache is worse than a slow cell.
56
+ 3. The continuation past chunk 1 is the model's own sampled action channel (D2), which is NEITHER
57
+ DINO-WM's hop head NOR LeWM's zero-order hold. The three columns therefore differ in the
58
+ continuation as well as the rollout mechanism; the caption must say so.
59
+ """
60
+ from __future__ import annotations
61
+
62
+ import json
63
+ import os
64
+ import sys
65
+ from pathlib import Path
66
+
67
+ import numpy as np
68
+ import torch
69
+
70
+ _DF_DIR = "/proj/dmfexp/zwhong/rsm_rise/code/df_rise"
71
+ if _DF_DIR not in sys.path:
72
+ sys.path.insert(0, _DF_DIR)
73
+
74
+ # The RISE eval env ($ROOT/env, py3.10) does not ship rotary_embedding_torch, and upstream's
75
+ # models/diffusion.py -> models/unet3d.py:6 imports it unconditionally (unet3d is NOT used by our
76
+ # 1-D transformer bundle; the import is merely on the module path). code/df_rise/_deps holds the
77
+ # real 0.9.1 package, vendored by the planner stream (see _deps/PROVENANCE.txt) and put on sys.path
78
+ # there only inside eval.py's `if RR_DF_CKPT:` block -- a branch this value-estimator route never
79
+ # takes. Do the same here, guarded, so no shared environment is mutated and a process that already
80
+ # has the package (venv_df, where the trainer and the offline gate run) is untouched.
81
+ # Measured: without this, LSF 1893591 died at df_readout.py:87 with ModuleNotFoundError.
82
+ try: # pragma: no cover - env-dependent
83
+ import rotary_embedding_torch as _ret # noqa: F401
84
+ except ModuleNotFoundError:
85
+ _DF_DEPS = os.path.join(_DF_DIR, "_deps")
86
+ if os.path.isdir(_DF_DEPS) and _DF_DEPS not in sys.path:
87
+ sys.path.append(_DF_DEPS)
88
+
89
+ from df_data import OBS_DIM, ACT_DIM # noqa: E402
90
+ from df_core import DFRise # noqa: E402
91
+ from df_value import value_of_candidates, default_gamma # noqa: E402
92
+
93
+
94
+ class DFCritic:
95
+ """The interface robomimic's RSMScorer expects of a backend core (see rsm_scorer.DWMBackend)."""
96
+
97
+ def __init__(self, ck, device, free_tail=True):
98
+ meta = ck["meta"]
99
+ self.device = torch.device(device)
100
+ # TF32 ON by default, and it is a MEASUREMENT, not a guess. LSF 1894069 ran threading df_A
101
+ # H=50 M=8 over 128 shared anchors at S=50 in both precisions and dumped the raw 128x128
102
+ # value matrices (status/real/dfval/vals_*_cost_s50_{fp32,tf32}.npz). Against the fp32
103
+ # reference TF32 agrees on top-1 -- which is all the planner's argmax consumes -- for
104
+ # 99.2 % of anchors on the discounted read-out and 96.9 % on terminal, with per-anchor rank
105
+ # correlation 1.000 / 0.995, while cutting the cell 1.45x (119.4s -> 81.3s / 128 anchors).
106
+ # Contrast the DDIM knob, measured in the SAME job and REJECTED: S=25 already drops terminal
107
+ # top-1 to 0.594 and S=10 to 0.367, so sampling_timesteps stays at its trained-config 50.
108
+ # RR_DF_TF32=0 restores full fp32 for a bit-comparable re-read.
109
+ self._tf32 = os.environ.get("RR_DF_TF32", "1") not in ("0", "false", "False")
110
+ torch.backends.cuda.matmul.allow_tf32 = self._tf32
111
+ torch.backends.cudnn.allow_tf32 = self._tf32
112
+ self.frame_stack = int(meta["frame_stack"])
113
+ self.n_tokens = int(meta["n_tokens"])
114
+ self.model = DFRise(frame_stack=self.frame_stack, n_tokens=self.n_tokens,
115
+ mean=ck["mean"], std=ck["std"], cfg=ck["cfg"]).to(self.device)
116
+ self.model.load_state_dict(ck["model"])
117
+ self.model.eval()
118
+ for p in self.model.parameters():
119
+ p.requires_grad_(False)
120
+ # The candidate chunk IS one plan token: frame_stack == the project's 8-frame action chunk.
121
+ self.chunk = self.frame_stack
122
+ self.adim = ACT_DIM
123
+ self.d_act = self.chunk * ACT_DIM
124
+ self.d_z = OBS_DIM
125
+ # One DF hop = one plan token = frame_stack frames, so K = ceil(H / hop_frames) plan tokens.
126
+ # Read by rsm_scorer to turn the cell's H (in frames) into a depth; constant in beta, as on
127
+ # DINO-WM and LeWM, because a latent world model has no beta.
128
+ self.hop_frames = float(self.frame_stack)
129
+ self.step = int(ck.get("step", -1))
130
+ self.free_tail = bool(free_tail)
131
+ self.temperature = 1.0
132
+ self.calib = None
133
+ self.q_action_winrate = None
134
+ # The training window, kept so a cell can declare when H extrapolates past it.
135
+ self.train_frames = self.frame_stack * self.n_tokens
136
+ self.last_diag = None
137
+
138
+ # ------------------------------------------------------------------------------------------
139
+ def _prep(self, inp, a_chunk):
140
+ x = inp[0] if isinstance(inp, (tuple, list)) else inp
141
+ x = torch.as_tensor(x).to(self.device).float()
142
+ assert x.ndim == 2 and x.shape[1] == self.d_z, \
143
+ f"DF scores from the pooled {self.d_z}-d state, got {tuple(x.shape)}"
144
+ a = torch.as_tensor(a_chunk).to(self.device).float().view(x.shape[0], -1)
145
+ assert a.shape[1] == self.d_act, f"a_chunk must be [B,{self.d_act}], got {tuple(a.shape)}"
146
+ return x, a.view(x.shape[0], 1, self.chunk, self.adim)
147
+
148
+ @torch.no_grad()
149
+ def q(self, inp, a_chunk, beta=None, n_particles=1, crn_seed=None, depth=1, mode="mpc",
150
+ proprio=None, hop_policy=None, gamma=0.99, flow_steps=8, micro=256, return_hops=False,
151
+ return_logit=False, temperature=None, return_lcb=None, rescore_top=0,
152
+ n_particles_rescore=0):
153
+ """Q per row. `depth` = plan tokens (K), so the horizon rolled is K * frame_stack frames.
154
+
155
+ `n_particles` is DF's M (D3) -- unlike DINO-WM this model IS stochastic, so the particle
156
+ axis is real here and is not forced to 1. `beta`, `flow_steps`, `hop_policy` and `proprio`
157
+ are accepted because the shared planner passes them to every backend, and are inert: DF has
158
+ no hazard, no ODE, no hop head and reads no proprio channel of its own (proprio is already
159
+ inside the pooled state)."""
160
+ if mode not in ("mpc", "mpc_disc"):
161
+ raise ValueError(
162
+ f"mode {mode!r}: the DF value route publishes the two MPC read-outs only -- 'mpc' "
163
+ f"(terminal r_hat at H) and 'mpc_disc' (normalised discounted sum along the "
164
+ f"rollout). 'd1' and 'fold' are hazard read-outs of a SUCCESSOR model; DF has no "
165
+ f"per-hop hazard to fold, and faking one would not be the same estimator.")
166
+ if return_lcb is not None:
167
+ raise ValueError("plan_score=conformal_lcb needs a calibrated particle quantile; DF's "
168
+ "reward channel is an uncalibrated regression, so a quantile of it is "
169
+ "not a lower confidence bound on anything")
170
+ x, a = self._prep(inp, a_chunk)
171
+ K = max(int(depth), 1)
172
+ H = int(K * self.frame_stack)
173
+ M = max(int(n_particles), 1)
174
+ seed = 0 if crn_seed is None else int(crn_seed)
175
+ out = value_of_candidates(
176
+ self.model, x, a, H=H, M=M,
177
+ # D4: the cell's own gamma, so the discounted sum uses the SAME discount the cell's H
178
+ # was derived from (H = 1/(1-gamma)) instead of df_value's default 1 - 1/H.
179
+ gamma=float(gamma) if mode == "mpc_disc" else None,
180
+ free_tail=self.free_tail, device=self.device, seed=seed,
181
+ crn_rows=True, assert_clamp=True)
182
+ v = (out["terminal"] if mode == "mpc" else out["disc"])[:, 0]
183
+ sd = (out["terminal_std"] if mode == "mpc" else out["disc_std"])[:, 0]
184
+ self.last_diag = dict(out["diag"], mode=mode, H=H, K=K, M=M,
185
+ mean_std_across_M=float(sd.mean().item()),
186
+ std_across_rows=float(v.std().item()))
187
+ q_raw = torch.nan_to_num(v, nan=0.0)
188
+ q = q_raw.clamp(0.0, 1.0) # see "WHAT IS NOT MATCHED" 1 in the module docstring
189
+ out_v = (q, q_raw) if return_logit else q
190
+ if return_hops:
191
+ # DF generates the horizon JOINTLY -- there is no per-hop sequence of independent
192
+ # decisions to report, which is the whole point of the column. Returning the terminal
193
+ # value K times would look like a hop trace and would be a lie about the mechanism.
194
+ raise ValueError("return_hops has no meaning for DF: the horizon is generated jointly, "
195
+ "not hop by hop")
196
+ return out_v
197
+
198
+ def hop_sample(self, x, eps):
199
+ raise RuntimeError("DF has no hop head: the continuation past the candidate chunk is the "
200
+ "model's OWN sampled action channel (D2), not a policy over states")
201
+
202
+ def describe(self):
203
+ return {"backend": "df", "frame_stack": self.frame_stack, "n_tokens": self.n_tokens,
204
+ "hop_frames": self.hop_frames, "chunk": self.chunk, "d_act": self.d_act,
205
+ "step": self.step, "free_tail": self.free_tail, "tf32": self._tf32,
206
+ "train_frames": self.train_frames, "deterministic": False,
207
+ "readout": "predicted reward channel of a jointly generated multi-step bundle",
208
+ "guidance": "none (guidance_fn=None)"}
209
+
210
+
211
+ def load_critic_df(path, device="cuda", calib="auto", free_tail=None) -> DFCritic:
212
+ """`path` is a train_df.py checkpoint (ckpt_s<step>.pt: keys cfg/mean/meta/model/std/step).
213
+
214
+ `free_tail` defaults to D2 (True) and can be forced to False by the env var RR_DF_FREE_TAIL=0 so
215
+ the "this chunk then nothing" ablation can be run WITHOUT a new cell grammar -- the scorer has
216
+ no flag for it and inventing one would change every other column's argument surface."""
217
+ ck = torch.load(str(path), map_location="cpu", weights_only=False)
218
+ if "meta" not in ck or "model" not in ck:
219
+ raise RuntimeError(f"{path} is not a train_df.py checkpoint (keys {sorted(ck.keys())})")
220
+ if free_tail is None:
221
+ free_tail = os.environ.get("RR_DF_FREE_TAIL", "1") not in ("0", "false", "False")
222
+ crit = DFCritic(ck, device, free_tail=free_tail)
223
+ # Accepted and IGNORED, loudly: DF's value is a regression, not a logit, so a temperature is not
224
+ # defined for it. Silently reading calib.json would make the column look calibrated.
225
+ if calib not in (None, "auto", "none") or (Path(path).parent / "calib.json").exists():
226
+ print(f"[df_readout] temperature calibration does not apply to DF's regression read-out; "
227
+ f"T=1 (calib={calib!r})", flush=True)
228
+ return crit
frozen/rsm_libero_freeze_20261002/dinowm_readout.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DINO-WM read-out: the same best-of-N scorer interface as dwm_readout, with DINO-WM's dynamics.
2
+
3
+ gen_q#268. The single-actor flagship asks one question -- "same RISE actor, same 128 candidates,
4
+ same provenance reward, only the value estimator changes" -- so a world-model comparator is only
5
+ worth running if it differs from RSM/DWM in the MODEL and in nothing else. That is why this module
6
+ is 60 lines instead of 600: `DINOWMCritic` SUBCLASSES `dwm_readout.DWMCritic` and overrides exactly
7
+ two methods, the transition and the hop length. The fold algebra, the hop-policy chaining, the
8
+ reward head, the token normaliser, the temperature calibration and the two-stage rescore are the
9
+ same code objects the DWM column runs.
10
+
11
+ WHAT DINO-WM IS HERE
12
+ --------------------
13
+ stable-worldmodel's PreJEPA recipe: frozen DINOv2 ViT-S/14 patch features + a causal transformer
14
+ that predicts the next frame's features from the current ones and the action, trained by latent MSE.
15
+ Our caches already hold exactly those features (cache/<task>/tokens/tok.f16.npy is
16
+ [N, 514, 384] = 2 cameras x (CLS + 256 patches) from dinov2_vits14 at 224 px), and dwm_model.DWM is
17
+ already "the DINO-WM predictor" -- stream C built it as the velocity network of a token-space flow.
18
+ So DINO-WM is that predictor trained with train_rsm_dwm.py --dynamics latent_mse, and scored here.
19
+
20
+ TRANSITION. Deterministic: s' = f_theta(s, a), one action chunk ahead. The predictor is queried
21
+ at the one fixed point of its flow-time/noise inputs that training used (x_k = 0, k = 0, beta = 0),
22
+ so the "future" half of its token sequence is a learned query attending to the current frame's patch
23
+ tokens under the action embedding. There is no ODE and no noise IN THE TRANSITION.
24
+
25
+ PARTICLES (gen_q#288, corrected 2026-09-25). A deterministic transition does NOT make the ESTIMATOR
26
+ deterministic. Past the candidate chunk the continuation action comes from the stochastic Gaussian
27
+ hop head -- the same object RSM chains with -- so at depth > 1 the M particles are M different action
28
+ sequences and Q is the mean over them, with common random numbers across candidates (`_q_once` draws
29
+ eps per particle and tiles it over the rows). This module used to force n_particles = 1 at EVERY
30
+ depth, so all 855 published DINO-WM MPC cells requested 16 particles and measured one roll-out. Only
31
+ depth == 1 is truly deterministic and keeps the force. Search cost therefore scales with M and the
32
+ flagship discloses it; the effective count is in the cell's `planner.scorer.effective_particles` and
33
+ in the arm key, so a repaired cell cannot pool with an old one.
34
+
35
+ HOP LENGTH. One DINO-WM hop is `hop_frames` frames (the action chunk the model was trained on, 8 =
36
+ 0.4 s at 20 Hz), whereas an RSM/DWM hop spans 1/(1-beta) frames. The two scorers are therefore
37
+ matched on the NUMBER of hops, L in {1,2,4,8}, not on beta -- a latent-dynamics model has no beta --
38
+ and the fold's per-hop discount uses gamma ** hop_frames. L is the only knob this scorer has, which
39
+ is why its arm label in verdict_table is "L<depth> N<n>" with no beta in it.
40
+
41
+ DEVIATIONS FROM THE PAPER, DECLARED
42
+ -----------------------------------
43
+ 1. History length 1, not 3. Forced by the protocol, not chosen: rsm_planner.plan_get_action hands a
44
+ scorer the SINGLE current frame (`obs_t = {k: v[:, -1] ...}`), so a history-3 world model cannot
45
+ be evaluated on the same observation every other scorer sees.
46
+ 2. Two cameras (514 tokens) rather than one, because that is what the RISE observation is and what
47
+ every other scorer in the table reads.
48
+ 3. Actions enter as the flattened 8-step chunk the RISE actor emits, not per-frame, for the same
49
+ reason: it is the candidate the planner ranks.
50
+ 4. The reward probe is the checkpoint's own head on the provenance/membership label -- the same
51
+ label and the same head class RSM's membership read-out uses.
52
+ """
53
+ from __future__ import annotations
54
+
55
+ import json
56
+ from pathlib import Path
57
+
58
+ import torch
59
+
60
+ # (no direct model construction here: DWMCritic.__init__ builds the predictor and the reward head)
61
+ from dwm_readout import DWMCritic
62
+
63
+
64
+ class DINOWMCritic(DWMCritic):
65
+ """DWMCritic with DINO-WM's deterministic latent dynamics instead of the occupancy flow."""
66
+
67
+ def __init__(self, ck, device, use_ema=True):
68
+ super().__init__(ck, device, use_ema=use_ema)
69
+ # frames per hop: the action chunk the model was trained to step over.
70
+ self.hop_frames = float(ck.get("hop_frames", self.config.get("chunk", 8)))
71
+ self.dynamics = str(self.config.get("dynamics", "latent_mse"))
72
+
73
+ def _step(self, tzr, pzr, ar, bq, B, n, g, flow_steps, micro):
74
+ """s' = f_theta(s, a): one deterministic chunk step, in normalised token space.
75
+
76
+ Mirrors the training call in train_rsm_dwm._latent_mse_terms exactly -- same zero flow-time,
77
+ same zero noise input, same zero beta, same residual reparameterisation -- so the model is
78
+ queried at scoring time at the one point it was fitted at. `micro` still bounds the rows per
79
+ forward, because N=128 candidates x 514 tokens is the same memory problem the flow path has.
80
+ """
81
+ outs_t, outs_p = [], []
82
+ m = max(int(micro), 1)
83
+ for i in range(0, tzr.shape[0], m):
84
+ t_i, p_i, a_i = tzr[i:i + m], pzr[i:i + m], ar[i:i + m]
85
+ zt = torch.zeros_like(t_i)
86
+ zp = torch.zeros_like(p_i)
87
+ kz = torch.zeros(t_i.shape[0], device=t_i.device)
88
+ bz = torch.zeros(t_i.shape[0], device=t_i.device)
89
+ with self.autocast():
90
+ v_tok, v_pr = self.flow(t_i, p_i, a_i, bz, zt, zp, kz)
91
+ nt = t_i.float() + self.rms_tok * v_tok.float()
92
+ npr = (p_i.float() + self.rms_pr * v_pr.float()) if v_pr.shape[1] else p_i.float()
93
+ outs_t.append(nt)
94
+ outs_p.append(npr)
95
+ return torch.cat(outs_t, 0), torch.cat(outs_p, 0)
96
+
97
+ def _hop_frames(self, beta):
98
+ return self.hop_frames
99
+
100
+ def n_eff_particles(self, n_particles, depth, mode):
101
+ """The number of DISTINCT roll-outs a (n_particles, depth, mode) cell actually averages.
102
+
103
+ Exposed so the eval cell's `planner.scorer` block can record the EFFECTIVE count rather than
104
+ the requested one, the same self-verifying trick the temperature field already uses: two cells
105
+ pool in verdict_table's arm key exactly when the estimator they ran was the same, whatever the
106
+ grid asked for. Before gen_q#288 this class silently collapsed every count to 1, so 855
107
+ published DINO-WM cells REQUESTED 16 and MEASURED 1; without this field a re-run at a working
108
+ M=16 would pool with them.
109
+ """
110
+ d = 1 if mode == "d1" else int(depth or 1)
111
+ return 1 if d <= 1 else int(n_particles or 1)
112
+
113
+ def q(self, *a, **kw):
114
+ """gen_q#288 -- M STOCHASTIC ROLL-OUTS, not one. n_particles is forced to 1 only at depth 1.
115
+
116
+ The TRANSITION here is deterministic (`_step` above), which is why this override used to force
117
+ n_particles = 1 unconditionally. That was wrong for every depth > 1 cell, and every published
118
+ DINO-WM MPC cell is one: past the candidate chunk the continuation comes from the STOCHASTIC
119
+ Gaussian hop head (`_q_once`'s hop_policy branch draws its own eps per particle), so particles
120
+ at depth > 1 are genuinely different chains and averaging them is the estimator, exactly as it
121
+ is for RSM and DWM. Owner, 2026-09-25: "should definitely be M different chains for DINOWM
122
+ and LeWM with stochastic continuations just like RSM."
123
+
124
+ At depth == 1 there is no continuation to sample and the roll IS deterministic, so 16 identical
125
+ roll-outs would burn 16x the compute and report the same number -- that case keeps the force.
126
+ `mode="d1"` pins depth to 1 inside the parent, so it is resolved here the same way.
127
+ """
128
+ if len(a) > 3:
129
+ # n_particles/depth/mode passed POSITIONALLY would be invisible to the kw rewrite below and
130
+ # `kw["n_particles"] = 1` would then be a duplicate argument, so say so instead of guessing.
131
+ raise TypeError(
132
+ "dinowm_readout.DINOWMCritic.q takes (x_tokens, a_chunk, beta) positionally; pass "
133
+ "n_particles / depth / mode by keyword (rsm_scorer.DWMBackend.q already does) -- the "
134
+ "particle count is rewritten here (gen_q#288) and cannot be read out of *args")
135
+ mode = kw.get("mode", "d1")
136
+ depth = kw.get("depth", 1)
137
+ if self.n_eff_particles(kw.get("n_particles", 16), depth, mode) == 1:
138
+ if kw.get("n_particles", 1) != 1:
139
+ kw["n_particles"] = 1
140
+ if kw.get("n_particles_rescore"):
141
+ kw["n_particles_rescore"] = 1
142
+ return super().q(*a, **kw)
143
+
144
+
145
+ def load_critic_dwm(path, device="cuda", use_ema=True, calib="auto") -> DINOWMCritic:
146
+ """Same name and signature as dwm_readout.load_critic_dwm, so this module is a drop-in for the
147
+ scorer's DWM backend (which imports `load_critic_dwm` from `rsm_dwm_module`)."""
148
+ ck = torch.load(str(path), map_location="cpu", weights_only=False)
149
+ m = str(ck.get("model", "dwm"))
150
+ dyn = dict(ck.get("config", {})).get("dynamics")
151
+ if m != "dinowm" or dyn != "latent_mse":
152
+ raise RuntimeError(
153
+ f"{path} is model={m!r} dynamics={dyn!r}; dinowm_readout needs a checkpoint trained with "
154
+ f"train_rsm_dwm.py --dynamics latent_mse. A flow DWM must be loaded by "
155
+ f"dwm_readout.load_critic_dwm -- reading it here would treat a velocity field as a "
156
+ f"next-state predictor.")
157
+ crit = DINOWMCritic(ck, device, use_ema=use_ema)
158
+ if isinstance(calib, (int, float)) and not isinstance(calib, bool):
159
+ crit.temperature = float(calib)
160
+ elif calib == "auto":
161
+ cj = Path(path).parent / "calib.json"
162
+ if cj.exists():
163
+ try:
164
+ crit.calib = json.loads(cj.read_text())
165
+ crit.temperature = float(crit.calib["T"])
166
+ except Exception as e:
167
+ print(f"[dinowm_readout] calib.json unreadable ({e}); T=1", flush=True)
168
+ return crit
frozen/rsm_libero_freeze_20261002/dwm_model.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DWM: the DINO-WM predictor architecture, trained as a beta-discounted SUCCESSOR model.
2
+
3
+ DINO-WM (gaoyuezhou/dino_wm, conf/predictor/vit.yaml): a ViT (depth 6, 16 heads x 64,
4
+ MLP 2048, dropout 0.1) over frozen DINOv2 ViT-S/14 patch tokens (384-d) with the action and
5
+ proprio embeddings CONCATENATED to every token, trained by MSE to the next frame's tokens.
6
+
7
+ Ours keeps the ViT and changes the target and the objective (LAUNCH_MATRIX rev. 4, "DWM"):
8
+
9
+ * sequence = 514 "now" tokens (agentview CLS + 256 patches, wrist CLS + 256 patches)
10
+ + 514 NOISY FUTURE tokens x_k = (1-k) y + k eps, full attention,
11
+ learned position embedding shared by the two halves + a 2-way TYPE embedding;
12
+ * y = (x_{t+K} - x_t) / rho, the residual of the z-scored tokens, rho = running
13
+ per-(token, channel) RMS of the residual (OccFlow's per-dim normalisation);
14
+ * K ~ Geom(1 - beta), beta ~ U[lo, hi], truncated at the episode end (data.py sampler);
15
+ * conditioning, concatenated to EVERY token as DINO-WM does: action chunk (8x7=56 -> 16),
16
+ proprio (9 -> 8), Fourier(log(-log beta)) (-> 8), flow time k sinusoid (8): 384+40 = 424;
17
+ * output = the flow velocity v = y - eps read at the future positions (LayerNorm+Linear);
18
+ * reward head R: mean-pooled tokens per camera (2x384) ++ proprio -> MLP 512x2 -> logit.
19
+
20
+ One documented addition: a 515th "proprio" token per frame (9-d proprio embedded to 384, and
21
+ its own 9-d residual on the future side, read out by a 424->9 head). The MLP cells model the
22
+ pooled 1545-d state, which INCLUDES proprio, and the Stage-2 hop policy consumes the pooled
23
+ state of the sampled future, so the DWM successor has to predict proprio too. Cost: 2 tokens
24
+ out of 1030.
25
+
26
+ No learned encoder: DINO is frozen and its tokens are the state (Stage 1 "no learned encoder
27
+ in either case").
28
+ """
29
+ from __future__ import annotations
30
+ import sys as _sys, os as _os
31
+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
32
+ import json
33
+ from pathlib import Path
34
+ import numpy as np
35
+ import torch
36
+ import torch.utils.checkpoint
37
+ import torch.nn as nn
38
+ import torch.nn.functional as F
39
+
40
+ from model import beta_fourier, time_embed
41
+ from data import truncated_geometric_future
42
+
43
+ # token layout of cache/<task>/tokens/tok.f16.npy [N, 514, 384]
44
+ N_PATCH = 256
45
+ D_TOK = 384
46
+ TOK_LAYOUT = {"agent_cls": 0, "agent_patch": (1, 1 + N_PATCH),
47
+ "wrist_cls": 1 + N_PATCH, "wrist_patch": (2 + N_PATCH, 2 + 2 * N_PATCH)}
48
+ N_TOK = 2 + 2 * N_PATCH # 514
49
+ # Stage-1 state normalisation rule (orchestrator, 2026-09-18; B_stage1.md "STATE DEFINITION (final)"):
50
+ # x = clip((feat - mu) / max(sd, SD_FLOOR), -Z_CLIP, Z_CLIP) -- same floor/clip for pooled and token space
51
+ # and the residual RMS rho is floored at RHO_FLOOR; the normalised residual y is clipped to +-Y_CLIP so a dead
52
+ # channel (sd at the floor, delta up to 2*Z_CLIP) can never blow up the flow target.
53
+ SD_FLOOR = 0.01
54
+ Z_CLIP = 10.0
55
+ RHO_FLOOR = 0.01
56
+ Y_CLIP = 10.0
57
+ STATS_VERSION = 2
58
+
59
+
60
+ # --------------------------------------------------------------------------- #
61
+ # pooled 1545-d state from tokens (RISE's DinoV2Core(concatenate=True) ++ proprio)
62
+ # --------------------------------------------------------------------------- #
63
+ def gem_pool(patches: torch.Tensor, p: float = 4.0, eps: float = 1e-6) -> torch.Tensor:
64
+ """GeM over the patch axis exactly as robomimic/models/obs_core.py DinoV2Core does:
65
+ clamp(min=1e-6) -> mean over the 16x16 grid of x^4 -> ^(1/4). patches [..., 256, 384]."""
66
+ return patches.clamp(min=eps).pow(p).mean(-2).pow(1.0 / p)
67
+
68
+
69
+ def pool_tokens(tokens: torch.Tensor, proprio: torch.Tensor | None = None) -> torch.Tensor:
70
+ """[B, 514, 384] RAW DINO tokens (+ [B, 9] proprio) -> [B, 1536 (+9)] pooled state
71
+ = [agent CLS ‖ GeM(agent patches) ‖ wrist CLS ‖ GeM(wrist patches)] ‖ proprio,
72
+ i.e. what cache/<task>/z.f16.npy ‖ proprio.f32.npy holds (un-normalised)."""
73
+ t = tokens.float()
74
+ a0, (a1, a2) = TOK_LAYOUT["agent_cls"], TOK_LAYOUT["agent_patch"]
75
+ w0, (w1, w2) = TOK_LAYOUT["wrist_cls"], TOK_LAYOUT["wrist_patch"]
76
+ parts = [t[:, a0], gem_pool(t[:, a1:a2]), t[:, w0], gem_pool(t[:, w1:w2])]
77
+ if proprio is not None:
78
+ parts.append(proprio.float())
79
+ return torch.cat(parts, -1)
80
+
81
+
82
+ # --------------------------------------------------------------------------- #
83
+ # data: the pooled pack's meta/actions/proprio/labels + the token memmap
84
+ # --------------------------------------------------------------------------- #
85
+ class TokenRSMData:
86
+ """Same episode split, reward label and future sampler as data.LiberoRSMData, but the
87
+ state is the [514, 384] token frame from <cache>/tokens/tok.f16.npy (memmap; the page
88
+ cache is shared by the 8 DDP ranks on a node). Frame order = the pooled pack's."""
89
+
90
+ def __init__(self, root, chunk: int = 8, val_frac: float = 0.1, seed: int = 0,
91
+ reward_mode: str = "dense", success_gamma: float = 0.98,
92
+ in_ram: bool = False, tokens_file: str = "", goal_file: str = "",
93
+ tok_rows: str = ""):
94
+ root = Path(root)
95
+ self.root = root
96
+ m = np.load(root / "meta.npz", allow_pickle=True)
97
+ self.ep_from = m["ep_from"].astype(np.int64); self.ep_to = m["ep_to"].astype(np.int64)
98
+ self.ep_len = m["ep_len"].astype(np.int64)
99
+ self.ep_task = m["ep_task"].astype(np.int64); self.ep_success = m["ep_success"].astype(bool)
100
+ self.ep_demo = m["ep_demo"] if "ep_demo" in m else np.zeros(len(self.ep_task), bool)
101
+ self.tasks = [str(t) for t in m["tasks"]]
102
+ self.n_task = len(self.tasks); self.n_ep = len(self.ep_len)
103
+ self.adim = int(m["adim"]); self.chunk = chunk
104
+ self.act = np.load(root / "act.f32.npy", mmap_mode="r")
105
+ pp = root / "proprio.f32.npy"
106
+ self.proprio = np.load(pp, mmap_mode="r") if pp.exists() else None
107
+ tf = Path(tokens_file) if tokens_file else root / "tokens" / "tok.f16.npy"
108
+ self.tok_path = tf
109
+ self.tok = np.load(tf, mmap_mode="r")
110
+ assert self.tok.ndim == 3 and self.tok.shape[1:] == (N_TOK, D_TOK), \
111
+ f"token cache {tf} has shape {self.tok.shape}, expected [N, {N_TOK}, {D_TOK}]"
112
+ # ROW MAP (gen_q#268). A cache that is a ROW SLICE of a parent -- cache/square_sub_20100 is
113
+ # exactly that of cache/square_expert_suboptimal (SLICE.json,
114
+ # scripts/build_sq20100_cache_slice.py), and its PACK.json records that tokens were not
115
+ # sliced -- can read the PARENT's token file through an index array instead of getting a
116
+ # 15.6 GB copy of it. /proj/dmfexp runs at 99% full, so the copy is not an option.
117
+ # tok_rows[i] is the parent-file row of THIS cache's frame i; it must have one entry per
118
+ # frame of the pooled pack, and the pooled pack's own frame count is what everything else
119
+ # (act, proprio, meta, the reward label) is indexed by.
120
+ self.tok_rows = None
121
+ if tok_rows:
122
+ self.tok_rows = np.load(tok_rows).astype(np.int64)
123
+ assert len(self.tok_rows) == int(self.ep_to[-1]), \
124
+ f"row map {tok_rows} has {len(self.tok_rows)} entries, pooled pack has {int(self.ep_to[-1])} frames"
125
+ assert int(self.tok_rows.max()) < self.tok.shape[0], \
126
+ f"row map indexes frame {int(self.tok_rows.max())} of a {self.tok.shape[0]}-frame token file"
127
+ print(f"[data] token row map {tok_rows}: {len(self.tok_rows)} frames read out of "
128
+ f"{self.tok.shape[0]} in {tf}", flush=True)
129
+ else:
130
+ assert self.tok.shape[0] == int(self.ep_to[-1]), \
131
+ f"token frames {self.tok.shape[0]} != pooled pack frames {int(self.ep_to[-1])}"
132
+ self.tok_info = {}
133
+ tj = tf.parent / "TOKENS.json"
134
+ if tj.exists():
135
+ try:
136
+ self.tok_info = json.loads(tj.read_text())
137
+ except Exception:
138
+ pass
139
+ self.act = np.ascontiguousarray(self.act)
140
+ if self.proprio is not None:
141
+ self.proprio = np.ascontiguousarray(self.proprio)
142
+ if in_ram:
143
+ gb = self.tok.nbytes / 1e9
144
+ print(f"[data] loading {gb:.1f} GB of tokens into RAM", flush=True)
145
+ self.tok = np.ascontiguousarray(self.tok)
146
+ if self.tok_rows is not None and in_ram:
147
+ # keep only the rows this cache uses, and renumber the map onto them
148
+ self.tok = np.ascontiguousarray(self.tok[np.sort(np.unique(self.tok_rows))])
149
+ _u = np.sort(np.unique(np.load(tok_rows).astype(np.int64)))
150
+ self.tok_rows = np.searchsorted(_u, np.load(tok_rows).astype(np.int64))
151
+ self.n_pr = 0 if self.proprio is None else int(self.proprio.shape[1])
152
+
153
+ # episode-level split, IDENTICAL to LiberoRSMData(seed=seed) so the val set matches
154
+ # the MLP cells
155
+ rng = np.random.default_rng(seed)
156
+ perm = rng.permutation(self.n_ep)
157
+ n_val = max(1, int(val_frac * self.n_ep))
158
+ self.val_eps = np.sort(perm[:n_val]); self.train_eps = np.sort(perm[n_val:])
159
+
160
+ # per-frame reward label (LiberoRSMData: dense = every frame of a success; soft =
161
+ # gamma ** frames-to-end on successes)
162
+ self.r = np.zeros(int(self.ep_to[-1]), dtype=np.float32)
163
+ if reward_mode == "goal":
164
+ # GOAL-STATE label: env.is_success() at the replayed frame (scripts/goal_label_replay.py), not the
165
+ # outcome. The dense label fires on every frame of a successful episode and makes the read-out saturate.
166
+ gf = Path(goal_file) if goal_file else root / "goal.npz"
167
+ g = np.load(gf, allow_pickle=True)["goal"]
168
+ assert len(g) == len(self.r), f"{gf}: {len(g)} frames vs cache {len(self.r)}"
169
+ self.r[:] = g.astype(np.float32)
170
+ print(f"[data] goal label from {gf}: {self.r.mean():.4f} of frames", flush=True)
171
+ for i in range(self.n_ep):
172
+ if reward_mode == "goal" or not self.ep_success[i]:
173
+ continue
174
+ lo, hi = int(self.ep_from[i]), int(self.ep_to[i])
175
+ if reward_mode == "dense":
176
+ self.r[lo:hi] = 1.0
177
+ elif reward_mode == "soft":
178
+ n = hi - lo
179
+ self.r[lo:hi] = (success_gamma ** np.arange(n - 1, -1, -1, dtype=np.float64)
180
+ ).astype(np.float32)
181
+ else:
182
+ raise ValueError(f"reward_mode {reward_mode} not supported for DWM")
183
+ self.stats = self._fit_stats()
184
+
185
+ # ---- normalisation statistics (per token position x channel; per proprio dim) ----
186
+ def _fit_stats(self, stride: int = 97):
187
+ # With a row map the token file belongs to the PARENT task, so its tok_stats.npz describes
188
+ # the parent's frame distribution, not ours. Fit and cache our own, in our own cache dir.
189
+ f = (self.root / "tokens" / "tok_stats.npz") if self.tok_rows is not None \
190
+ else self.tok_path.parent / "tok_stats.npz"
191
+ f.parent.mkdir(parents=True, exist_ok=True)
192
+ n = int(self.ep_to[-1])
193
+ if f.exists():
194
+ try:
195
+ c = np.load(f)
196
+ if c["mu"].shape == (N_TOK, D_TOK) and int(c["version"]) == STATS_VERSION \
197
+ and float(c["sd_floor"]) == SD_FLOOR and float(c["z_clip"]) == Z_CLIP:
198
+ print(f"[data] token normalisation loaded from {f} (sd floor {SD_FLOOR}, clip {Z_CLIP})", flush=True)
199
+ return {k: c[k] for k in ("mu", "sd", "pr_mu", "pr_sd")}
200
+ print(f"[data] token stats {f} are an older version; refitting", flush=True)
201
+ except Exception as e: # a half-written file from a concurrent job: refit
202
+ print(f"[data] token stats unreadable ({e}); refitting", flush=True)
203
+ idx = np.arange(0, n, max(1, min(stride, max(n // 64, 1))))
204
+ x = np.asarray(self.tok[self._rows(idx)], np.float32)
205
+ mu = x.mean(0); sd_raw = x.std(0); sd = np.maximum(sd_raw, SD_FLOOR)
206
+ if self.proprio is not None:
207
+ p = np.asarray(self.proprio[idx], np.float32)
208
+ pr_mu, pr_sd = p.mean(0), np.maximum(p.std(0), SD_FLOOR)
209
+ else:
210
+ pr_mu = np.zeros(0, np.float32); pr_sd = np.ones(0, np.float32)
211
+ st = {"mu": mu.astype(np.float32), "sd": sd.astype(np.float32),
212
+ "pr_mu": pr_mu.astype(np.float32), "pr_sd": pr_sd.astype(np.float32)}
213
+ n_floor = int((sd_raw < SD_FLOOR).sum())
214
+ try:
215
+ tmp = f.with_name(f"tok_stats.{_os.getpid()}.tmp.npz")
216
+ np.savez(tmp, n=len(idx), version=STATS_VERSION, sd_floor=SD_FLOOR, z_clip=Z_CLIP,
217
+ rho_floor=RHO_FLOOR, y_clip=Y_CLIP, sd_raw=sd_raw.astype(np.float32), **st)
218
+ _os.replace(tmp, f) # atomic: concurrent jobs
219
+ (f.parent / "TOK_STATS.json").write_text(json.dumps({
220
+ "file": "tok_stats.npz", "version": STATS_VERSION, "n_frames": int(len(idx)),
221
+ "stride": int(idx[1] - idx[0]) if len(idx) > 1 else 1,
222
+ "rule": "x = clip((tok - mu) / max(sd, sd_floor), -z_clip, z_clip), per (token position, channel); "
223
+ "proprio: per dim, same floor/clip",
224
+ "sd_floor": SD_FLOOR, "z_clip": Z_CLIP,
225
+ "residual": "y = clip((x_fut - x_now) / max(rho, rho_floor), -y_clip, y_clip), rho = running "
226
+ "per-(token, channel) RMS of the residual",
227
+ "rho_floor": RHO_FLOOR, "y_clip": Y_CLIP,
228
+ "n_token_channels_at_sd_floor": n_floor,
229
+ "sd_raw_min": float(sd_raw.min()), "sd_raw_p01": float(np.percentile(sd_raw, 1)),
230
+ "abs_z_max_on_fit_frames": float(np.abs((x - mu) / sd).max())}, indent=1))
231
+ print(f"[data] token normalisation fitted on {len(idx)} frames -> {f} "
232
+ f"({n_floor} token-channels at the sd floor {SD_FLOOR}; z clipped to +-{Z_CLIP})", flush=True)
233
+ except OSError as e:
234
+ print(f"[data] token normalisation fitted but not cached ({e})", flush=True)
235
+ return st
236
+
237
+ def _chunk_at(self, idx, ep_i, chunk_len=None):
238
+ cl = self.chunk if chunk_len is None else chunk_len
239
+ out = np.empty((len(idx), cl * self.adim), np.float32)
240
+ for j, (t, e) in enumerate(zip(idx, ep_i)):
241
+ hi = int(self.ep_to[e]); take = min(cl, hi - t)
242
+ a = np.asarray(self.act[t:t + take], np.float32)
243
+ if take < cl:
244
+ a = np.concatenate([a, np.repeat(a[-1:], cl - take, 0)], 0)
245
+ out[j] = a.reshape(-1)
246
+ return out
247
+
248
+ def _rows(self, idx):
249
+ """cache frame indices -> rows of the token file (identity unless a row map is in use)."""
250
+ return idx if self.tok_rows is None else self.tok_rows[idx]
251
+
252
+ def _tok(self, idx):
253
+ """RAW fp16 tokens for a set of rows (gathered in sorted order for locality)."""
254
+ idx = self._rows(np.asarray(idx, np.int64))
255
+ order = np.argsort(idx, kind="stable")
256
+ g = np.asarray(self.tok[idx[order]])
257
+ out = np.empty_like(g); out[order] = g
258
+ return out
259
+
260
+ def _pr(self, idx):
261
+ if self.proprio is None:
262
+ return np.zeros((len(idx), 0), np.float32)
263
+ return np.asarray(self.proprio[idx], np.float32)
264
+
265
+ def draw(self, batch, rng, beta_lo, beta_hi, split="train"):
266
+ """Index-level draw (no I/O): the (t, K, beta) tuple per row."""
267
+ eps_pool = self.train_eps if split == "train" else self.val_eps
268
+ w = self.ep_len[eps_pool].astype(np.float64); w /= w.sum()
269
+ e = rng.choice(eps_pool, size=batch, p=w)
270
+ lo = self.ep_from[e]; hi = self.ep_to[e]
271
+ t = lo + (rng.random(batch) * (hi - lo)).astype(np.int64)
272
+ beta = rng.uniform(beta_lo, beta_hi, size=batch)
273
+ fut = truncated_geometric_future(t, hi, beta, rng.random(batch))
274
+ return e, t, fut, beta
275
+
276
+ def gather(self, e, t, fut, beta, with_fut=True):
277
+ """CPU tensors for a draw. Tokens stay fp16 (normalised on the device)."""
278
+ out = {"tok_now": torch.from_numpy(self._tok(t)),
279
+ "pr_now": torch.from_numpy(self._pr(t)),
280
+ "a_now": torch.from_numpy(self._chunk_at(t, e)),
281
+ "task": torch.from_numpy(self.ep_task[e]).long(),
282
+ "beta": torch.from_numpy(np.asarray(beta)).float(),
283
+ "r_now": torch.from_numpy(self.r[t]),
284
+ "succ": torch.from_numpy(self.ep_success[e].astype(np.float32)),
285
+ "to_end": torch.from_numpy((self.ep_to[e] - t).astype(np.float32)),
286
+ "t_idx": t, "ep": e, "fut_idx": fut}
287
+ if with_fut:
288
+ out["tok_fut"] = torch.from_numpy(self._tok(fut))
289
+ out["pr_fut"] = torch.from_numpy(self._pr(fut))
290
+ out["r_fut"] = torch.from_numpy(self.r[fut])
291
+ return out
292
+
293
+ def sample(self, batch, rng, beta_lo, beta_hi, split="train", device="cpu"):
294
+ e, t, fut, beta = self.draw(batch, rng, beta_lo, beta_hi, split)
295
+ b = self.gather(e, t, fut, beta)
296
+ return {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v)
297
+ for k, v in b.items()}
298
+
299
+ def sample_frames(self, batch, rng, split="train", device="cpu"):
300
+ e, t, _, _ = self.draw(batch, rng, 0.5, 0.5, split)
301
+ b = self.gather(e, t, t, np.zeros(batch), with_fut=False)
302
+ b["x"] = b.pop("tok_now"); b["a"] = b.pop("a_now"); b["r"] = b.pop("r_now")
303
+ return {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v)
304
+ for k, v in b.items()}
305
+
306
+
307
+ class Normalizer(nn.Module):
308
+ """z-scoring of raw tokens / proprio, stored in the checkpoint as buffers."""
309
+
310
+ def __init__(self, stats):
311
+ super().__init__()
312
+ self.register_buffer("mu", torch.as_tensor(stats["mu"], dtype=torch.float32))
313
+ self.register_buffer("sd", torch.as_tensor(stats["sd"], dtype=torch.float32))
314
+ self.register_buffer("pr_mu", torch.as_tensor(stats["pr_mu"], dtype=torch.float32))
315
+ self.register_buffer("pr_sd", torch.as_tensor(stats["pr_sd"], dtype=torch.float32))
316
+
317
+ def tok(self, x): # raw -> z-scored, sd floored (in the stats) and clipped
318
+ return ((x.float() - self.mu) / self.sd.clamp_min(SD_FLOOR)).clamp(-Z_CLIP, Z_CLIP)
319
+
320
+ def tok_inv(self, z): # z-scored -> raw
321
+ return z.float() * self.sd.clamp_min(SD_FLOOR) + self.mu
322
+
323
+ def pr(self, p):
324
+ return ((p.float() - self.pr_mu) / self.pr_sd.clamp_min(SD_FLOOR)).clamp(-Z_CLIP, Z_CLIP)
325
+
326
+ def pr_inv(self, z):
327
+ return z.float() * self.pr_sd.clamp_min(SD_FLOOR) + self.pr_mu
328
+
329
+
330
+ # --------------------------------------------------------------------------- #
331
+ # the DINO-WM ViT (vit-pytorch style: PreNorm, Attention, FeedForward, dropout)
332
+ # --------------------------------------------------------------------------- #
333
+ class Attention(nn.Module):
334
+ def __init__(self, dim, heads=16, dim_head=64, dropout=0.0):
335
+ super().__init__()
336
+ inner = heads * dim_head
337
+ self.heads, self.dim_head, self.dropout = heads, dim_head, dropout
338
+ self.norm = nn.LayerNorm(dim)
339
+ self.to_qkv = nn.Linear(dim, inner * 3, bias=False)
340
+ self.to_out = nn.Sequential(nn.Linear(inner, dim), nn.Dropout(dropout))
341
+
342
+ def forward(self, x):
343
+ B, N, _ = x.shape
344
+ q, k, v = self.to_qkv(self.norm(x)).chunk(3, -1)
345
+ q, k, v = (t.view(B, N, self.heads, self.dim_head).transpose(1, 2) for t in (q, k, v))
346
+ o = F.scaled_dot_product_attention(q, k, v, dropout_p=self.dropout if self.training else 0.0)
347
+ return self.to_out(o.transpose(1, 2).reshape(B, N, -1))
348
+
349
+
350
+ class FeedForward(nn.Module):
351
+ def __init__(self, dim, hidden, dropout=0.0):
352
+ super().__init__()
353
+ self.net = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, hidden), nn.GELU(),
354
+ nn.Dropout(dropout), nn.Linear(hidden, dim), nn.Dropout(dropout))
355
+
356
+ def forward(self, x):
357
+ return self.net(x)
358
+
359
+
360
+ class Transformer(nn.Module):
361
+ def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout=0.0, grad_ckpt=False):
362
+ super().__init__()
363
+ self.layers = nn.ModuleList([nn.ModuleList([Attention(dim, heads, dim_head, dropout),
364
+ FeedForward(dim, mlp_dim, dropout)])
365
+ for _ in range(depth)])
366
+ self.norm = nn.LayerNorm(dim)
367
+ self.grad_ckpt = grad_ckpt
368
+
369
+ @staticmethod
370
+ def _block(attn, ff, x):
371
+ x = x + attn(x)
372
+ return x + ff(x)
373
+
374
+ def forward(self, x):
375
+ for attn, ff in self.layers:
376
+ if self.grad_ckpt and self.training and torch.is_grad_enabled():
377
+ x = torch.utils.checkpoint.checkpoint(self._block, attn, ff, x, use_reentrant=False)
378
+ else:
379
+ x = self._block(attn, ff, x)
380
+ return self.norm(x)
381
+
382
+
383
+ class DWM(nn.Module):
384
+ """Successor flow in token space with the DINO-WM predictor as the velocity network."""
385
+
386
+ def __init__(self, n_tok=N_TOK, d_tok=D_TOK, n_pr=9, d_act=56, depth=6, heads=16,
387
+ dim_head=64, mlp_dim=2048, dropout=0.1, d_act_emb=16, d_pr_emb=8,
388
+ d_beta_emb=8, d_time_emb=8, n_fourier=6, emb_dropout=0.1, grad_ckpt=False,
389
+ tok_drop=0.0):
390
+ super().__init__()
391
+ self.tok_drop = tok_drop # training-time dropout of WHOLE "now" tokens (regulariser probe)
392
+ self.n_tok, self.d_tok, self.n_pr, self.d_act = n_tok, d_tok, n_pr, d_act
393
+ self.d_cond = d_act_emb + d_pr_emb + d_beta_emb + d_time_emb
394
+ self.dim = d_tok + self.d_cond # 424
395
+ self.d_time_emb = d_time_emb; self.n_fourier = n_fourier
396
+ self.act_emb = nn.Linear(d_act, d_act_emb)
397
+ self.pr_emb = nn.Linear(max(n_pr, 1), d_pr_emb)
398
+ self.beta_emb = nn.Linear(2 * n_fourier + 1, d_beta_emb)
399
+ # the extra proprio token (now: embedded proprio; future: embedded noisy residual)
400
+ self.pr_tok_now = nn.Linear(max(n_pr, 1), d_tok)
401
+ self.pr_tok_fut = nn.Linear(max(n_pr, 1), d_tok)
402
+ self.n_seq = n_tok + 1
403
+ self.pos = nn.Parameter(torch.randn(1, self.n_seq, self.dim) * 0.02)
404
+ self.type_emb = nn.Parameter(torch.randn(2, 1, self.dim) * 0.02)
405
+ self.drop = nn.Dropout(emb_dropout)
406
+ self.transformer = Transformer(self.dim, depth, heads, dim_head, mlp_dim, dropout, grad_ckpt)
407
+ self.head_tok = nn.Linear(self.dim, d_tok)
408
+ self.head_pr = nn.Linear(self.dim, max(n_pr, 1))
409
+
410
+ def _cond(self, a, pr, beta, k):
411
+ c = torch.cat([self.act_emb(a), self.pr_emb(pr if self.n_pr else torch.zeros_like(a[:, :1])),
412
+ self.beta_emb(beta_fourier(beta.float(), self.n_fourier)),
413
+ time_embed(k.float(), self.d_time_emb)], -1)
414
+ return c
415
+
416
+ def forward(self, tok_now, pr_now, a, beta, xk_tok, xk_pr, k):
417
+ """tok_now [B,514,384] z-scored; pr_now [B,9] z-scored; a [B,56]; beta [B];
418
+ xk_tok [B,514,384] noisy residual; xk_pr [B,9]; k [B] flow time (1 = noise).
419
+ -> (v_tok [B,514,384], v_pr [B,9])"""
420
+ B = tok_now.shape[0]
421
+ pr_in = pr_now if self.n_pr else torch.zeros(B, 1, device=tok_now.device)
422
+ xk_pr_in = xk_pr if self.n_pr else torch.zeros(B, 1, device=tok_now.device)
423
+ if self.tok_drop > 0 and self.training:
424
+ keep = (torch.rand(B, tok_now.shape[1], 1, device=tok_now.device) >= self.tok_drop).to(tok_now.dtype)
425
+ tok_now = tok_now * keep # dropped token -> 0 = the mean token (z-scored space)
426
+ now = torch.cat([tok_now, self.pr_tok_now(pr_in)[:, None]], 1) # [B,515,384]
427
+ fut = torch.cat([xk_tok, self.pr_tok_fut(xk_pr_in)[:, None]], 1) # [B,515,384]
428
+ c = self._cond(a, pr_in, beta, k)[:, None].expand(-1, self.n_seq, -1) # [B,515,40]
429
+ now = torch.cat([now, c], -1) + self.pos + self.type_emb[0]
430
+ fut = torch.cat([fut, c], -1) + self.pos + self.type_emb[1]
431
+ h = self.transformer(self.drop(torch.cat([now, fut], 1))) # [B,1030,424]
432
+ hf = h[:, self.n_seq:]
433
+ v_tok = self.head_tok(hf[:, :self.n_tok])
434
+ v_pr = self.head_pr(hf[:, self.n_tok])
435
+ return v_tok, (v_pr if self.n_pr else v_pr[:, :0])
436
+
437
+
438
+ class DWMReward(nn.Module):
439
+ """R(x): mean-pooled tokens per camera (2 x 384) ++ proprio -> MLP 512 x 2 -> logit."""
440
+
441
+ def __init__(self, n_tok=N_TOK, d_tok=D_TOK, n_pr=9, width=512):
442
+ super().__init__()
443
+ self.n_tok, self.n_pr = n_tok, n_pr
444
+ self.net = nn.Sequential(nn.Linear(2 * d_tok + n_pr, width), nn.SiLU(),
445
+ nn.Linear(width, width), nn.SiLU(), nn.Linear(width, 1))
446
+
447
+ @staticmethod
448
+ def pool(tok):
449
+ h = tok.shape[1] // 2
450
+ return torch.cat([tok[:, :h].mean(1), tok[:, h:].mean(1)], -1)
451
+
452
+ def forward(self, tok, pr):
453
+ x = self.pool(tok.float())
454
+ if self.n_pr:
455
+ x = torch.cat([x, pr.float()], -1)
456
+ return self.net(x).squeeze(-1)
457
+
458
+
459
+ # --------------------------------------------------------------------------- #
460
+ # sampling
461
+ # --------------------------------------------------------------------------- #
462
+ @torch.no_grad()
463
+ def sample_future_dwm(model, tok_now, pr_now, a, beta, rms_tok, rms_pr, n_steps=8, n=1,
464
+ x0=None, micro=512, autocast=None, y_clip=Y_CLIP):
465
+ """Euler ODE sample of the token residual, returned as ABSOLUTE z-scored tokens/proprio.
466
+ x0: optional (noise_tok [rows,514,384], noise_pr [rows,9]) for common random numbers.
467
+ autocast: zero-arg callable returning a context manager (default: bf16 on cuda).
468
+ y_clip: the integrated residual is clamped to +-y_clip (rho units) after every Euler step -- the
469
+ training target lives in that box, so anything outside it is a diverged velocity, not a
470
+ successor (stream B measured the MLP flow's velocity growing 170 -> 8500 over 8 steps on
471
+ held-out episodes; this bounds the damage at read-out). 0 = off.
472
+ Returns (tok_fut_z [B*n,514,384], pr_fut_z [B*n,9])."""
473
+ B = tok_now.shape[0]
474
+ if n > 1:
475
+ tok_now = tok_now.repeat_interleave(n, 0); pr_now = pr_now.repeat_interleave(n, 0)
476
+ a = a.repeat_interleave(n, 0); beta = beta.repeat_interleave(n, 0)
477
+ R = tok_now.shape[0]
478
+ dev = tok_now.device
479
+ if x0 is None:
480
+ xt = torch.randn(R, model.n_tok, model.d_tok, device=dev)
481
+ xp = torch.randn(R, model.n_pr, device=dev)
482
+ else:
483
+ xt, xp = x0[0].clone(), x0[1].clone()
484
+ if autocast is None:
485
+ autocast = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) if dev.type == "cuda" \
486
+ else (lambda: torch.autocast("cpu", enabled=False))
487
+ for s in range(n_steps):
488
+ kk = 1.0 - s / n_steps
489
+ for i in range(0, R, micro):
490
+ sl = slice(i, i + micro)
491
+ k = torch.full((xt[sl].shape[0],), kk, device=dev)
492
+ with autocast():
493
+ vt, vp = model(tok_now[sl], pr_now[sl], a[sl], beta[sl], xt[sl], xp[sl], k)
494
+ xt[sl] = (xt[sl] + vt.float() / n_steps).clamp(-y_clip, y_clip) if y_clip else xt[sl] + vt.float() / n_steps
495
+ xp[sl] = (xp[sl] + vp.float() / n_steps).clamp(-y_clip, y_clip) if y_clip else xp[sl] + vp.float() / n_steps
496
+ return tok_now + xt * rms_tok, pr_now + xp * rms_pr
497
+
498
+
499
+ # --------------------------------------------------------------------------- #
500
+ # synthetic cache with the real layout (tests, and development before stream B's dump)
501
+ # --------------------------------------------------------------------------- #
502
+ def make_synthetic_cache(root, n_ep=6, ep_len=(30, 50), seed=0, success_rate=0.5, n_pr=9, adim=7):
503
+ """Writes meta.npz, act.f32.npy, proprio.f32.npy, z.f16.npy (pooled, via the reference
504
+ GeM), tokens/tok.f16.npy [N,514,384], tokens/TOKENS.json. Tokens drift smoothly along
505
+ the episode so a successor has something to learn."""
506
+ root = Path(root); (root / "tokens").mkdir(parents=True, exist_ok=True)
507
+ rng = np.random.default_rng(seed)
508
+ lens = rng.integers(ep_len[0], ep_len[1] + 1, size=n_ep).astype(np.int64)
509
+ ep_to = np.cumsum(lens); ep_from = ep_to - lens; N = int(ep_to[-1])
510
+ tok = np.lib.format.open_memmap(root / "tokens" / "tok.f16.npy", mode="w+",
511
+ dtype=np.float16, shape=(N, N_TOK, D_TOK))
512
+ act = np.zeros((N, adim), np.float32); pr = np.zeros((N, n_pr), np.float32)
513
+ base = rng.normal(0, 1, size=(N_TOK, D_TOK)).astype(np.float32)
514
+ base[1:1 + N_PATCH] = np.abs(base[1:1 + N_PATCH]) + 0.5 # patches mostly positive (GeM)
515
+ base[2 + N_PATCH:] = np.abs(base[2 + N_PATCH:]) + 0.5
516
+ succ = rng.random(n_ep) < success_rate
517
+ for i in range(n_ep):
518
+ s, e = int(ep_from[i]), int(ep_to[i]); T = e - s
519
+ a = np.tanh(rng.normal(0, 0.7, size=(T, adim))).astype(np.float32)
520
+ a = np.cumsum(a, 0) / np.sqrt(np.arange(1, T + 1))[:, None] # correlated in time
521
+ act[s:e] = np.clip(a, -1, 1)
522
+ drift = rng.normal(0, 0.3, size=(D_TOK,)).astype(np.float32)
523
+ for t in range(T):
524
+ frac = t / max(T - 1, 1)
525
+ x = base + frac * drift[None] + 0.05 * rng.normal(size=(N_TOK, D_TOK)).astype(np.float32)
526
+ x += 0.2 * np.cumsum(act[s:s + t + 1], 0)[-1].sum() * (base > 0) * 0.01
527
+ tok[s + t] = x.astype(np.float16)
528
+ pr[s + t] = np.concatenate([np.cumsum(act[s:s + t + 1, :3], 0)[-1] * 0.05,
529
+ np.array([1, 0, 0, 0], np.float32),
530
+ np.array([0.04 - 0.03 * frac, -0.04 + 0.03 * frac])])[:n_pr]
531
+ tok.flush()
532
+ # pooled pack with the reference formula (torch avg_pool2d, as obs_core.py)
533
+ z = np.zeros((N, 4 * D_TOK), np.float16)
534
+ for i in range(0, N, 64):
535
+ t = torch.from_numpy(np.asarray(tok[i:i + 64], np.float32))
536
+ parts = []
537
+ for c0, (p0, p1) in ((TOK_LAYOUT["agent_cls"], TOK_LAYOUT["agent_patch"]),
538
+ (TOK_LAYOUT["wrist_cls"], TOK_LAYOUT["wrist_patch"])):
539
+ p = t[:, p0:p1].reshape(t.shape[0], 16, 16, -1).clamp(min=1e-6).permute(0, 3, 1, 2)
540
+ g = F.avg_pool2d(p.pow(4), (16, 16)).pow(1 / 4).reshape(t.shape[0], -1)
541
+ parts += [t[:, c0], g]
542
+ z[i:i + 64] = torch.cat(parts, -1).numpy().astype(np.float16)
543
+ np.save(root / "z.f16.npy", z)
544
+ np.save(root / "act.f32.npy", act); np.save(root / "proprio.f32.npy", pr)
545
+ np.savez(root / "meta.npz", ep_from=ep_from, ep_to=ep_to, ep_len=lens,
546
+ ep_task=np.zeros(n_ep, np.int64), ep_success=succ, ep_demo=np.zeros(n_ep, bool),
547
+ tasks=np.array(["synthetic"]), dim=4 * D_TOK, adim=adim, stride=1, n_frames=N)
548
+ # goal-state label: the last 30 % of frames of every successful episode (env-success-by-replay stand-in)
549
+ goal = np.zeros(N, np.uint8); first = np.full(n_ep, -1, np.int64)
550
+ for i in range(n_ep):
551
+ if succ[i]:
552
+ s, e = int(ep_from[i]), int(ep_to[i]); first[i] = s + int(0.7 * (e - s)); goal[first[i]:e] = 1
553
+ first[i] -= s
554
+ np.savez(root / "goal.npz", goal=goal, first_success=first, label="synthetic")
555
+ (root / "tokens" / "TOKENS.json").write_text(json.dumps({
556
+ "file": "tok.f16.npy", "shape": [N, N_TOK, D_TOK], "dtype": "float16",
557
+ "layout": "[agentview CLS, 256 agentview patches, wrist CLS, 256 wrist patches]",
558
+ "encoder": "synthetic", "synthetic": True}, indent=1))
559
+ (root / "PACK.json").write_text(json.dumps({"encoder": "synthetic", "cam_res": 84,
560
+ "frames": N, "episodes": n_ep,
561
+ "sd_floor": SD_FLOOR, "z_clip": Z_CLIP}, indent=1))
562
+ return root
frozen/rsm_libero_freeze_20261002/dwm_readout.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage-3 read-out of a DWM checkpoint: Q̄_β(x, A) = E_{x' ~ d_β(.|x, A)}[σ(R(x'))].
2
+
3
+ from dwm_readout import load_critic_dwm
4
+ crit = load_critic_dwm("runs/<task>/rsm/DWM/ckpt_best.pt", device)
5
+ q = crit.q(x_tokens, a_chunk, beta, n_particles=16, crn_seed=0, depth=1, mode="d1",
6
+ proprio=proprio) # -> [B] in [0, 1]
7
+
8
+ Inputs are RAW: x_tokens [B, 514, 384] DINOv2 ViT-S/14 tokens at 224 input, in the cache order
9
+ [agentview CLS, 256 agentview patches, wrist CLS, 256 wrist patches] (fp16/fp32 both fine);
10
+ proprio [B, 9] = robot0_eef_pos(3) ‖ robot0_eef_quat(4) ‖ robot0_gripper_qpos(2), un-normalised;
11
+ a_chunk [B, 56] = the next 8 actions flattened (7-d OSC_POSE, in [-1, 1]); beta a float.
12
+
13
+ mode="d1" one hop from the query chunk, mean over particles of σ(R(x')).
14
+ mode="fold" is_ope.q_fold's product fold over `depth` hops: hop 1 from the query chunk,
15
+ hop k+1 from `hop_policy` evaluated on the POOLED 1545-d state of hop k
16
+ (pool_tokens: [CLS ‖ GeM(patches)] per camera ‖ proprio, RAW units, the same
17
+ vector cache/<task>/z.f16.npy ‖ proprio.f32.npy holds).
18
+ Q = c_L; Q = c_k + (1 - c_k) γ^h Q (h = 1/(1-β)), mean over particles.
19
+ hop_policy(pooled_raw [R, 1545], eps [R, d_act]) -> a_chunk [R, 56]; the caller
20
+ applies its own feature normalisation (feat_stats.npz) inside that callable.
21
+ Optional attribute hop_policy.d_act (default 56) sizes the CRN noise eps.
22
+
23
+ PRIMARY read-out for planning (orchestrator 13:05): the dense expert-membership head with LOGIT averaging,
24
+ q, q_logit = crit.q(x_tokens, a_chunk, beta, ..., return_logit=True) # rank candidates by q_logit
25
+ q_logit = mean over particles of R(x'_i) (no sigmoid), which does not saturate/tie at 1.0 the way q does.
26
+ Temperature: calib_dwm.py fits T on held-out frames -> runs/<task>/rsm/DWM/calib.json; load_critic_dwm reads it
27
+ (crit.temperature) and q = mean_i sigmoid(logit_i / T); q(..., temperature=T) overrides.
28
+ Two-stage screening: q(..., n_particles=4, rescore_top=16, n_particles_rescore=64) scores all candidates with 4
29
+ particles, rescores the top-16 by q_logit with 64 particles, returns full-length arrays.
30
+
31
+ reward="goal_clf", reward_path="runs/<task>/goal_clf/clf.pt" (PRIVILEGED ABLATION: env success via state
32
+ replay, which RISE's baselines never see): the read-out reward is the standalone GOAL-STATE
33
+ classifier (train_goal_clf.py; env-success-by-replay label) on the pooled 1545-d state of every sampled future
34
+ instead of the checkpoint's own head; return_logit=True also returns q_logit (mean logit over particles).
35
+
36
+ Common random numbers: crn_seed seeds a torch.Generator; every particle i draws ONE noise
37
+ tensor shared by all B rows (candidates), so Q differences between candidates at the same
38
+ state are paired (same convention as is_ope.q_fold(crn=True)). Euler ODE with `flow_steps`
39
+ (8) steps in token space; the EMA weights are used.
40
+ """
41
+ from __future__ import annotations
42
+ import sys as _sys, os as _os
43
+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
44
+ from pathlib import Path
45
+ import numpy as np
46
+ import torch
47
+
48
+ from dwm_model import (DWM, DWMReward, Normalizer, pool_tokens, sample_future_dwm, N_TOK, D_TOK)
49
+
50
+
51
+ class DWMCritic:
52
+ def __init__(self, ck, device, use_ema=True):
53
+ a = ck["arch"]
54
+ self.device = torch.device(device)
55
+ self.n_pr, self.d_act = int(a["n_pr"]), int(a["d_act"])
56
+ self.flow = DWM(a["n_tok"], a["d_tok"], a["n_pr"], a["d_act"], depth=a["depth"],
57
+ heads=a["heads"], dim_head=a["dim_head"], mlp_dim=a["mlp_dim"],
58
+ dropout=a["dropout"], emb_dropout=a["dropout"]).to(self.device)
59
+ self.rew = DWMReward(a["n_tok"], a["d_tok"], a["n_pr"]).to(self.device)
60
+ self.flow.load_state_dict(ck["flow_ema" if use_ema else "flow"])
61
+ self.rew.load_state_dict(ck["rew_ema" if use_ema else "rew"])
62
+ self.norm = Normalizer({k: v.numpy() if torch.is_tensor(v) else v for k, v in ck["norm"].items()}).to(self.device)
63
+ self.rms_tok = ck["rms_tok"].to(self.device); self.rms_pr = ck["rms_pr"].to(self.device)
64
+ self.config = dict(ck["config"]); self.step = int(ck.get("step", -1))
65
+ self.temperature = 1.0; self.calib = None
66
+ self.q_action_winrate = ck.get("q_action_winrate", float("nan"))
67
+ for m in (self.flow, self.rew):
68
+ m.eval()
69
+ for p in m.parameters():
70
+ p.requires_grad_(False)
71
+ self.autocast = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) if self.device.type == "cuda" \
72
+ else (lambda: torch.autocast("cpu", enabled=False))
73
+
74
+ # ---- helpers ----
75
+ def _prep(self, x_tokens, proprio, a_chunk):
76
+ x = torch.as_tensor(x_tokens).to(self.device)
77
+ assert x.ndim == 3 and x.shape[1:] == (N_TOK, D_TOK), f"x_tokens must be [B,{N_TOK},{D_TOK}], got {tuple(x.shape)}"
78
+ B = x.shape[0]
79
+ if self.n_pr:
80
+ assert proprio is not None, "this checkpoint models proprio: pass proprio=[B, 9]"
81
+ p = torch.as_tensor(proprio).to(self.device).float().view(B, self.n_pr)
82
+ else:
83
+ p = torch.zeros(B, 0, device=self.device)
84
+ a = torch.as_tensor(a_chunk).to(self.device).float().view(B, -1)
85
+ assert a.shape[1] == self.d_act, f"a_chunk must be [B,{self.d_act}] (chunk x adim flattened)"
86
+ return self.norm.tok(x), self.norm.pr(p), a
87
+
88
+ @torch.no_grad()
89
+ def reward(self, x_tokens, proprio=None, reward="head", reward_path=None):
90
+ """σ(R(x)) on RAW tokens/proprio -> [B]; reward='goal_clf' uses the goal classifier."""
91
+ tz, pz, _ = self._prep(x_tokens, proprio, torch.zeros(len(x_tokens), self.d_act))
92
+ if reward == "goal_clf":
93
+ if reward_path is not None and getattr(self, "goal_clf", {}).get("path") != str(reward_path):
94
+ self.load_goal_clf(reward_path)
95
+ return torch.sigmoid(self.goal_logit(tz, pz))
96
+ with self.autocast():
97
+ return torch.sigmoid(self.rew(tz, pz).float())
98
+
99
+ @torch.no_grad()
100
+ def sample_future(self, x_tokens, a_chunk, beta, proprio=None, n=1, crn_seed=None, flow_steps=8, micro=512):
101
+ """Raw-unit successor samples: (tokens [B*n,514,384], proprio [B*n,9])."""
102
+ tz, pz, a = self._prep(x_tokens, proprio, a_chunk)
103
+ B = tz.shape[0]
104
+ bq = torch.full((B,), float(beta), device=self.device)
105
+ x0 = self._crn_noise(B, n, crn_seed) if crn_seed is not None else None
106
+ xt, xp = sample_future_dwm(self.flow, tz, pz, a, bq, self.rms_tok, self.rms_pr, flow_steps, n=n,
107
+ x0=x0, micro=micro, autocast=self.autocast)
108
+ return self.norm.tok_inv(xt), self.norm.pr_inv(xp)
109
+
110
+ # ---- goal-state classifier read-out (orchestrator 2026-09-18: R must be a goal classifier) ----
111
+ def load_goal_clf(self, path):
112
+ """train_goal_clf.py checkpoint: MLP on the pooled z-scored state; cached on the critic."""
113
+ ck = torch.load(str(path), map_location="cpu", weights_only=False)
114
+ c = ck["config"]
115
+ from train_goal_clf import build_net
116
+ net = build_net(c["d_in"], c["width"], c["depth"]).to(self.device)
117
+ net.load_state_dict(ck["net"]); net.eval()
118
+ for p in net.parameters():
119
+ p.requires_grad_(False)
120
+ nm = ck["norm"]
121
+ self.goal_clf = {"net": net, "mu": nm["mu"].to(self.device), "sd": nm["sd"].to(self.device),
122
+ "z_clip": float(nm["z_clip"]), "sd_floor": float(nm.get("sd_floor", 0.01)),
123
+ "path": str(path), "config": c}
124
+ return self.goal_clf
125
+
126
+ def goal_logit(self, tz, pz):
127
+ """logit of 'goal state' for z-scored token/proprio tensors (sampled futures or real frames)."""
128
+ g = self.goal_clf
129
+ pooled = pool_tokens(self.norm.tok_inv(tz), self.norm.pr_inv(pz) if self.n_pr else None) # raw 1545
130
+ x = (pooled - g["mu"]) / g["sd"].clamp_min(g["sd_floor"])
131
+ if g["z_clip"]:
132
+ x = x.clamp(-g["z_clip"], g["z_clip"])
133
+ return g["net"](x).squeeze(-1).float()
134
+
135
+ def _gen(self, seed):
136
+ g = torch.Generator(device=self.device); g.manual_seed(int(seed)); return g
137
+
138
+ def _crn_noise(self, B, n, seed, gen=None):
139
+ """[n, ...] noise per particle, tiled over the B rows (rows are repeat_interleave'd
140
+ by particle, so particle i of row b sits at b*n + i -> tile with .repeat(B, ...))."""
141
+ g = gen if gen is not None else self._gen(seed)
142
+ nt = torch.randn(n, N_TOK, D_TOK, device=self.device, generator=g).repeat(B, 1, 1)
143
+ npr = torch.randn(n, self.n_pr, device=self.device, generator=g).repeat(B, 1)
144
+ return nt, npr
145
+
146
+ @torch.no_grad()
147
+ def q(self, x_tokens, a_chunk, beta, n_particles=16, crn_seed=0, depth=1, mode="d1",
148
+ proprio=None, hop_policy=None, gamma=0.99, flow_steps=8, micro=512, return_hops=False,
149
+ reward="head", reward_path=None, return_logit=False, temperature=None,
150
+ rescore_top=0, n_particles_rescore=0):
151
+ """Q̄ estimate per row. See the module docstring.
152
+ reward="head": the checkpoint's own reward head R (trained on the run's --reward-mode label).
153
+ reward="goal_clf": the standalone goal-state classifier (train_goal_clf.py; PRIVILEGED ablation) on the POOLED
154
+ state of each sampled future; reward_path = its clf.pt (loaded once and cached).
155
+ temperature: q = mean_i sigmoid(logit_i / T). None -> self.temperature (calib.json next to the checkpoint,
156
+ fitted by calib_dwm.py on held-out frames; 1.0 if absent). q_logit is the RAW mean logit (ranking is T-free).
157
+ rescore_top=K, n_particles_rescore=M: two-stage screening -- score every candidate with n_particles, keep the
158
+ top-K by q_logit, rescore those with M particles (CRN seed family crn_seed -> crn_seed*7919+1) and write the
159
+ rescored values back; non-rescored rows keep their stage-1 values. Full-length outputs.
160
+ return_logit=True -> (q, q_logit); return_hops=True -> (out, [c_k [B, n]]) of the stage-1 pass."""
161
+ if reward == "goal_clf":
162
+ if reward_path is not None and getattr(self, "goal_clf", {}).get("path") != str(reward_path):
163
+ self.load_goal_clf(reward_path)
164
+ assert getattr(self, "goal_clf", None), "reward='goal_clf' needs reward_path=<clf.pt> once"
165
+ elif reward != "head":
166
+ raise ValueError(f"reward {reward!r}: use 'head' or 'goal_clf'")
167
+ if mode == "d1":
168
+ depth = 1
169
+ elif mode not in ("fold", "mpc", "mpc_disc"):
170
+ # gen_q#273: "mpc" / "mpc_disc" are the MPC read-outs -- the SAME open-loop roll-out the fold
171
+ # performs, combined differently (terminal latent / discounted sum) instead of through the
172
+ # beta-hazard fold. Additive: "d1" and "fold" take byte-identical code paths.
173
+ raise ValueError(f"mode {mode!r}: use 'd1', 'fold', 'mpc' or 'mpc_disc'")
174
+ if depth > 1 and hop_policy is None:
175
+ raise ValueError("depth > 1 needs hop_policy(pooled_raw [R,1545], eps [R,d_act]) -> a_chunk")
176
+ T = float(self.temperature if temperature is None else temperature)
177
+ tz, pz, a = self._prep(x_tokens, proprio, a_chunk)
178
+ q, ql, cs = self._q_once(tz, pz, a, beta, int(n_particles), self._gen(crn_seed), depth, mode, hop_policy,
179
+ gamma, flow_steps, micro, reward, T)
180
+ if rescore_top and n_particles_rescore and rescore_top < tz.shape[0]:
181
+ top = torch.topk(ql, int(rescore_top)).indices
182
+ q2, ql2, _ = self._q_once(tz[top], pz[top], a[top], beta, int(n_particles_rescore),
183
+ self._gen(int(crn_seed) * 7919 + 1), depth, mode, hop_policy, gamma,
184
+ flow_steps, micro, reward, T)
185
+ q = q.clone(); ql = ql.clone(); q[top] = q2; ql[top] = ql2
186
+ out = (q, ql) if return_logit else q
187
+ if return_hops:
188
+ return out, cs
189
+ return out
190
+
191
+ # ---- the two things a different dynamics model has to change (gen_q#268) -------------------
192
+ # Factored out so DINO-WM (dinowm_readout.DINOWMCritic) can subclass this class and override
193
+ # ONLY the transition and the hop length, exactly as TDFlowAgent subclasses RSMAgent to override
194
+ # only the occupancy target. Everything else -- the fold algebra, the hop-policy chaining, the
195
+ # reward head, the normaliser, the temperature, the two-stage rescore -- is then literally the
196
+ # same code, which is what makes the two columns of a matched-proposer table comparable.
197
+ def _step(self, tzr, pzr, ar, bq, B, n, g, flow_steps, micro):
198
+ """One hop: a DRAW from the beta-discounted successor, by Euler-integrating the flow."""
199
+ x0 = self._crn_noise(B, n, None, gen=g)
200
+ return sample_future_dwm(self.flow, tzr, pzr, ar, bq, self.rms_tok, self.rms_pr, flow_steps,
201
+ n=1, x0=x0, micro=micro, autocast=self.autocast)
202
+
203
+ def _hop_frames(self, beta):
204
+ """Frames one hop spans, for the fold's per-hop discount gamma ** h."""
205
+ return 1.0 / (1.0 - float(beta))
206
+
207
+ def _q_once(self, tz, pz, a, beta, n, g, depth, mode, hop_policy, gamma, flow_steps, micro, reward, T):
208
+ B = tz.shape[0]
209
+ tzr = tz.repeat_interleave(n, 0); pzr = pz.repeat_interleave(n, 0); ar = a.repeat_interleave(n, 0)
210
+ bq = torch.full((B * n,), float(beta), device=self.device)
211
+ cs = []
212
+ for k in range(depth):
213
+ tzr, pzr = self._step(tzr, pzr, ar, bq, B, n, g, flow_steps, micro)
214
+ with self.autocast():
215
+ lg = self.goal_logit(tzr, pzr) if reward == "goal_clf" else self.rew(tzr, pzr).float()
216
+ cs.append(torch.sigmoid(lg / T))
217
+ if k == depth - 1:
218
+ break
219
+ pooled = pool_tokens(self.norm.tok_inv(tzr), self.norm.pr_inv(pzr) if self.n_pr else None)
220
+ d_act = int(getattr(hop_policy, "d_act", self.d_act))
221
+ eps = torch.randn(n, d_act, device=self.device, generator=g).repeat(B, 1)
222
+ ar = torch.as_tensor(hop_policy(pooled, eps)).to(self.device).float().view(B * n, -1)
223
+ assert ar.shape[1] == self.d_act, "hop_policy must return [R, chunk*adim] chunks"
224
+ if mode == "d1":
225
+ q = cs[0]
226
+ elif mode in ("mpc", "mpc_disc"):
227
+ # gen_q#273 -- MPC READ-OUTS. `cs[k]` is the reward head on the latent the model predicts
228
+ # after k+1 chunks of open-loop rolling, so the roll-out itself is unchanged; only the way the
229
+ # per-step rewards are combined differs from the fold above.
230
+ # mpc : the TERMINAL latent only -- score(s_K), K = depth chunks = the H frames the
231
+ # discount defines. This is what a world-model MPC objective is.
232
+ # mpc_disc : the discounted sum over the same roll-out with the SAME gamma that defines H,
233
+ # normalised by sum_k gamma**(h k) so it stays a probability in [0, 1] and is
234
+ # comparable ACROSS horizons (an unnormalised sum grows with K and would rank
235
+ # longer horizons higher for arithmetic reasons alone).
236
+ h = self._hop_frames(beta)
237
+ if mode == "mpc":
238
+ q = cs[-1]
239
+ else:
240
+ w = [float(gamma) ** (h * k) for k in range(len(cs))]
241
+ tot = float(sum(w))
242
+ q = sum(wk * c for wk, c in zip(w, cs)) / tot
243
+ else:
244
+ h = self._hop_frames(beta)
245
+ q = torch.zeros_like(cs[-1])
246
+ for c in reversed(cs):
247
+ q = c + (1.0 - c) * (gamma ** h) * q
248
+ q = torch.nan_to_num(q, nan=0.0).clamp(0.0, 1.0).view(B, n).mean(1)
249
+ q_logit = torch.nan_to_num(lg, nan=0.0).view(B, n).mean(1)
250
+ return q, q_logit, [c.view(B, n) for c in cs]
251
+
252
+
253
+ def load_critic_dwm(path, device="cuda", use_ema=True, calib="auto") -> DWMCritic:
254
+ """calib: "auto" reads <dir of path>/calib.json (calib_dwm.py) and sets crit.temperature = T if present;
255
+ a float sets T directly; None/False leaves T = 1.0."""
256
+ ck = torch.load(str(path), map_location="cpu", weights_only=False)
257
+ _m = str(ck.get("model", "dwm"))
258
+ if _m != "dwm":
259
+ raise RuntimeError(
260
+ f"{path} is a '{_m}' checkpoint (config dynamics="
261
+ f"{dict(ck.get('config', {})).get('dynamics')!r}), not a flow DWM. Load it with the "
262
+ f"read-out for that model (dinowm_readout.load_critic_dwm) -- Euler-integrating a "
263
+ f"network that was never trained as a velocity field would report a number that is "
264
+ f"neither method.")
265
+ crit = DWMCritic(ck, device, use_ema=use_ema)
266
+ if isinstance(calib, (int, float)) and not isinstance(calib, bool):
267
+ crit.temperature = float(calib)
268
+ elif calib == "auto":
269
+ cj = Path(path).parent / "calib.json"
270
+ if cj.exists():
271
+ try:
272
+ import json
273
+ crit.calib = json.loads(cj.read_text()); crit.temperature = float(crit.calib["T"])
274
+ except Exception as e:
275
+ print(f"[dwm_readout] calib.json unreadable ({e}); T=1", flush=True)
276
+ return crit
277
+
278
+
279
+ # --------------------------------------------------------------------------- #
280
+ @torch.no_grad()
281
+ def verify_pooling(cache_dir, n=512, seed=0, tokens_file=""):
282
+ """pool_tokens(tokens, proprio) vs the pooled pack z.f16.npy ‖ proprio.f32.npy on n random
283
+ frames. Returns dict(max_abs, max_rel, fp16_ok). fp16_ok: every |diff| <= 2 fp16 ulps of the
284
+ stored value (the pack is fp16-rounded; the pooling itself is fp32)."""
285
+ cache_dir = Path(cache_dir)
286
+ z = np.load(cache_dir / "z.f16.npy", mmap_mode="r")
287
+ pr = np.load(cache_dir / "proprio.f32.npy", mmap_mode="r") if (cache_dir / "proprio.f32.npy").exists() else None
288
+ tf = Path(tokens_file) if tokens_file else cache_dir / "tokens" / "tok.f16.npy"
289
+ tok = np.load(tf, mmap_mode="r")
290
+ assert tok.shape[0] == z.shape[0], f"tokens {tok.shape[0]} frames vs pooled {z.shape[0]}"
291
+ rng = np.random.default_rng(seed)
292
+ idx = np.sort(rng.choice(tok.shape[0], size=min(n, tok.shape[0]), replace=False))
293
+ t = torch.from_numpy(np.asarray(tok[idx], np.float32))
294
+ p = torch.from_numpy(np.asarray(pr[idx], np.float32)) if pr is not None else None
295
+ got = pool_tokens(t, p).numpy()
296
+ ref = np.asarray(z[idx], np.float32)
297
+ if p is not None:
298
+ ref = np.concatenate([ref, p.numpy()], -1)
299
+ assert got.shape == ref.shape, f"pooled dim {got.shape[1]} vs pack {ref.shape[1]}"
300
+ diff = np.abs(got - ref)
301
+ ulp = np.abs(np.asarray(ref, np.float16)).astype(np.float32) * 2 ** -10 + 1e-6
302
+ ok = bool((diff <= 2 * ulp + 1e-4).all())
303
+ return {"n": int(len(idx)), "dim": int(got.shape[1]), "max_abs": float(diff.max()),
304
+ "max_rel": float((diff / (np.abs(ref) + 1e-3)).max()), "fp16_ok": ok,
305
+ "frac_within_2ulp": float((diff <= 2 * ulp + 1e-4).mean())}
306
+
307
+
308
+ if __name__ == "__main__":
309
+ import argparse, json
310
+ ap = argparse.ArgumentParser(description="verify pool_tokens against the pooled pack")
311
+ ap.add_argument("--cache", required=True); ap.add_argument("--n", type=int, default=512)
312
+ ap.add_argument("--tokens", default="")
313
+ a = ap.parse_args()
314
+ print(json.dumps(verify_pooling(a.cache, a.n, tokens_file=a.tokens), indent=1))
frozen/rsm_libero_freeze_20261002/dwm_readout_timing.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cost of one planning step with the DWM read-out at N=128 candidates (orchestrator, 13:20 UTC).
2
+
3
+ One real held-out state (tokens + proprio) and 128 candidate 8-step chunks; times (CUDA-synchronised, median of
4
+ --reps) for flat n_particles in {4, 16, 64} and for the two-stage screen (4 -> top-16 x 64), in d1 mode, plus the
5
+ agreement between the rankings. Candidates: `--chunks hop` loads stream B's hop head (runs/<task>/hop/flow) if its
6
+ loader is importable, else (default `logged`) 128 logged chunks from 128 random frames of the val split -- the timing
7
+ does not depend on which chunks are used. Writes <out>/readout_timing.json.
8
+ """
9
+ from __future__ import annotations
10
+ import sys as _sys, os as _os
11
+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
12
+ import argparse, json, time
13
+ from pathlib import Path
14
+ import numpy as np
15
+ import torch
16
+
17
+ from dwm_model import TokenRSMData
18
+ from dwm_readout import load_critic_dwm
19
+
20
+
21
+ def timed(fn, reps, dev):
22
+ fn() # warm-up (compile/caches)
23
+ ts = []
24
+ for _ in range(reps):
25
+ if dev.type == "cuda":
26
+ torch.cuda.synchronize()
27
+ t0 = time.time(); out = fn()
28
+ if dev.type == "cuda":
29
+ torch.cuda.synchronize()
30
+ ts.append(time.time() - t0)
31
+ return float(np.median(ts)), out
32
+
33
+
34
+ def main():
35
+ ap = argparse.ArgumentParser()
36
+ ap.add_argument("--cache", required=True); ap.add_argument("--ckpt", required=True)
37
+ ap.add_argument("--n-cand", type=int, default=128); ap.add_argument("--reps", type=int, default=3)
38
+ ap.add_argument("--beta", type=float, default=0.95); ap.add_argument("--micro", type=int, default=512)
39
+ ap.add_argument("--seed", type=int, default=0); ap.add_argument("--out", default="")
40
+ a = ap.parse_args()
41
+ dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
42
+ d = TokenRSMData(a.cache, chunk=8, seed=a.seed)
43
+ crit = load_critic_dwm(a.ckpt, dev)
44
+ rng = np.random.default_rng(a.seed)
45
+ fb = d.sample_frames(1, rng, "val"); cb = d.sample_frames(a.n_cand, rng, "val")
46
+ N = a.n_cand
47
+ x = torch.as_tensor(fb["x"]).expand(N, -1, -1).contiguous(); pr = torch.as_tensor(fb["pr_now"]).expand(N, -1).contiguous()
48
+ a_c = cb["a"]
49
+ res = {"n_cand": N, "beta": a.beta, "device": torch.cuda.get_device_name(0) if dev.type == "cuda" else "cpu",
50
+ "ckpt": a.ckpt, "step": crit.step, "temperature": crit.temperature, "micro": a.micro, "reps": a.reps}
51
+ outs = {}
52
+ for n in (4, 16, 64):
53
+ t, (q, ql) = timed(lambda: crit.q(x, a_c, a.beta, n_particles=n, crn_seed=0, proprio=pr, micro=a.micro,
54
+ return_logit=True), a.reps, dev)
55
+ outs[n] = ql.cpu().numpy()
56
+ res[f"flat_{n}_particles_s"] = t
57
+ res[f"flat_{n}_q_mean"] = float(q.mean()); res[f"flat_{n}_q_max"] = float(q.max())
58
+ res[f"flat_{n}_frac_q_gt_0.99"] = float((q > 0.99).float().mean())
59
+ print(f"[timing] flat n={n}: {t:.3f} s for {N} candidates ({N*n*8} ViT forwards); q mean {float(q.mean()):.3f} "
60
+ f"max {float(q.max()):.3f} frac>0.99 {float((q > 0.99).float().mean()):.3f}", flush=True)
61
+ t, (q2, ql2) = timed(lambda: crit.q(x, a_c, a.beta, n_particles=4, rescore_top=16, n_particles_rescore=64,
62
+ crn_seed=0, proprio=pr, micro=a.micro, return_logit=True), a.reps, dev)
63
+ res["two_stage_4_top16_64_s"] = t
64
+ top64 = set(np.argsort(-outs[64])[:16].tolist()); top2 = set(np.argsort(-ql2.cpu().numpy())[:16].tolist())
65
+ top4 = set(np.argsort(-outs[4])[:16].tolist())
66
+ res["top16_overlap_two_stage_vs_flat64"] = len(top64 & top2) / 16
67
+ res["top16_overlap_flat4_vs_flat64"] = len(top64 & top4) / 16
68
+ res["argmax_agree_two_stage_vs_flat64"] = bool(int(np.argmax(outs[64])) == int(torch.argmax(ql2)))
69
+ res["spearman_flat4_vs_flat64"] = float(np.corrcoef(np.argsort(np.argsort(outs[4])), np.argsort(np.argsort(outs[64])))[0, 1])
70
+ print(f"[timing] two-stage 4 -> top16 x 64: {t:.3f} s; top-16 overlap with flat-64 {res['top16_overlap_two_stage_vs_flat64']:.2f} "
71
+ f"(flat-4 alone {res['top16_overlap_flat4_vs_flat64']:.2f}); spearman flat4/flat64 {res['spearman_flat4_vs_flat64']:.3f}",
72
+ flush=True)
73
+ out = Path(a.out) if a.out else Path(a.ckpt).parent / "readout_timing.json"
74
+ out.write_text(json.dumps(res, indent=1)); print(f"[timing] -> {out}", flush=True)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ main()
frozen/rsm_libero_freeze_20261002/encode_parquet.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Encode RLinf LeRobot parquet rollouts straight from their RECORDED frames into the
2
+ per-episode npz the cache packer consumes (z fp16 [T,4096], proprio [T,8], actions [T,7],
3
+ success, prompt, task_index) -- no re-rendering, no EGL.
4
+
5
+ The recorded frames ARE the evaluation environment's frames (the collector renders at
6
+ cam_res 256 and RLinf stores them upright, i.e. already in the evaluator's serving
7
+ orientation), and the parquet `state` equals the evaluator's proprio exactly (checked:
8
+ max |state - proprio| = 0 on the existing corpus). The encoder is whatever OGPO_PI05_BASE
9
+ points at, so this is how a LIBERO-finetuned pi0.5 (lerobot/pi05_libero_base) becomes the
10
+ feature encoder for a new cache; the tag is recorded in every episode.
11
+
12
+ usage: OGPO_PI05_BASE=<ckpt dir> encode_parquet.py --root <collect root> --out <corpus dir>
13
+ [--shard i --num-shards n] [--task-file lib10_tasks.txt]
14
+ Layout in: <root>/task{t}_block{b}/rank_*/id_{i}/data/chunk-*/episode_{k:06d}.parquet
15
+ Layout out: <out>/<taskname>/ep_t{t}_b{b}_i{i}_{k:06d}.npz (same as the existing corpus)
16
+ """
17
+ from __future__ import annotations
18
+ import argparse, io, os, re, sys, glob, time
19
+ from pathlib import Path
20
+ import numpy as np
21
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22
+ from eval_closed_loop import BUILDER, ogpo, to224 # the evaluator's own encoder path
23
+
24
+ PAT = re.compile(r"task(\d+)_block(\d+)/rank_(\d+)/id_(\d+)/data/chunk-(\d+)/episode_(\d+)\.parquet$")
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("--root", required=True); ap.add_argument("--out", required=True)
30
+ ap.add_argument("--shard", type=int, default=0); ap.add_argument("--num-shards", type=int, default=1)
31
+ ap.add_argument("--batch", type=int, default=64)
32
+ ap.add_argument("--task-file", default=os.environ.get("RSM_TASKS_FILE", ""))
33
+ a = ap.parse_args()
34
+ import torch, pyarrow.parquet as pq
35
+ from PIL import Image
36
+ from libero.libero import benchmark
37
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
38
+ enc_tag = os.path.basename(os.path.normpath(os.environ.get("OGPO_PI05_BASE", "pi05_base_pytorch")))
39
+ canon = [n.strip() for n in Path(a.task_file).read_text().replace("\n", ",").split(",") if n.strip()]
40
+ bench = benchmark.get_benchmark_dict()["libero_10"]()
41
+ lang = {bench.get_task(i).name: bench.get_task(i).language for i in range(bench.n_tasks)}
42
+ files = sorted(glob.glob(f"{a.root}/task*_block*/rank_*/id_*/data/chunk-*/episode_*.parquet"))
43
+ files = [f for k, f in enumerate(files) if k % a.num_shards == a.shard]
44
+ print(f"[enc] encoder={enc_tag} shard {a.shard}/{a.num_shards}: {len(files)} episodes", flush=True)
45
+ model = ogpo.build_paligemma(dev)
46
+ ids_cache = {}
47
+ n_done = n_skip = 0; t0 = time.time()
48
+ for k, f in enumerate(files):
49
+ m = PAT.search(f)
50
+ if not m:
51
+ continue
52
+ t, b, i, _c, ep = (int(x) for x in (m.group(1), m.group(2), m.group(4), m.group(5), m.group(6)))
53
+ tname = canon[t]
54
+ op = Path(a.out) / tname / f"ep_t{t}_b{b}_i{i}_{ep:06d}.npz"
55
+ if op.exists():
56
+ n_skip += 1; continue
57
+ tb = pq.read_table(f, columns=["state", "actions", "is_success", "image", "wrist_image"])
58
+ st = np.asarray(tb.column("state").to_pylist(), np.float32)
59
+ ac = np.asarray(tb.column("actions").to_pylist(), np.float32)
60
+ succ = bool(np.asarray(tb.column("is_success").to_pylist()).any())
61
+ frames = {}
62
+ for cam in ("image", "wrist_image"):
63
+ col = tb.column(cam).to_pylist()
64
+ frames[cam] = np.stack([to224(np.asarray(Image.open(io.BytesIO(x["bytes"])).convert("RGB")))
65
+ for x in col])
66
+ if t not in ids_cache:
67
+ ids_cache[t] = ogpo.tokenize_prompt(lang[tname])
68
+ za = ogpo.encode_frames(model, frames["image"], ids_cache[t], dev, a.batch)
69
+ zw = ogpo.encode_frames(model, frames["wrist_image"], ids_cache[t], dev, a.batch)
70
+ z = np.concatenate([za, zw], 1).astype(np.float16)
71
+ op.parent.mkdir(parents=True, exist_ok=True)
72
+ tmp = str(op) + ".tmp.npz"
73
+ np.savez(tmp, z=z, proprio=st, actions=ac, success=succ, prompt=ids_cache[t],
74
+ task_index=t, encoder=enc_tag, cam_res=256)
75
+ os.replace(tmp, op); n_done += 1
76
+ if n_done % 20 == 0:
77
+ el = time.time() - t0
78
+ print(f"[enc] {k+1}/{len(files)} done={n_done} skip={n_skip} {el/n_done:.1f}s/ep", flush=True)
79
+ print(f"[enc] DONE shard {a.shard}: {n_done} written, {n_skip} existed, encoder={enc_tag}", flush=True)
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
frozen/rsm_libero_freeze_20261002/encode_t5.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Encode the ten LIBERO-10 instructions with T5 and cache the vectors.
2
+
3
+ Replaces the learned nn.Embedding(n_task) conditioning. An index lookup carries no
4
+ information about WHAT the task is: it cannot transfer to a held-out instruction, and it
5
+ gives the network a free shortcut so nothing forces the visual latent to represent the
6
+ instruction. A frozen T5 embedding conditions on the sentence itself.
7
+
8
+ Ten short strings, so this runs once and the result is a few hundred KB.
9
+ """
10
+ import argparse, numpy as np, torch, os
11
+
12
+ ap = argparse.ArgumentParser()
13
+ ap.add_argument("--cache", required=True)
14
+ ap.add_argument("--out", required=True)
15
+ ap.add_argument("--model", default="google-t5/t5-11b")
16
+ ap.add_argument("--pool", default="mean", choices=["mean", "first"])
17
+ a = ap.parse_args()
18
+
19
+ m = np.load(f"{a.cache}/meta.npz", allow_pickle=True)
20
+ # the cache stores directory names; recover the instruction the way the evaluator does
21
+ from libero.libero import benchmark
22
+ b = benchmark.get_benchmark_dict()["libero_10"]()
23
+ names = [str(t) for t in m["tasks"]]
24
+ by_name = {b.get_task(i).name: b.get_task(i).language for i in range(b.n_tasks)}
25
+ texts = [by_name.get(n, n.replace("_", " ")) for n in names]
26
+ for i, t in enumerate(texts):
27
+ print(f" [{i}] {t}", flush=True)
28
+
29
+ from transformers import T5EncoderModel, T5Tokenizer
30
+ tok = T5Tokenizer.from_pretrained(a.model, legacy=False)
31
+ enc = T5EncoderModel.from_pretrained(a.model, torch_dtype=torch.float16).eval()
32
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
33
+ enc = enc.to(dev)
34
+ with torch.no_grad():
35
+ bt = tok(texts, return_tensors="pt", padding=True)
36
+ out = enc(input_ids=bt["input_ids"].to(dev),
37
+ attention_mask=bt["attention_mask"].to(dev)).last_hidden_state
38
+ msk = bt["attention_mask"].to(dev).unsqueeze(-1).float()
39
+ vec = ((out.float() * msk).sum(1) / msk.sum(1)) if a.pool == "mean" else out[:, 0].float()
40
+ vec = vec.cpu().numpy().astype(np.float32)
41
+ np.savez(a.out, emb=vec, tasks=np.array(names, dtype=object),
42
+ texts=np.array(texts, dtype=object), model=a.model, pool=a.pool)
43
+ print(f"[t5] wrote {a.out} shape={vec.shape} "
44
+ f"norm mean={np.linalg.norm(vec,axis=1).mean():.2f}", flush=True)
45
+ # sanity: the two LIVING_ROOM_SCENE2 tasks differ only in the objects named
46
+ import itertools
47
+ D = np.linalg.norm(vec[:, None] - vec[None], axis=-1)
48
+ iu = list(itertools.combinations(range(len(vec)), 2))
49
+ d = [(D[i, j], i, j) for i, j in iu]
50
+ d.sort()
51
+ print(f"[t5] closest pair : t{d[0][1]} / t{d[0][2]} dist {d[0][0]:.2f}")
52
+ print(f"[t5] farthest pair : t{d[-1][1]} / t{d[-1][2]} dist {d[-1][0]:.2f}")
frozen/rsm_libero_freeze_20261002/encode_t5.sbatch ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --job-name=encode_t5
3
+ #SBATCH --account=vision-pulkitag
4
+ #SBATCH --gres=gpu:1 --cpus-per-task=8 --mem=120G
5
+ #SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.out
6
+ #SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.err
7
+ set -uo pipefail
8
+ B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation
9
+ S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion
10
+ export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard
11
+ export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1
12
+ export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1
13
+ $B/venvs/rlinf-libero-eval-venv/bin/python \
14
+ /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/encode_t5.py \
15
+ --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \
16
+ --out /data/pulkitag/users/rli14/rsm_libero_runs/t5_lib10.npz
frozen/rsm_libero_freeze_20261002/eval_closed_loop.py ADDED
@@ -0,0 +1,1025 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Closed-loop LIBERO-10 success rate for an rsm_libero policy.
2
+
3
+ Reuses the LANE'S evaluator wholesale -- featurization, env construction, seeding,
4
+ task ordering, chunk execution -- and swaps ONLY the policy call. That is
5
+ deliberate: the 0.584 +- 0.025 `bcdemos_m120k` bar was produced by
6
+ `09032026_latent_head_eval.py`, and a success rate measured by any other harness
7
+ is not comparable to it.
8
+
9
+ Featurization contract copied exactly from that evaluator:
10
+ * ROT180 to serving orientation (`obs[key][::-1, ::-1]`)
11
+ * 128 -> 224 bilinear
12
+ * per-camera 2048-d pool, agentview ++ wrist -> 4096
13
+ * proprio = eef_pos(3) ++ eef_ori(3) ++ gripper_qpos(2) = 8
14
+
15
+ Features are z-scored with the SAME per-dim statistics the policy trained under,
16
+ loaded from the training cache (`feat_stats.npz`). Getting normalisation wrong in
17
+ either direction evaluates a good policy off-distribution and is
18
+ indistinguishable from the policy being bad, so the stats travel with the run
19
+ rather than being reconstructed here.
20
+ """
21
+ from __future__ import annotations
22
+ import argparse, hashlib, importlib.util, json, os, sys
23
+ from pathlib import Path
24
+ import numpy as np
25
+ import torch
26
+
27
+ WT = os.environ.get("RSM_WT",
28
+ "/data/pulkitag/hamer_diffusion_policy_project/projects/"
29
+ "continual_learning_for_manipulation/.claude/worktrees/08312026_jvq_recap_worktree")
30
+ # RSM_WT: the CLM worktree holding scripts/rlinf_jvq (the latent-cache BUILDER). On IBM it
31
+ # is /proj/dmfexp/zwhong/rli14_jvq_worktree; the builder itself reads OGPO_PI05_BASE and
32
+ # OGPO_TOKENIZER for its weights.
33
+ sys.path.insert(0, WT + "/scripts/rlinf_jvq")
34
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
35
+
36
+ # build_paligemma / tokenize_prompt / encode_frames live in the latent-cache
37
+ # BUILDER; the rollout producer merely imports it under the local name `ogpo`.
38
+ # Importing the producer instead gives a module without those attributes, which
39
+ # kills the evaluator on its first line of work. This is the SAME builder that
40
+ # wrote the training cache -- verified to reproduce it at cos 0.9999 offline and
41
+ # 0.9903 from live env frames.
42
+ BUILDER = WT + "/scripts/rlinf_jvq/08312026_1110pm_ogpo_latent_cache.py"
43
+ _spec = importlib.util.spec_from_file_location("ogpo_cache", BUILDER)
44
+ ogpo = importlib.util.module_from_spec(_spec)
45
+ sys.modules["ogpo_cache"] = ogpo
46
+ _spec.loader.exec_module(ogpo)
47
+
48
+ from model import Encoder, FlowPolicy, BCHead, ConcatFlowPolicy
49
+ from is_ope import _LatWithProprio
50
+
51
+
52
+ def to224(img):
53
+ """128 -> 224 bilinear, then ROUND AND CLAMP TO uint8.
54
+
55
+ The uint8 quantisation is not cosmetic. The latent cache was built from PIL
56
+ uint8 images, so the encoder has only ever seen quantised pixels. Feeding it
57
+ the raw float32 interpolation instead shifts the latent by up to 0.31 in a
58
+ space whose per-dimension standard deviation is 0.107 -- a three-sigma
59
+ perturbation on the dimensions that matter, re-applied at every one of the
60
+ ~52 chunk decisions in an episode. Measured: the lane's own 0.584 policy
61
+ scores 0/50 through this evaluator with float input and 0.46 through its own
62
+ evaluator, which quantises. Cosine similarity (0.999898) hides this entirely,
63
+ which is why it was not caught by the featurisation checks.
64
+ """
65
+ t = torch.from_numpy(np.ascontiguousarray(img[None])).permute(0, 3, 1, 2).float()
66
+ t = torch.nn.functional.interpolate(t, size=(224, 224), mode="bilinear",
67
+ align_corners=False)
68
+ return t.permute(0, 2, 3, 1).round().clamp(0, 255).byte().numpy()[0]
69
+
70
+
71
+ def _eef_ori(obs):
72
+ """End-effector orientation as AXIS-ANGLE, matching the cache.
73
+
74
+ This was the bug that produced 0% everywhere. The cache's 8-d proprio is
75
+ eef_pos(3) ++ ee_ori(3) ++ gripper_qpos(2), and LIBERO's `ee_ori` is
76
+ robosuite AXIS-ANGLE. This evaluator previously converted the quaternion to
77
+ Euler roll/pitch/yaw, so three of the eight proprio dimensions were a
78
+ different quantity at every timestep. The policy still emitted plausible
79
+ first actions -- the visual latent dominates the input -- which is why the
80
+ featurisation checks, the offline fit and even a bit-exact comparison of the
81
+ first action chunk all looked healthy.
82
+
83
+ Measured with the lane's own 0.584 policy on task 5: 0/5 through this
84
+ evaluator with Euler, 5/5 through theirs with axis-angle, same machine and
85
+ same weights.
86
+ """
87
+ q = obs.get("robot0_eef_quat")
88
+ if q is None:
89
+ return np.zeros(3, np.float32)
90
+ try:
91
+ from robosuite.utils.transform_utils import quat2axisangle
92
+ return np.asarray(quat2axisangle(np.asarray(q)), dtype=np.float32)
93
+ except Exception:
94
+ w = np.clip(q[3], -1, 1)
95
+ ang = 2 * np.arccos(abs(w))
96
+ axis = q[:3] / (np.linalg.norm(q[:3]) + 1e-8)
97
+ return (axis * ang).astype(np.float32)
98
+
99
+
100
+ _oodx = [] # (task, online t=0 feature) when --probe-ood: lets the online region be
101
+ # compared against the cached demo and rollout clouds offline
102
+
103
+
104
+ # A checkpoint records the cache it trained on. When it was trained on the OTHER cluster,
105
+ # resolve that path to the local twin: both caches are packed from the same pinned
106
+ # episode list (index-identical, latents bit-identical) and their stats come from the
107
+ # same arrays. Extend with RSM_CACHE_REMAP="from1=to1,from2=to2" if a new pair appears.
108
+ _CACHE_TWINS = {
109
+ "/proj/dmfexp/zwhong/rsm_libero/cache/": "/data/pulkitag/users/rli14/rsm_libero_cache/",
110
+ "/data/pulkitag/users/rli14/rsm_libero_cache/": "/proj/dmfexp/zwhong/rsm_libero/cache/",
111
+ }
112
+
113
+
114
+ def _resolve_cache(path):
115
+ import os as _os
116
+ p = str(path or "")
117
+ if not p or _os.path.exists(p):
118
+ return p
119
+ pairs = list(_CACHE_TWINS.items())
120
+ for kv in filter(None, _os.environ.get("RSM_CACHE_REMAP", "").split(",")):
121
+ a, b = kv.split("=", 1); pairs.append((a, b))
122
+ for a, b in pairs:
123
+ if p.startswith(a) and _os.path.exists(b + p[len(a):]):
124
+ print(f"[cache] {p} -> {b + p[len(a):]} (cluster twin)", flush=True)
125
+ return b + p[len(a):]
126
+ return p
127
+
128
+
129
+ def _declared_cam_res(ckpt_path):
130
+ """What resolution were this checkpoint's latents rendered at? From the checkpoint
131
+ itself, else from its cache's RENDER.json / PACK.json. 'UNKNOWN' if neither."""
132
+ import json as _j
133
+ try:
134
+ ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
135
+ except Exception:
136
+ return "UNKNOWN"
137
+ if ck.get("cam_res") not in (None, "UNKNOWN"):
138
+ return ck["cam_res"]
139
+ cache = _resolve_cache((ck.get("config") or {}).get("cache", ""))
140
+ for f in ("RENDER.json", "PACK.json"):
141
+ try:
142
+ v = _j.load(open(f"{cache}/{f}")).get("cam_res")
143
+ if v is not None:
144
+ return v
145
+ except Exception:
146
+ pass
147
+ return "UNKNOWN"
148
+
149
+
150
+ def _declared_encoder(ckpt_path):
151
+ """Which feature encoder produced this checkpoint's latents (basename of the
152
+ OGPO_PI05_BASE it was built with). Legacy checkpoints predate the tag -> pi05_base_pytorch."""
153
+ import json as _j
154
+ try:
155
+ ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
156
+ except Exception:
157
+ return "UNKNOWN"
158
+ if ck.get("encoder"):
159
+ return ck["encoder"]
160
+ cache = _resolve_cache((ck.get("config") or {}).get("cache", ""))
161
+ for f in ("PACK.json", "RENDER.json"):
162
+ try:
163
+ v = _j.load(open(os.path.join(cache, f))).get("encoder")
164
+ if v: return v
165
+ except Exception:
166
+ pass
167
+ return "pi05_base_pytorch"
168
+
169
+
170
+ def _guard_encoder(args):
171
+ """Refuse to evaluate with a feature encoder different from the one the latents were
172
+ encoded with (the 128/256 lesson applied to the encoder weights themselves)."""
173
+ mine = os.path.basename(os.path.normpath(os.environ.get("OGPO_PI05_BASE", "pi05_base_pytorch")))
174
+ bad = []
175
+ for label, path in (("policy", args.policy), ("policy2", getattr(args, "policy2", "")), ("critic", args.critic),
176
+ ("qf-ckpt", args.qf_ckpt), ("hop-policy", getattr(args, "hop_policy", ""))):
177
+ if not path:
178
+ continue
179
+ v = _declared_encoder(path)
180
+ if v != mine:
181
+ bad.append(f"{label} {path}: latents from encoder '{v}', evaluator encoder '{mine}'")
182
+ if bad and not args.allow_cam_mismatch:
183
+ raise SystemExit("[guard] ENCODER MISMATCH -- refusing:\n " + "\n ".join(bad))
184
+ for b in bad:
185
+ print(f"[guard] OVERRIDDEN encoder mismatch: {b}", flush=True)
186
+
187
+
188
+ def _guard_render_resolution(args):
189
+ """Refuse to evaluate a policy/critic at a resolution its latents were not rendered
190
+ at. This is the defect that voided every result before 2026-09-13 (i251): rollout
191
+ latents at 256, evaluator at 128, and nothing complained."""
192
+ bad = []
193
+ for label, path in (("policy", args.policy), ("critic", args.critic), ("qf-ckpt", args.qf_ckpt), ("hop-policy", getattr(args, "hop_policy", ""))):
194
+ if not path:
195
+ continue
196
+ v = _declared_cam_res(path)
197
+ if v == "UNKNOWN":
198
+ # trusting an undeclared checkpoint is exactly how the 128/256 mismatch ran
199
+ # unnoticed for weeks; undeclared is refused like a mismatch
200
+ bad.append(f"{label} {path}: render resolution UNDECLARED (no cam_res in checkpoint "
201
+ f"or in its cache's RENDER.json/PACK.json)")
202
+ elif str(v) != str(args.cam_res):
203
+ bad.append(f"{label} {path}: latents rendered at {v}, evaluator at {args.cam_res}")
204
+ if bad and not args.allow_cam_mismatch:
205
+ raise SystemExit("[guard] RENDER RESOLUTION MISMATCH -- refusing:\n " + "\n ".join(bad)
206
+ + "\n (--allow-cam-mismatch 1 to override; never for a reported number)")
207
+ for b in bad:
208
+ print(f"[guard] OVERRIDDEN mismatch: {b}", flush=True)
209
+
210
+
211
+ def load_policy(critic_path, policy_path, n_task, device, lane_norm=""):
212
+ """Encoder from the critic checkpoint + the trained policy.
213
+
214
+ The policy may read the FULL observation (`policy_features=raw`, the default
215
+ since the reward-predictive bottleneck was found to strip action detail) or
216
+ the critic latent. Which one is recorded in the policy checkpoint, so the
217
+ evaluator can never feed a policy the features it was not trained on.
218
+ """
219
+ d_in = 4096 + 8
220
+ pk = torch.load(policy_path, map_location=device, weights_only=False)
221
+
222
+ # HARNESS CONTROL: a lane checkpoint (key "model") is wrapped so it runs
223
+ # through THIS evaluator unchanged. If it reproduces the score its own
224
+ # evaluator gives, this harness is proven equivalent and any 0% belongs to
225
+ # our training rather than to deployment.
226
+ if "model" in pk:
227
+ import importlib.util as _il
228
+ _sp = _il.spec_from_file_location("lh", WT + "/scripts/rlinf_jvq/"
229
+ "09032026_latent_head_bc.py")
230
+ _lh = _il.module_from_spec(_sp); sys.modules["lh"] = _lh
231
+ _sp.loader.exec_module(_lh)
232
+ c = pk["config"]
233
+ head = _lh.Head(4096, 8, len(_lh.FS15), c["hidden"], c["depth"],
234
+ c["chunk"]).to(device)
235
+ head.load_state_dict(pk["model"]); head.eval()
236
+ if not lane_norm:
237
+ raise SystemExit("a lane checkpoint needs --lane-norm <norm npz>")
238
+ nz = np.load(lane_norm)
239
+ zm = torch.tensor(nz["zm"], dtype=torch.float32, device=device)
240
+ zs = torch.tensor(nz["zs"], dtype=torch.float32, device=device)
241
+ pm = torch.tensor(nz["pm"], dtype=torch.float32, device=device)
242
+ ps = torch.tensor(nz["ps"], dtype=torch.float32, device=device)
243
+
244
+ class _LaneWrap(torch.nn.Module):
245
+ """Exposes the lane Head through our (pfeat, sample) interface."""
246
+ d_act = c["chunk"] * 7
247
+
248
+ def __init__(self):
249
+ super().__init__(); self.h = head; self.chunk = c["chunk"]
250
+
251
+ @torch.no_grad()
252
+ def sample(self, x, task):
253
+ z = (x[:, :4096] - zm) / zs
254
+ pr = (x[:, 4096:] - pm) / ps
255
+ adv = torch.full((x.shape[0],), 2, dtype=torch.long, device=x.device)
256
+ a = torch.randn(x.shape[0], self.chunk, 7, device=x.device)
257
+ for st in range(10):
258
+ kk = torch.full((x.shape[0],), 1 - st / 10, device=x.device)
259
+ a = a + self.h(z, pr, task, adv, a, kk).view_as(a) / 10
260
+ return a.flatten(1)
261
+
262
+ mu0 = torch.zeros(d_in, device=device); sd1 = torch.ones(d_in, device=device)
263
+ return ((lambda x: x), _LaneWrap(), c["chunk"], {"d_z": 0}, "lane",
264
+ d_in, (mu0, sd1))
265
+ # the exact transform the policy trained under -- never re-derived here
266
+ # the stats file must match the pool the policy trained under
267
+ _np = pk["config"].get("norm_pool", "all")
268
+ st = Path(_resolve_cache(pk["config"].get("cache", ""))) / (
269
+ "feat_stats.npz" if _np == "all" else f"feat_stats_{_np}.npz")
270
+ if not st.exists():
271
+ raise FileNotFoundError(
272
+ f"feature stats missing: {st}. The policy was trained on normalised "
273
+ f"features; evaluating it on raw ones is off-distribution.")
274
+ _s = np.load(st)
275
+ if int(_s["dim"]) != d_in:
276
+ raise ValueError(f"feat_stats dim {int(_s['dim'])} != evaluator dim {d_in}")
277
+ nmu = torch.tensor(_s["mu"], dtype=torch.float32, device=device)
278
+ nsd = torch.tensor(_s["sd"], dtype=torch.float32, device=device)
279
+ # A raw-feature policy trains on CENTERED input, which the data layer
280
+ # produces by z-scoring and then rescaling the visual block back by
281
+ # sd / mean(sd). Rebuilt here from the same stats file so the evaluator and
282
+ # is_ope.policy_features cannot drift apart. Proprio (last 8 dims) keeps its
283
+ # per-dim z-score.
284
+ _sd = np.asarray(_s["sd"], np.float32)
285
+ _sc = np.ones(d_in, np.float32)
286
+ _sc[:4096] = _sd[:4096] / max(float(_sd[:4096].mean()), 1e-6)
287
+ nsc = torch.tensor(_sc, dtype=torch.float32, device=device)
288
+ if pk["config"].get("policy_features", "latent") == "raw":
289
+ # a raw-feature policy needs no encoder at all, so a BC arm evaluates
290
+ # without ever loading a critic
291
+ cls = (ConcatFlowPolicy
292
+ if pk["config"].get("policy_family", "flow") == "concat"
293
+ else FlowPolicy)
294
+ _kw = {}
295
+ if pk["config"].get("policy_family", "flow") == "concat":
296
+ _kw = dict(width=int(pk["config"].get("pol_width", 1024) or 1024),
297
+ depth=int(pk["config"].get("pol_depth", 4) or 4))
298
+ pol = cls(d_in, pk["config"]["chunk"] * 7, n_task, **_kw).to(device)
299
+ pol.load_state_dict(pk["pol"]); pol.eval()
300
+ return ((lambda x: x * nsc), pol, pk["config"]["chunk"], {"d_z": 0},
301
+ "raw", d_in, (nmu, nsd))
302
+ if not critic_path:
303
+ raise SystemExit("this policy reads latent features; pass --critic")
304
+ ck = torch.load(critic_path, map_location=device, weights_only=False)
305
+ c = ck["config"]
306
+ n_pr = int(ck.get("n_pr", 0) or 0)
307
+ base = Encoder(d_in, c["d_z"], c["enc_width"]).to(device)
308
+ base.load_state_dict(ck["enc"])
309
+ pcfg = pk["config"]
310
+ chunk = pcfg["chunk"]
311
+ mode = pcfg.get("policy_features", "latent")
312
+
313
+ mu = sd = torch.zeros(0, device=device)
314
+ if n_pr:
315
+ # proprio normalisation must come from the cache the CRITIC was fit on,
316
+ # not a hard-coded path: different caches have different proprio stats.
317
+ pcache = Path(pcfg.get("cache", "")) / "proprio.f32.npy"
318
+ if not pcache.exists():
319
+ raise FileNotFoundError(f"proprio stats cache missing: {pcache}")
320
+ pr = np.asarray(np.load(pcache, mmap_mode="r")[::37], np.float32)
321
+ mu = torch.tensor(pr.mean(0), device=device)
322
+ sd = torch.tensor(pr.std(0) + 1e-6, device=device)
323
+ enc = _LatWithProprio(base, n_pr, mu, sd).to(device).eval()
324
+
325
+ if mode == "raw":
326
+ pfeat, d_lat = (lambda x: x), d_in
327
+ else:
328
+ pfeat, d_lat = enc, c["d_z"] + n_pr
329
+
330
+ cls = (ConcatFlowPolicy if pcfg.get("policy_family", "flow") == "concat"
331
+ else FlowPolicy)
332
+ pol = cls(d_lat, chunk * 7, n_task).to(device)
333
+ pol.load_state_dict(pk["pol"])
334
+ pol.eval()
335
+ return pfeat, pol, chunk, c, mode, d_lat, (nmu, nsd)
336
+
337
+
338
+ def main():
339
+ ap = argparse.ArgumentParser()
340
+ ap.add_argument("--critic", default="",
341
+ help="only needed when the policy reads latent features")
342
+ ap.add_argument("--policy", required=True)
343
+ ap.add_argument("--tasks", default="0,1,2,3,4,5,6,7,8,9")
344
+ ap.add_argument("--n-init", type=int, default=10)
345
+ ap.add_argument("--execute", type=int, default=10)
346
+ ap.add_argument("--max-steps", type=int, default=520)
347
+ ap.add_argument("--suite", default="libero_10")
348
+ ap.add_argument("--seed", type=int, default=0)
349
+ ap.add_argument("--policy-seed", type=int, default=0)
350
+ ap.add_argument("--fresh", type=int, default=0)
351
+ ap.add_argument("--qf-gate", type=float, default=0.0,
352
+ help="only OVERRIDE the policy's own action when the best "
353
+ "candidate beats it by more than this margin in Q units. "
354
+ "0 = always take the arg-max (plain ranking, 0.550); a "
355
+ "large value never fires and reduces exactly to the "
356
+ "policy (0.630). The ranker is weak on average -- "
357
+ "expert-vs-perturbation wins only 0.515 at small "
358
+ "perturbations -- so acting on it only where it is "
359
+ "confident is the way to use it without paying for its "
360
+ "average quality.")
361
+ ap.add_argument("--policy-sde", type=float, default=0.0,
362
+ help="noise injected DURING integration when --q-filter is "
363
+ "on. Unlike --policy-temp this follows the learned "
364
+ "drift, so candidates stay near the manifold. Measured: "
365
+ "test-time ranking (0.550) beats distilling the selected "
366
+ "actions (0.410), because distillation replaces the "
367
+ "policy while ranking only picks among its own samples.")
368
+ ap.add_argument("--policy-sde-anneal", type=int, default=0,
369
+ help="1 = scale --policy-sde noise by the remaining noise "
370
+ "fraction so the last integration steps are clean.")
371
+ ap.add_argument("--policy-temp", type=float, default=1.0,
372
+ help="scales the proposal's initial noise when --q-filter is "
373
+ "on. A trained flow clone samples at action std 0.029 "
374
+ "against the data's 0.421, so 8 candidates are near "
375
+ "copies and there is nothing to rank. Diversity only "
376
+ "pays once the ranker has the right SIGN, which the "
377
+ "supervised student Q does and our counterfactual Q did "
378
+ "not.")
379
+ ap.add_argument("--qf-ckpt", default="",
380
+ help="main_rsm.pt from rsm_main.py. Ranks --q-filter candidate "
381
+ "chunks by the DISTILLED student qf(z,a), which main "
382
+ "supervises on real (s,a,s') transitions, instead of by "
383
+ "conditioning the occupancy on a counterfactual action.")
384
+ ap.add_argument("--save-frames", default="",
385
+ help="directory to write per-episode agentview JPEG strips. Lets a "
386
+ "closed-loop FAILURE be inspected: the scalar SR says an arm "
387
+ "lost an episode, not what the arm did wrong.")
388
+ ap.add_argument("--frame-stride", type=int, default=12)
389
+ ap.add_argument("--init-jitter", type=float, default=0.0,
390
+ help="metres of uniform xy perturbation applied to every object "
391
+ "free joint after reset. BOTH stock init states and env.reset() "
392
+ "are narrow (std 0.024 / 0.014), and both sit inside "
393
+ "BC-on-demos's training support, so neither tests whether a "
394
+ "demo-trained policy degrades off-support. This widens the "
395
+ "initial-state distribution explicitly. Applies to A and B "
396
+ "alike; 0 = off.")
397
+ ap.add_argument("--select", default="argmaxq",
398
+ choices=["argmaxq", "random", "medoid", "qnear", "quantile", "randgate"],
399
+ help="how to pick among the --q-filter candidates. argmaxq uses "
400
+ "the critic. random picks uniformly (must reproduce plain BC, "
401
+ "and is the sanity check that the harness adds nothing). "
402
+ "medoid picks the candidate nearest the other N-1, a "
403
+ "CRITIC-FREE variance reducer -- if best-of-N helps for any "
404
+ "reason other than value, medoid captures it, and any gain "
405
+ "over medoid is what the critic actually contributes.")
406
+ ap.add_argument("--demo-cand", type=int, default=0,
407
+ help="append this many nearest-DEMO action chunks to the "
408
+ "candidate set, retrieved by L2 in the same normalised "
409
+ "feature space the policy reads. The ranker is otherwise "
410
+ "confined to the proposal's own support: 8 samples from a "
411
+ "flow with action std 0.029 against the data's 0.421 are "
412
+ "near-copies, so even a perfect ranker has nothing to "
413
+ "choose. Demo chunks are off-proposal but ON-manifold, "
414
+ "unlike --policy-sde noise which cost 0.22.")
415
+ ap.add_argument("--q-filter", type=int, default=0,
416
+ help="sample this many action chunks from the policy and "
417
+ "execute the one the RSM critic scores highest. 0 = off. "
418
+ "Uses the occupancy model at DEPLOYMENT, which needs only "
419
+ "a critic that RANKS actions, not one that is calibrated.")
420
+ ap.add_argument("--qf-beta", type=float, default=0.97,
421
+ help="hop length for the filter, inside the critic's training "
422
+ "band [0.85, 0.97]; 0.97 looks ~33 frames ahead")
423
+ ap.add_argument("--qf-depth", type=int, default=1,
424
+ help="depth 1 needs no continuation policy: the recursion "
425
+ "breaks before it would have to re-draw an action in a "
426
+ "latent the flow only imagined")
427
+ ap.add_argument("--qf-particles", type=int, default=16)
428
+ ap.add_argument("--qf-mode", default="restart", choices=["restart", "fold"],
429
+ help="restart: geometric mixture of beta-hops (restart prob "
430
+ "(gamma-beta)/(gamma(1-beta))) = the gamma-occupancy, reward read "
431
+ "once at the stopping state. fold: the OCBench product fold "
432
+ "Q_k = c_k + (1-c_k) gamma^(1/(1-beta)) Q_{k+1} over a FIXED "
433
+ "number of hops (--qf-depth).")
434
+ ap.add_argument("--policy2", default="",
435
+ help="second proposer checkpoint; --q-filter2 of its samples are appended "
436
+ "to the candidate set (test-time stitching of two policies)")
437
+ ap.add_argument("--q-filter2", type=int, default=0)
438
+ ap.add_argument("--select-q", type=float, default=0.9,
439
+ help="select=quantile: execute the candidate at this quantile of Q "
440
+ "(rank round(q*(N-1)) in ascending order) instead of the arg-max.")
441
+ ap.add_argument("--qf-crn", type=int, default=0,
442
+ help="1 = common random numbers across candidates in the Q "
443
+ "recursion (same flow noise / restart coins / hop-policy noise "
444
+ "for particle i of every candidate), so the arg-max compares "
445
+ "paired estimates. Independent draws rank near-copies by noise.")
446
+ ap.add_argument("--qnear-k", type=int, default=4,
447
+ help="select=qnear: arg-max Q among the K candidates nearest the medoid")
448
+ ap.add_argument("--hop-policy", default="",
449
+ help="bc_arm checkpoint trained with --policy-features latent over the "
450
+ "SAME critic encoder. Required for --qf-depth >= 2: the beta-hop "
451
+ "composition continues the trajectory from the sampled latent z' "
452
+ "with pi(a|z'), and the raw-feature proposer cannot read z'.")
453
+ ap.add_argument("--qf-pessimism", type=float, default=2.0)
454
+ ap.add_argument("--partial-only", type=int, default=0,
455
+ help="write only <out>.partial.t<k> files; the final JSON is left to an assembly run")
456
+ ap.add_argument("--allow-cam-mismatch", type=int, default=0,
457
+ help="override the render-resolution guard. Never for a reported number.")
458
+ ap.add_argument("--init-source", default="libero", choices=["libero", "demo", "rollout"],
459
+ help="where episode k's initial state comes from. libero = the stock "
460
+ "init_states (protocol A) or env.reset() (protocol B); demo = the "
461
+ "EXACT first sim state of demo k from the LIBERO hdf5; rollout = the "
462
+ "first sim_state of the k-th cached rollout of this task.")
463
+ ap.add_argument("--save-video-frames", default="",
464
+ help="dir: write full-res agentview frames (uint8, every --video-stride "
465
+ "steps) per episode, for mp4 export")
466
+ ap.add_argument("--video-stride", type=int, default=2)
467
+ ap.add_argument("--cam-res", type=int, default=256,
468
+ help="render resolution of both cameras. 128 is the LIBERO demo-hdf5 "
469
+ "convention and what the demo cache was encoded from; 256 is what "
470
+ "RLinf's libero_10 env (the lane's evaluator AND the rollout "
471
+ "collector) uses, i.e. the space the 43k rollout latents live in. "
472
+ "A policy must be evaluated at the resolution its latents were "
473
+ "encoded at, or it is off-support from step 1 (i251).")
474
+ ap.add_argument("--probe-ood", type=int, default=0,
475
+ help="print the first decision's action scale per episode. Default "
476
+ "off so queued evals are unaffected.")
477
+ ap.add_argument("--lane-norm", default="",
478
+ help="norm npz for a lane checkpoint run as a harness control")
479
+ ap.add_argument("--out", required=True)
480
+ args = ap.parse_args()
481
+ _guard_render_resolution(args)
482
+ _guard_encoder(args)
483
+
484
+ dev = "cuda" if torch.cuda.is_available() else "cpu" # an assembly run (all tasks in partials) needs no GPU
485
+ tower = ogpo.build_paligemma(dev)
486
+ from libero.libero import benchmark, get_libero_path
487
+ from libero.libero.envs import OffScreenRenderEnv
488
+ import time as _time
489
+ _T0 = _time.time()
490
+ def _lap(msg):
491
+ print(f"[eval][t+{_time.time()-_T0:6.0f}s] {msg}", flush=True)
492
+ bench = benchmark.get_benchmark_dict()[args.suite]()
493
+ _lap("imports + benchmark ready")
494
+
495
+ canon = [n.strip() for n in Path(
496
+ os.environ.get("RSM_TASKS_FILE",
497
+ "/data/pulkitag/hamer_diffusion_policy_project/projects/"
498
+ "continual_learning_for_manipulation/logs/09052026_lib10_tasks.txt")
499
+ ).read_text().replace("\n", ",").split(",") if n.strip()]
500
+ by_name = {t: i for i, t in enumerate(canon)}
501
+
502
+ pfeat, pol, chunk, ccfg, pmode, d_lat, (nmu, nsd) = load_policy(
503
+ args.critic, args.policy, len(canon), dev, lane_norm=args.lane_norm)
504
+ _lap("policy (+encoder) loaded")
505
+ pol2 = pfeat2 = None
506
+ if args.policy2:
507
+ # Second proposer: its candidates are appended to the first's, so the selector
508
+ # can stitch between a narrow strong policy (demos) and a broad one (successes)
509
+ # per decision. Both must share the feature normalisation (checked).
510
+ pfeat2, pol2, chunk2, _c2, _m2, _d2, (nmu2, nsd2) = load_policy(
511
+ args.critic, args.policy2, len(canon), dev, lane_norm=args.lane_norm)
512
+ if chunk2 != chunk or not torch.allclose(nmu2, nmu) or not torch.allclose(nsd2, nsd):
513
+ raise SystemExit("--policy2 must share chunk length and feature normalisation with --policy")
514
+ print(f"[eval] second proposer: {args.policy2} x {args.q_filter2} candidates", flush=True)
515
+
516
+ qf = None
517
+ gate_stats = {"fire": 0, "hold": 0}
518
+ if args.q_filter and args.qf_ckpt and torch.load(args.qf_ckpt, map_location="cpu",
519
+ weights_only=False).get("iql_q"):
520
+ # IQL baseline, ranked with EXACTLY the RSM arm's best-of-N machinery: same
521
+ # proposal policy, same N, same arg-max; only the source of Q differs. The IQL
522
+ # Q reads the frozen encoder of the RSM critic it was trained against.
523
+ from iql import QNet as _QNet
524
+ from is_ope import load_critic as _lc
525
+ from data import LiberoRSMData
526
+ ck = torch.load(args.qf_ckpt, map_location=dev, weights_only=False)
527
+ _pc = torch.load(args.policy, map_location="cpu", weights_only=False)["config"]
528
+ _dq = LiberoRSMData(_resolve_cache(_pc["cache"]), chunk=chunk, seed=0, in_ram=False,
529
+ reward_mode="dense", norm_pool=_pc.get("norm_pool", "all"))
530
+ _enc, _r, _f, _rms, _cfg = _lc(_resolve_cache(ck["critic"]), _dq.feat_dim, _dq.n_task, dev, data=_dq)
531
+ _enc.eval()
532
+ _qc = ck.get("config") or {}
533
+ qnet = _QNet(ck["d_z"], ck["d_act"], ck["n_task"], width=int(_qc.get("width", 512) or 512),
534
+ depth=int(_qc.get("depth", 3) or 3)).to(dev)
535
+ qnet.load_state_dict(ck["q"]); qnet.eval()
536
+
537
+ def qf(x_norm, tt, cand):
538
+ z = _enc(x_norm).expand(cand.shape[0], -1)
539
+ q = qnet(z, cand, tt.expand(cand.shape[0]))
540
+ if args.select == "quantile":
541
+ # Rank the candidates by Q and execute the one at quantile --select-q
542
+ # (0.9 of 8 -> the 2nd best, of 32 -> the 4th best). The arg-max is the
543
+ # candidate most exposed to off-support optimism; a high-but-not-top
544
+ # quantile keeps a strongly-scored action while discarding the extreme.
545
+ _order = torch.argsort(q) # ascending
546
+ _r = int(round(args.select_q * (cand.shape[0] - 1)))
547
+ gate_stats["fire"] += 1
548
+ return int(_order[min(max(_r, 0), cand.shape[0] - 1)])
549
+ best = int(q.argmax())
550
+ if args.qf_gate > 0 and float(q[best] - q[0]) < args.qf_gate:
551
+ gate_stats["hold"] += 1
552
+ return 0
553
+ gate_stats["fire"] += 1
554
+ return best
555
+ print(f"[eval] IQL Q reader ON: {args.q_filter} candidates (tau={ck['config'].get('tau')})", flush=True)
556
+ elif args.q_filter and args.qf_ckpt:
557
+ # main's reader: a student Q supervised on logged transitions.
558
+ from model import Encoder as _Enc
559
+ from rsm_main import QStudent
560
+ ck = torch.load(args.qf_ckpt, map_location=dev, weights_only=False)
561
+ c = ck["config"]
562
+ qenc = _Enc(4096 + 8, c["d_z"], c["enc_width"]).to(dev)
563
+ qenc.load_state_dict(ck["enc"]); qenc.eval()
564
+ qnet = QStudent(c["d_z"], ck["d_act"], len(canon)).to(dev)
565
+ qnet.load_state_dict(ck["qf"]); qnet.eval()
566
+
567
+ def qf(x_norm, tt, cand):
568
+ z = qenc(x_norm).expand(cand.shape[0], -1)
569
+ q = qnet(z, cand, tt.expand(cand.shape[0]))
570
+ best = int(q.argmax())
571
+ # candidate 0 is an ordinary draw from the policy: the default action
572
+ if args.qf_gate > 0 and float(q[best] - q[0]) < args.qf_gate:
573
+ gate_stats["hold"] += 1
574
+ return 0
575
+ gate_stats["fire"] += 1
576
+ return best
577
+ print(f"[eval] qf reader ON: {args.q_filter} candidates, student Q "
578
+ f"(arrival AUC {ck.get('arrival_auc', float('nan')):.4f})", flush=True)
579
+ elif args.q_filter and args.select not in ("argmaxq", "qnear", "quantile"): # randgate/medoid/random are critic-free
580
+ qf = None # critic-free selector; no critic needed
581
+ print(f"[eval] CRITIC-FREE selector '{args.select}' over "
582
+ f"{args.q_filter} candidates", flush=True)
583
+ elif args.q_filter:
584
+ if not args.critic:
585
+ raise SystemExit("--q-filter needs --critic or --qf-ckpt")
586
+ from data import LiberoRSMData
587
+ from is_ope import load_critic, q_recursive
588
+ pcfg_cache = torch.load(args.policy, map_location="cpu",
589
+ weights_only=False)["config"]
590
+ _d = LiberoRSMData(_resolve_cache(pcfg_cache["cache"]), chunk=chunk, seed=0, in_ram=False,
591
+ reward_mode="dense",
592
+ norm_pool=pcfg_cache.get("norm_pool", "all"))
593
+ q_enc, q_rew, q_flow, q_rms, q_cfg = load_critic(
594
+ args.critic, _d.feat_dim, _d.n_task, dev, data=_d)
595
+
596
+ hop_pol = None
597
+ if args.qf_depth >= 2:
598
+ if not args.hop_policy:
599
+ raise SystemExit("--qf-depth >= 2 needs --hop-policy (latent-feature BC over the critic encoder)")
600
+ from is_ope import make_policy as _mk
601
+ _hk = torch.load(args.hop_policy, map_location=dev, weights_only=False)
602
+ _hc = _hk["config"]
603
+ if _hc.get("policy_features") != "latent":
604
+ raise SystemExit(f"--hop-policy must be a --policy-features latent checkpoint (got {_hc.get('policy_features')})")
605
+ class _HA: pass
606
+ _ha = _HA(); [setattr(_ha, k, v) for k, v in _hc.items()]
607
+ hop_pol = _mk(_ha, _d, dev, d_z=q_cfg["d_z"])
608
+ hop_pol.load_state_dict(_hk["pol"]); hop_pol.eval()
609
+ print(f"[eval] beta-hop policy loaded: {args.hop_policy} (depth {args.qf_depth}, "
610
+ f"restart p={(0.99 - args.qf_beta) / (0.99 * (1 - args.qf_beta)):.3f})", flush=True)
611
+
612
+ from is_ope import q_fold
613
+ if args.qf_mode == "fold":
614
+ print(f"[eval] Q = OCBench product fold, depth {args.qf_depth}, "
615
+ f"gamma^h = {0.99 ** (1 / (1 - args.qf_beta)):.3f} per hop, crn={args.qf_crn}", flush=True)
616
+ def qf(x_norm, tt, cand):
617
+ """cand: [N, chunk*7] -> index of the highest-scoring chunk."""
618
+ z = q_enc(x_norm).expand(cand.shape[0], -1)
619
+ if args.qf_mode == "fold":
620
+ q, _ = q_fold(z, cand, tt.expand(cand.shape[0]),
621
+ rew=q_rew, flow=q_flow, rms=q_rms, pol=hop_pol,
622
+ beta=args.qf_beta, gamma=0.99, depth=args.qf_depth,
623
+ n_particles=args.qf_particles, crn=bool(args.qf_crn))
624
+ else:
625
+ q, _ = q_recursive(z, cand, tt.expand(cand.shape[0]),
626
+ rew=q_rew, flow=q_flow, rms=q_rms, pol=hop_pol,
627
+ wend=None, beta=args.qf_beta, gamma=0.99,
628
+ depth=args.qf_depth, n_particles=args.qf_particles,
629
+ use_is=False, pessimism=args.qf_pessimism,
630
+ crn=bool(args.qf_crn))
631
+ if args.select == "qnear":
632
+ # Support-constrained arg-max: the critic orders only the K candidates
633
+ # nearest the medoid. Measured failure of plain arg-max: off-support
634
+ # candidates draw diffuse futures whose read-out drifts to the base rate
635
+ # and outranks confident low scores on real actions; the medoid never
636
+ # selects those outliers, and beat plain arg-max on B by 0.05-0.08.
637
+ _dd = torch.cdist(cand, cand).sum(1)
638
+ _near = torch.topk(-_dd, k=min(args.qnear_k, cand.shape[0])).indices
639
+ best = int(_near[q[_near].argmax()])
640
+ gate_stats["fire"] += 1
641
+ return best
642
+ if args.select == "quantile":
643
+ # Rank the candidates by Q and execute the one at quantile --select-q
644
+ # (0.9 of 8 -> the 2nd best, of 32 -> the 4th best). The arg-max is the
645
+ # candidate most exposed to off-support optimism; a high-but-not-top
646
+ # quantile keeps a strongly-scored action while discarding the extreme.
647
+ _order = torch.argsort(q) # ascending
648
+ _r = int(round(args.select_q * (cand.shape[0] - 1)))
649
+ gate_stats["fire"] += 1
650
+ return int(_order[min(max(_r, 0), cand.shape[0] - 1)])
651
+ best = int(q.argmax())
652
+ if args.qf_gate > 0 and float(q[best] - q[0]) < args.qf_gate:
653
+ gate_stats["hold"] += 1
654
+ return 0
655
+ gate_stats["fire"] += 1
656
+ return best
657
+ print(f"[eval] Q-filter ON: {args.q_filter} candidates, beta={args.qf_beta}, "
658
+ f"depth={args.qf_depth}, pessimism={args.qf_pessimism}, "
659
+ f"gate={args.qf_gate}", flush=True)
660
+ print(f"[eval] chunk={chunk} policy_features={pmode} d_policy={d_lat} "
661
+ f"suite={args.suite}", flush=True)
662
+ _lap("critic / selector ready")
663
+
664
+ demo_bank = None
665
+ if args.demo_cand > 0:
666
+ import numpy as _np
667
+ pcfg_c = torch.load(args.policy, map_location="cpu",
668
+ weights_only=False)["config"]
669
+ _ca = pcfg_c["cache"]
670
+ _m = _np.load(f"{_ca}/meta.npz", allow_pickle=True)
671
+ _isd = _m["ep_demo"].astype(bool)
672
+ if not _isd.any():
673
+ raise SystemExit("--demo-cand: cache has no demo episodes")
674
+ _zs = _np.load(f"{_ca}/z.f16.npy", mmap_mode="r")
675
+ _pr = _np.load(f"{_ca}/proprio.f32.npy", mmap_mode="r")
676
+ _ac = _np.load(f"{_ca}/act.f32.npy", mmap_mode="r")
677
+ _idx = []
678
+ for _e in _np.where(_isd)[0]:
679
+ _lo, _hi = int(_m["ep_from"][_e]), int(_m["ep_to"][_e])
680
+ # only frames with a full chunk ahead inside the same episode
681
+ if _hi - _lo > chunk:
682
+ _idx.append(_np.arange(_lo, _hi - chunk))
683
+ _idx = _np.concatenate(_idx)
684
+ _f = _np.concatenate([_np.asarray(_zs[_idx], _np.float32),
685
+ _np.asarray(_pr[_idx], _np.float32)], 1)
686
+ _f = torch.tensor(_f, device=dev)
687
+ _f = ((_f - nmu) / nsd).half() # identical transform to x
688
+ _off = _np.arange(chunk)[None, :] + _idx[:, None]
689
+ _A = torch.tensor(_np.asarray(_ac[_off], _np.float32).reshape(len(_idx), -1),
690
+ device=dev)
691
+ demo_bank = (_f, _A)
692
+ print(f"[eval] demo-cand ON: {args.demo_cand} nearest of "
693
+ f"{len(_idx)} demo frames appended to each candidate set", flush=True)
694
+
695
+ demo_pick = {"demo": 0, "policy": 0}
696
+ mix_pick = {"p1": 0, "p2": 0}
697
+ results, episodes = {}, {}
698
+ # Resume from a preempted run: tasks already finished are in <out>.partial. On IBM's
699
+ # preemptable queue an hour-long eval is interrupted every ~30 min; without this it
700
+ # never completes. Episodes within a task are re-run (seeds are per-episode, so the
701
+ # completed tasks are unaffected by where the restart happens).
702
+ import glob as _glob
703
+ for _pp in sorted(_glob.glob(args.out + ".partial*")):
704
+ try:
705
+ _pj = json.loads(Path(_pp).read_text())
706
+ results.update(_pj.get("results", {})); episodes.update(_pj.get("episodes", {}))
707
+ except Exception as _e:
708
+ print(f"[eval] partial file {_pp} unreadable ({_e}); ignored", flush=True)
709
+ if results:
710
+ print(f"[eval] RESUMED: {len(results)} tasks already done from partial files", flush=True)
711
+ for tid in [int(x) for x in args.tasks.split(",")]:
712
+ task = bench.get_task(tid)
713
+ tname = task.name
714
+ if tname in results:
715
+ print(f"[eval] t{tid} {tname[:40]}: done in a previous run (SR {results[tname]:.2f}), skipping", flush=True)
716
+ continue
717
+ if tname not in by_name:
718
+ raise ValueError(f"task {tid} ({tname}) not in the canonical libero_10 list")
719
+ thead = by_name[tname]
720
+ ids = ogpo.tokenize_prompt(task.language)
721
+ inits = bench.get_task_init_states(tid)
722
+ if args.init_source == "demo":
723
+ import h5py as _h5
724
+ with _h5.File(f"/data/pulkitag/users/rli14/libero_datasets/libero_10/{tname}_demo.hdf5", "r") as _H:
725
+ _ks = sorted(_H["data"].keys(), key=lambda q: int(q.split("_")[1]))
726
+ inits = [np.asarray(_H["data"][q]["states"][0]) for q in _ks]
727
+ print(f"[eval] t{tid}: {len(inits)} EXACT demo initial states from hdf5", flush=True)
728
+ elif args.init_source == "rollout":
729
+ import pyarrow.parquet as _pq, re as _re
730
+ _m = np.load("/data/pulkitag/users/rli14/rsm_libero_cache/full_demo_cam256/meta.npz", allow_pickle=True)
731
+ _PAT = _re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
732
+ inits = []
733
+ for _e in np.where((_m["ep_task"] == tid) & ~_m["ep_demo"].astype(bool))[0]:
734
+ _g = _PAT.search(str(_m["ep_src"][_e])); _t, _b, _i, _x = _g.groups()
735
+ _pp = (f"/data/pulkitag/users/rli14/pi05_lib10_sde_v1/task{int(_t)}_block{int(_b)}"
736
+ f"/rank_0/id_{int(_i)}/data/chunk-000/episode_{int(_x):06d}.parquet")
737
+ if not Path(_pp).exists(): continue
738
+ inits.append(np.asarray(_pq.read_table(_pp, columns=["sim_state"])["sim_state"][0].as_py()))
739
+ if len(inits) >= args.n_init: break
740
+ print(f"[eval] t{tid}: {len(inits)} rollout initial sim_states from parquet", flush=True)
741
+ _lap(f"t{tid}: creating env")
742
+ env = OffScreenRenderEnv(
743
+ bddl_file_name=str(Path(get_libero_path("bddl_files"))
744
+ / task.problem_folder / task.bddl_file),
745
+ camera_heights=args.cam_res, camera_widths=args.cam_res)
746
+ _lap(f"t{tid}: env ready")
747
+ _objn, _objb, _target = [], [], []
748
+ if args.save_frames:
749
+ try:
750
+ _objn = list(env.env.obj_body_id.keys())
751
+ _objb = [env.env.obj_body_id[n] for n in _objn]
752
+ _target = list(env.env.obj_of_interest)
753
+ print(f"[eval] t{tid} objects={_objn} target={_target}", flush=True)
754
+ except Exception as _e:
755
+ print(f"[eval] object handles unavailable: {_e}", flush=True)
756
+ succ, episodes[tname] = [], []
757
+ # Per-episode progress: the EGL driver on IBM aborts the process (SIGABRT, no
758
+ # traceback) at random points DURING a task, not only at teardown, so a 50-episode
759
+ # task job that dies at episode 40 must not redo 40 episodes. Every finished
760
+ # episode is appended to <out>.progress.t<tid>; a restarted job reloads it and
761
+ # skips those episode indices (inits are seeded per (seed, tid, k), so the
762
+ # remaining episodes are the same ones the dead job would have run).
763
+ _prog = Path(args.out + f".progress.t{tid}")
764
+ _done_k = set()
765
+ try:
766
+ if _prog.exists():
767
+ for _e in json.loads(_prog.read_text()):
768
+ if int(_e["episode"]) < args.n_init and int(_e["episode"]) not in _done_k:
769
+ episodes[tname].append(_e); succ.append(bool(_e["success"]))
770
+ _done_k.add(int(_e["episode"]))
771
+ if _done_k:
772
+ print(f"[eval] t{tid}: resumed {len(_done_k)} episodes from {_prog.name}", flush=True)
773
+ except Exception as _e:
774
+ print(f"[eval] t{tid}: progress file unreadable ({_e}); starting over", flush=True)
775
+ episodes[tname], succ, _done_k = [], [], set()
776
+ for k in range(args.n_init):
777
+ if k in _done_k:
778
+ continue
779
+ pseed = 7_919_003 + args.policy_seed * 500_009 + tid * 1_013 + k
780
+ torch.manual_seed(pseed); torch.cuda.manual_seed_all(pseed)
781
+ np.random.seed(args.seed * 100003 + tid * 1009 + k)
782
+ if hasattr(env, "seed"):
783
+ env.seed(args.seed * 100003 + tid * 1009 + k)
784
+ env.reset()
785
+ if args.init_source != "libero":
786
+ env.env.sim.set_state_from_flattened(np.asarray(inits[k % len(inits)], np.float64))
787
+ env.env.sim.forward()
788
+ elif not args.fresh:
789
+ env.set_init_state(inits[k % len(inits)])
790
+ if args.init_jitter > 0:
791
+ # Perturb object free joints only. mjtJoint FREE == 0; its qpos block is
792
+ # [x, y, z, qw, qx, qy, qz], so writing indices 0-1 moves the object in
793
+ # the table plane without touching height or orientation (which would
794
+ # make the state unphysical). The robot is welded in LIBERO, so free
795
+ # joints are exactly the manipulable objects.
796
+ _sim = env.env.sim
797
+ _st = np.asarray(_sim.get_state().flatten()).copy()
798
+ _nq = _sim.model.nq
799
+ _rs = np.random.RandomState(
800
+ 987_631 + args.seed * 7919 + tid * 131 + k)
801
+ _moved = 0
802
+ for _j in range(_sim.model.njnt):
803
+ if int(_sim.model.jnt_type[_j]) != 0:
804
+ continue
805
+ _a = int(_sim.model.jnt_qposadr[_j])
806
+ if _a + 1 >= _nq:
807
+ continue
808
+ _st[1 + _a] += _rs.uniform(-args.init_jitter, args.init_jitter)
809
+ _st[1 + _a + 1] += _rs.uniform(-args.init_jitter, args.init_jitter)
810
+ _moved += 1
811
+ _sim.set_state_from_flattened(_st)
812
+ _sim.forward()
813
+ for _ in range(5): # let contacts settle onto the table
814
+ _sim.step()
815
+ if tid == 0 and k == 0:
816
+ print(f"[eval] init-jitter {args.init_jitter*100:.1f} cm on "
817
+ f"{_moved} object free joints", flush=True)
818
+ done, steps = False, 0
819
+ _frames, _geo, _vid = [], [], []
820
+ obs, _, _, _ = env.step(np.zeros(7))
821
+ init_hash = hashlib.sha256(
822
+ np.asarray(env.env.sim.get_state().flatten()).tobytes()).hexdigest()
823
+ while steps < args.max_steps and not done:
824
+ cams = []
825
+ for key in ("agentview_image", "robot0_eye_in_hand_image"):
826
+ img = obs[key][::-1, ::-1]
827
+ cams.append(to224(img)[None])
828
+ if args.save_video_frames and steps % args.video_stride == 0:
829
+ _vid.append(np.asarray(obs["agentview_image"][::-1, ::-1], np.uint8).copy())
830
+ if args.save_frames and steps % args.frame_stride == 0:
831
+ _frames.append(np.asarray(obs["agentview_image"][::-1, ::-1]).copy())
832
+ # geometry for offline failure typing: where the hand is, whether it
833
+ # is closed, and where every object is. obj_of_interest names the
834
+ # BDDL goal's target, so "went to the wrong object" is measurable
835
+ # without touching a network.
836
+ _ee = np.asarray(obs["robot0_eef_pos"], np.float32)
837
+ _gq = np.asarray(obs["robot0_gripper_qpos"], np.float32)
838
+ _op = np.stack([np.asarray(env.env.sim.data.body_xpos[_b], np.float32)
839
+ for _b in _objb]) if _objb else np.zeros((0, 3), np.float32)
840
+ _geo.append(np.concatenate([_ee, _gq[:2], _op.reshape(-1)]))
841
+ z = np.concatenate(
842
+ [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0]
843
+ prop = np.concatenate([
844
+ obs["robot0_eef_pos"], _eef_ori(obs), obs["robot0_gripper_qpos"],
845
+ ]).astype(np.float32)
846
+ x = torch.tensor(np.concatenate([z, prop])[None], dtype=torch.float32,
847
+ device=dev)
848
+ x = (x - nmu) / nsd # same transform as LiberoRSMData._feat
849
+ tt = torch.tensor([thead], device=dev)
850
+ if args.probe_ood and steps == 0:
851
+ # Off-distribution guard. A policy cloned from one pool can be a
852
+ # near-perfect predictor on its own frames (held-out action MSE
853
+ # 0.0008 at t=0 for BC_rollsucc) and still emit actions 5x too
854
+ # large on the evaluator's first observation, which reads as a
855
+ # flat 0/500 indistinguishable from a weak policy. Printing the
856
+ # first action's scale next to the reference pools' action scale
857
+ # separates "bad policy" from "policy evaluated off its manifold".
858
+ with torch.no_grad():
859
+ _a0 = pol.sample(pfeat(x), tt)[0].view(chunk, 7)
860
+ _oodx.append((int(tid), np.asarray(x[0].cpu(), np.float32)))
861
+ print(f"[ood] task {tid} init {k}: |a| std={float(_a0.std()):.3f} "
862
+ f"max={float(_a0.abs().max()):.3f} "
863
+ f"frac|a|>1={float((_a0.abs() > 1).float().mean()):.3f} "
864
+ f"(corpus action std ~0.43) |x|={float(x.norm()):.2f}",
865
+ flush=True)
866
+ with torch.no_grad():
867
+ if qf is None and not args.q_filter:
868
+ a = pol.sample(pfeat(x), tt)[0].view(chunk, 7).cpu().numpy()
869
+ else:
870
+ feats = pfeat(x).expand(args.q_filter, -1)
871
+ cand = pol.sample(feats, tt.expand(args.q_filter),
872
+ temp=args.policy_temp,
873
+ sde=args.policy_sde,
874
+ sde_anneal=bool(args.policy_sde_anneal))
875
+ if pol2 is not None and args.q_filter2 > 0:
876
+ cand2 = pol2.sample(pfeat2(x).expand(args.q_filter2, -1),
877
+ tt.expand(args.q_filter2))
878
+ cand = torch.cat([cand, cand2], 0)
879
+ n_pol = cand.shape[0]
880
+ if demo_bank is not None:
881
+ _fb, _Ab = demo_bank
882
+ _d = torch.cdist(x.half(), _fb).squeeze(0)
883
+ _nn = torch.topk(_d, args.demo_cand, largest=False).indices
884
+ cand = torch.cat([cand, _Ab[_nn].to(cand.dtype)], 0)
885
+ if args.select == "random":
886
+ _pick = int(torch.randint(cand.shape[0], (1,)).item())
887
+ elif args.select == "randgate":
888
+ # control for the critic gate: with prob --select-q execute a
889
+ # random NON-default candidate, else the default (candidate 0)
890
+ _pick = int(torch.randint(1, cand.shape[0], (1,)).item()) \
891
+ if float(torch.rand(1)) < args.select_q else 0
892
+ elif args.select == "medoid":
893
+ _dd = torch.cdist(cand, cand) # [N,N]
894
+ _pick = int(_dd.sum(1).argmin())
895
+ else:
896
+ _pick = qf(x, tt, cand)
897
+ if demo_bank is not None:
898
+ demo_pick["demo" if _pick >= n_pol else "policy"] += 1
899
+ if pol2 is not None:
900
+ mix_pick["p2" if args.q_filter <= _pick < args.q_filter + args.q_filter2 else "p1"] += 1
901
+ a = cand[_pick].view(chunk, 7).cpu().numpy()
902
+ for act in a[: args.execute]:
903
+ obs, _, done, _ = env.step(act.astype(np.float64))
904
+ steps += 1
905
+ if done or steps >= args.max_steps:
906
+ break
907
+ succ.append(bool(done))
908
+ episodes[tname].append({"episode": k, "success": bool(done), "steps": steps,
909
+ "init_sha256": init_hash})
910
+ try:
911
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
912
+ _tmp = _prog.with_suffix(_prog.suffix + ".tmp")
913
+ _tmp.write_text(json.dumps(episodes[tname])); _tmp.replace(_prog)
914
+ except Exception as _e:
915
+ print(f"[eval] progress write failed ({_e})", flush=True)
916
+ if (len(episodes[tname]) % 10) == 0:
917
+ _lap(f"t{tid}: {len(episodes[tname])}/{args.n_init} episodes, SR so far {np.mean(succ):.2f}")
918
+ if args.save_video_frames and _vid:
919
+ _vd = Path(args.save_video_frames); _vd.mkdir(parents=True, exist_ok=True)
920
+ np.savez_compressed(_vd / f"t{tid}_e{k}.npz", frames=np.stack(_vid),
921
+ success=bool(done), steps=steps, task=tid, ep=k,
922
+ stride=args.video_stride)
923
+ if args.save_frames and _frames:
924
+ import io as _io, base64 as _b64
925
+ from PIL import Image as _Im
926
+ _fd = Path(args.save_frames); _fd.mkdir(parents=True, exist_ok=True)
927
+ _enc = []
928
+ for _fr in _frames[:40]:
929
+ _im = _Im.fromarray(_fr).convert("RGB"); _im.thumbnail((144, 144))
930
+ _bb = _io.BytesIO(); _im.save(_bb, "JPEG", quality=70)
931
+ _enc.append(_b64.b64encode(_bb.getvalue()).decode())
932
+ np.savez_compressed(
933
+ _fd / f"t{tid}_e{k}.npz",
934
+ frames=np.array(_enc, dtype=object),
935
+ geo=np.asarray(_geo, np.float32),
936
+ objects=np.array(_objn, dtype=object),
937
+ target=np.array(_target, dtype=object),
938
+ success=bool(done), steps=steps, task=tid, ep=k)
939
+ episodes[tname].sort(key=lambda _e: int(_e["episode"]))
940
+ results[tname] = float(np.mean(succ))
941
+ try: # partial results survive a teardown abort or a preemption. Written BEFORE
942
+ # env.close(): on IBM's EGL driver close() aborts the process (rc=134).
943
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
944
+ # one file per task: parallel per-task jobs never write the same file
945
+ Path(args.out + f".partial.t{tid}").write_text(json.dumps(
946
+ {"results": {tname: results[tname]}, "episodes": {tname: episodes[tname]}}, indent=1))
947
+ except Exception:
948
+ pass
949
+ if os.environ.get("RSM_NO_ENV_CLOSE"):
950
+ _keep_alive = globals().setdefault("_KEEP_ENVS", []); _keep_alive.append(env)
951
+ else:
952
+ try:
953
+ env.close()
954
+ except Exception as _e:
955
+ print(f"[eval] env.close() raised (ignored): {_e}", flush=True)
956
+ print(f"task {tid} {tname[:40]}: SR {results[tname]:.2f} "
957
+ f"({sum(succ)}/{len(succ)})", flush=True)
958
+
959
+ overall = float(np.mean(list(results.values())))
960
+ n_tot = sum(len(v) for v in episodes.values())
961
+ n_suc = sum(e["success"] for v in episodes.values() for e in v)
962
+ pooled = n_suc / max(n_tot, 1)
963
+ # THROUGHPUT = SR * max_steps / mean_steps. Rewards finishing FAST, not just
964
+ # finishing: a policy that solves in half the horizon does twice the work per
965
+ # unit time. Reported two ways because they answer different questions:
966
+ # _succ : mean over SUCCESSFUL episodes -- how fast is it when it works
967
+ # _all : mean over ALL episodes -- failures burn the full horizon, so this
968
+ # penalises failing twice (once in SR, once in the time it wasted)
969
+ all_steps = [e["steps"] for v in episodes.values() for e in v]
970
+ suc_steps = [e["steps"] for v in episodes.values() for e in v if e["success"]]
971
+ mean_all = float(np.mean(all_steps)) if all_steps else float("nan")
972
+ mean_suc = float(np.mean(suc_steps)) if suc_steps else float("nan")
973
+ thr_all = pooled * args.max_steps / mean_all if mean_all == mean_all and mean_all > 0 else float("nan")
974
+ thr_suc = pooled * args.max_steps / mean_suc if mean_suc == mean_suc and mean_suc > 0 else float("nan")
975
+ per_task_thr = {}
976
+ for tname, eps in episodes.items():
977
+ s = [e["steps"] for e in eps if e["success"]]
978
+ if s:
979
+ per_task_thr[tname] = results[tname] * args.max_steps / float(np.mean(s))
980
+ out = {"overall_task_mean_SR": overall, "successes": n_suc, "episodes": n_tot,
981
+ "pooled_SR": pooled,
982
+ "throughput_succ": thr_suc, "throughput_all": thr_all,
983
+ "mean_steps_success": mean_suc, "mean_steps_all": mean_all,
984
+ "max_steps": args.max_steps, "per_task_throughput": per_task_thr,
985
+ "per_task": results,
986
+ "critic": args.critic, "policy": args.policy, "chunk": chunk,
987
+ "policy_features": pmode,
988
+ "seed": args.seed, "n_init": args.n_init, "suite": args.suite,
989
+ "episodes_detail": episodes}
990
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
991
+ if args.partial_only:
992
+ print("[eval] --partial-only: final JSON left to the assembly run", flush=True)
993
+ else:
994
+ Path(args.out).write_text(json.dumps(out, indent=1))
995
+ if args.probe_ood and _oodx:
996
+ _p = str(Path(args.out).with_suffix("")) + "_oodx.npz"
997
+ np.savez_compressed(_p, task=np.array([t for t, _ in _oodx], np.int64),
998
+ x=np.stack([v for _, v in _oodx]))
999
+ print(f"[ood] wrote {len(_oodx)} online t=0 features to {_p}", flush=True)
1000
+ if pol2 is not None:
1001
+ _m1, _m2 = mix_pick["p1"], mix_pick["p2"]
1002
+ print(f"[eval] mixed proposer: policy2 chosen {_m2}/{_m1+_m2} ({_m2/max(_m1+_m2,1):.3f})", flush=True)
1003
+ _dp, _pp = demo_pick["demo"], demo_pick["policy"]
1004
+ if _dp + _pp:
1005
+ print(f"[eval] demo-cand: expert chunk chosen {_dp}/{_dp+_pp} "
1006
+ f"({_dp/(_dp+_pp):.3f}) of decisions", flush=True)
1007
+ _gf, _gh = gate_stats["fire"], gate_stats["hold"]
1008
+ if _gf + _gh:
1009
+ print(f"[eval] gate={args.qf_gate}: fired {_gf}/{_gf+_gh} "
1010
+ f"({_gf/(_gf+_gh):.3f}) decisions overridden", flush=True)
1011
+ print(f"\nOVERALL task-mean SR {overall:.4f} | pooled {n_suc}/{n_tot} = {pooled:.4f}",
1012
+ flush=True)
1013
+ print(f"THROUGHPUT succ-only {thr_suc:.4f} all-episodes {thr_all:.4f} "
1014
+ f"(mean steps: success {mean_suc:.0f}, all {mean_all:.0f}, max {args.max_steps})",
1015
+ flush=True)
1016
+ print(f"BAR: bcdemos_m120k = 0.584 +- 0.025 (n=500, same harness family)", flush=True)
1017
+ # Everything is on disk. Skip interpreter teardown: on IBM's EGL driver robosuite's
1018
+ # context destructor aborts the process (rc=134), which on a normal exit would turn a
1019
+ # finished, written evaluation into a "failed" job.
1020
+ import sys as _sys; _sys.stdout.flush(); _sys.stderr.flush()
1021
+ os._exit(0)
1022
+
1023
+
1024
+ if __name__ == "__main__":
1025
+ main()
frozen/rsm_libero_freeze_20261002/eval_slurm.sbatch ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --job-name=rsm_libero_eval
3
+ #SBATCH --account=vision-pulkitag
4
+ #SBATCH --qos=lab-free
5
+ #SBATCH --partition=csail-shared-h200
6
+ #SBATCH --gres=gpu:1
7
+ #SBATCH --cpus-per-task=8
8
+ #SBATCH --mem=64G
9
+ #SBATCH --time=20:00:00
10
+ #SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.out
11
+ #SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.err
12
+
13
+ # Closed-loop LIBERO-10 success rate for an rsm_libero policy.
14
+ # Environment copied EXACTLY from the lane's own eval launcher
15
+ # (08312026_0135am_libero10_pertask_eval.sbatch) so the number is comparable to
16
+ # the bcdemos_m120k = 0.584 +- 0.025 bar. A success rate from a different
17
+ # harness or a different render backend is not comparable to it.
18
+ set -uo pipefail
19
+ B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation
20
+ S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion
21
+ VENV=$B/venvs/rlinf-libero-eval-venv
22
+ PY=$VENV/bin/python
23
+
24
+ export REPO_PATH=$B/external/rlinf
25
+ export PYTHONPATH="$REPO_PATH:${PYTHONPATH:-}"
26
+ export LIBERO_CONFIG_PATH=$S/libero_config
27
+ export ROBOT_PLATFORM=LIBERO
28
+ export LIBERO_TYPE=standard
29
+ export MUJOCO_GL=egl
30
+ export PYOPENGL_PLATFORM=egl
31
+ _GPU="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)"
32
+ export MUJOCO_EGL_DEVICE_ID="$_GPU" EGL_DEVICE_ID="$_GPU"
33
+ export TOKENIZERS_PARALLELISM=false
34
+ export PYTHONUNBUFFERED=1
35
+ export HF_HOME=/data/pulkitag/users/rli14/hf_cache
36
+ export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "")
37
+ export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN
38
+ export HF_HUB_OFFLINE=1
39
+ # the lane head sizes its task embedding from FL15_TASKS; harmless for our heads
40
+ export FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')"
41
+
42
+ CRITIC=${CRITIC:-} # only needed when the policy reads latent features
43
+ POLICY=${POLICY:?set POLICY}
44
+ OUT=${OUT:?set OUT}
45
+ LANE_NORM=${LANE_NORM:-}
46
+ QFILTER=${QFILTER:-0}
47
+ QFCKPT=${QFCKPT:-}
48
+ PTEMP=${PTEMP:-1.0}
49
+ PSDE=${PSDE:-0.0}
50
+ QFGATE=${QFGATE:-0.0}
51
+ QFBETA=${QFBETA:-0.97}
52
+ QFDEPTH=${QFDEPTH:-1}
53
+ QFPES=${QFPES:-2.0}
54
+ NINIT=${NINIT:-10}
55
+ SEED=${SEED:-0}
56
+ # protocol A ignores SEED entirely (set_init_state overwrites the reset, and
57
+ # np.random is unused in the loop). Its ONLY source of variation is the policy
58
+ # sampling stream, which is keyed on --policy-seed.
59
+ PSEED=${PSEED:-0}
60
+ # steps of each predicted chunk actually executed. Hardcoding 10 made every
61
+ # chunk>10 policy waste capacity on steps that are always discarded, which is an
62
+ # unfair comparison across chunk lengths.
63
+ EXEC=${EXEC:-10}
64
+ DEMOCAND=${DEMOCAND:-0}
65
+ # 0 = replay LIBERO's fixed init_states (which the demos were collected from);
66
+ # 1 = env.reset() only, so object placements are sampled from the task's
67
+ # continuous placement region. Fixed inits risk measuring memorisation.
68
+ FRESH=${FRESH:-0}
69
+ SELECT=${SELECT:-argmaxq}
70
+ JITTER=${JITTER:-0.0}
71
+ SAVEFRAMES=${SAVEFRAMES:-}
72
+ PROBEOOD=${PROBEOOD:-0}
73
+ TASKS=${TASKS:-0,1,2,3,4,5,6,7,8,9}
74
+ MAXSTEPS=${MAXSTEPS:-520}
75
+ CAMRES=${CAMRES:-256}
76
+ INITSRC=${INITSRC:-libero}
77
+ VIDEO=${VIDEO:-}
78
+
79
+ echo "[eval] critic=$CRITIC"
80
+ echo "[eval] policy=$POLICY n_init=$NINIT seed=$SEED"
81
+ $PY /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/eval_closed_loop.py \
82
+ ${CRITIC:+--critic "$CRITIC"} ${LANE_NORM:+--lane-norm "$LANE_NORM"} --policy "$POLICY" \
83
+ --tasks "$TASKS" --n-init "$NINIT" --seed "$SEED" --policy-seed "$PSEED" --fresh "$FRESH" \
84
+ --cam-res "$CAMRES" --init-source "$INITSRC" ${VIDEO:+--save-video-frames "$VIDEO"} --probe-ood "$PROBEOOD" --q-filter "$QFILTER" --demo-cand "$DEMOCAND" --select "$SELECT" --init-jitter "$JITTER" ${SAVEFRAMES:+--save-frames "$SAVEFRAMES"} --qf-beta "$QFBETA" --qf-depth "$QFDEPTH" ${HOPPOL:+--hop-policy "$HOPPOL"} --qf-pessimism "$QFPES" \
85
+ ${QFCKPT:+--qf-ckpt "$QFCKPT"} --policy-temp "$PTEMP" --policy-sde "$PSDE" --qf-gate "$QFGATE" \
86
+ --suite libero_10 --max-steps "$MAXSTEPS" --execute "$EXEC" \
87
+ --out "$OUT"
88
+ RC=$?
89
+ echo "[eval] done rc=$RC"
90
+ exit $RC
frozen/rsm_libero_freeze_20261002/extract_clips.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build playable clips: demos (hdf5) vs rollout successes vs rollout failures (parquet).
2
+
3
+ Same task, same frame budget, same size -- so the three slices are directly comparable
4
+ by eye. Demos come from the stock LIBERO hdf5 (agentview_rgb); rollouts from the source
5
+ corpus PNGs.
6
+ """
7
+ import argparse, base64, io, json, os, re
8
+ import numpy as np
9
+
10
+ SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"
11
+ DEMO = "/data/pulkitag/users/rli14/libero_datasets/libero_10"
12
+ PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
13
+
14
+
15
+ def src_parquet(ep_src):
16
+ m = PAT.search(str(ep_src))
17
+ if not m: return None
18
+ t, b, i, idx = m.groups()
19
+ p = (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}"
20
+ f"/data/chunk-000/episode_{int(idx):06d}.parquet")
21
+ return p if os.path.exists(p) else None
22
+
23
+
24
+ def enc(arr, px, q):
25
+ from PIL import Image
26
+ im = Image.fromarray(arr).convert("RGB")
27
+ im.thumbnail((px, px))
28
+ b = io.BytesIO(); im.save(b, "JPEG", quality=q)
29
+ return base64.b64encode(b.getvalue()).decode()
30
+
31
+
32
+ def pick(n, k):
33
+ """k evenly spaced indices spanning 0..n-1, always including the last frame."""
34
+ if n <= k: return list(range(n))
35
+ return [int(round(i * (n - 1) / (k - 1))) for i in range(k)]
36
+
37
+
38
+ def main():
39
+ ap = argparse.ArgumentParser()
40
+ ap.add_argument("--cache", required=True); ap.add_argument("--out", required=True)
41
+ ap.add_argument("--per", type=int, default=3, help="episodes per slice per task")
42
+ ap.add_argument("--nf", type=int, default=36); ap.add_argument("--px", type=int, default=84)
43
+ ap.add_argument("--quality", type=int, default=45)
44
+ args = ap.parse_args()
45
+
46
+ import pyarrow.parquet as pq, h5py
47
+ m = np.load(f"{args.cache}/meta.npz", allow_pickle=True)
48
+ d, s, task = m["ep_demo"].astype(bool), m["ep_success"].astype(bool), m["ep_task"]
49
+ tasks = [str(t) for t in m["tasks"]]
50
+ rng = np.random.default_rng(0)
51
+ out = {"tasks": tasks, "nf": args.nf, "clips": []}
52
+
53
+ for ti, tname in enumerate(tasks):
54
+ # demos straight from the stock LIBERO hdf5
55
+ h = f"{DEMO}/{tname}_demo.hdf5"
56
+ if os.path.exists(h):
57
+ with h5py.File(h, "r") as f:
58
+ keys = sorted(f["data"].keys(), key=lambda x: int(x.split("_")[1]))
59
+ for k in keys[:args.per]:
60
+ rgb = f["data"][k]["obs"]["agentview_rgb"]
61
+ ids = pick(rgb.shape[0], args.nf)
62
+ # robosuite stores bottom-up; flip to human-upright like the evaluator
63
+ fr = [enc(np.asarray(rgb[i])[::-1], args.px, args.quality) for i in ids]
64
+ out["clips"].append({"slice": "demo", "task": ti,
65
+ "len": int(rgb.shape[0]), "f": fr})
66
+ else:
67
+ print(f"[clip] MISSING demo hdf5 for {tname}", flush=True)
68
+ # rollouts from the source parquet
69
+ for name, mask in (("success", s & ~d), ("failure", ~s & ~d)):
70
+ cand = np.where(mask & (task == ti))[0]
71
+ rng.shuffle(cand)
72
+ got = 0
73
+ for e in cand:
74
+ if got >= args.per: break
75
+ p = src_parquet(m["ep_src"][e])
76
+ if not p: continue
77
+ try:
78
+ tb = pq.read_table(p, columns=["image"])
79
+ ids = pick(tb.num_rows, args.nf)
80
+ from PIL import Image
81
+ fr = []
82
+ for i in ids:
83
+ im = Image.open(io.BytesIO(tb["image"][i].as_py()["bytes"]))
84
+ fr.append(enc(np.asarray(im.convert("RGB")), args.px, args.quality))
85
+ out["clips"].append({"slice": name, "task": ti,
86
+ "len": int(tb.num_rows), "f": fr})
87
+ got += 1
88
+ except Exception as ex:
89
+ print(f"[clip] t{ti} {name}: {str(ex)[:50]}", flush=True)
90
+ print(f"[clip] task {ti} done ({len(out['clips'])} clips)", flush=True)
91
+
92
+ json.dump(out, open(args.out, "w"))
93
+ print(f"[clip] wrote {args.out} {os.path.getsize(args.out)/1e6:.1f} MB "
94
+ f"{len(out['clips'])} clips", flush=True)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
frozen/rsm_libero_freeze_20261002/extract_viz.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sample episodes from each corpus slice and emit a compact JSON bundle for the viewer.
2
+
3
+ Demos have no frames anywhere on disk (the OGPO demo cache stores latents only, and
4
+ LIBERO's datasets/ dir is not installed), so frames are rollout-only. End-effector
5
+ trajectories come from proprio and exist for all three slices, which makes them the one
6
+ directly comparable view.
7
+ """
8
+ import argparse, base64, io, json, os, re, sys
9
+ import numpy as np
10
+
11
+ SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"
12
+ PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
13
+
14
+
15
+ def src_parquet(ep_src):
16
+ m = PAT.search(str(ep_src))
17
+ if not m: return None
18
+ t, b, i, idx = m.groups()
19
+ p = (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}"
20
+ f"/data/chunk-000/episode_{int(idx):06d}.parquet")
21
+ return p if os.path.exists(p) else None
22
+
23
+
24
+ def jpeg(png_bytes, px, q):
25
+ from PIL import Image
26
+ im = Image.open(io.BytesIO(png_bytes)).convert("RGB")
27
+ im.thumbnail((px, px))
28
+ b = io.BytesIO(); im.save(b, "JPEG", quality=q)
29
+ return base64.b64encode(b.getvalue()).decode()
30
+
31
+
32
+ def main():
33
+ ap = argparse.ArgumentParser()
34
+ ap.add_argument("--cache", required=True)
35
+ ap.add_argument("--out", required=True)
36
+ ap.add_argument("--n", type=int, default=100)
37
+ ap.add_argument("--px", type=int, default=110)
38
+ ap.add_argument("--quality", type=int, default=55)
39
+ args = ap.parse_args()
40
+
41
+ import pyarrow.parquet as pq
42
+ m = np.load(f"{args.cache}/meta.npz", allow_pickle=True)
43
+ d, s = m["ep_demo"].astype(bool), m["ep_success"].astype(bool)
44
+ task, lo, hi = m["ep_task"], m["ep_from"], m["ep_to"]
45
+ tasks = [str(t) for t in m["tasks"]]
46
+ prop = np.load(f"{args.cache}/proprio.f32.npy", mmap_mode="r")
47
+ rng = np.random.default_rng(0)
48
+
49
+ slices = {"demo": np.where(d)[0],
50
+ "success": np.where(s & ~d)[0],
51
+ "failure": np.where(~s & ~d)[0]}
52
+ out = {"tasks": tasks, "episodes": []}
53
+ for name, pool in slices.items():
54
+ # stratify across tasks so no slice is dominated by one scene
55
+ pick = []
56
+ per = max(1, args.n // max(len(set(task[pool].tolist())), 1))
57
+ for t in sorted(set(task[pool].tolist())):
58
+ c = pool[task[pool] == t]
59
+ pick += list(rng.choice(c, size=min(per, len(c)), replace=False))
60
+ pick = list(rng.permutation(pick))[:args.n]
61
+ print(f"[viz] {name}: {len(pick)} episodes", flush=True)
62
+ for e in pick:
63
+ a, b = int(lo[e]), int(hi[e])
64
+ P = np.asarray(prop[a:b], np.float32)
65
+ k = max(1, len(P) // 60)
66
+ rec = {"slice": name, "task": int(task[e]), "len": int(b - a),
67
+ "eef": [[round(float(v), 4) for v in p[:3]] for p in P[::k]],
68
+ "grip": [round(float(p[6]), 4) for p in P[::k]]}
69
+ if name != "demo":
70
+ p = src_parquet(m["ep_src"][e])
71
+ if p:
72
+ try:
73
+ tb = pq.read_table(p, columns=["image"])
74
+ n = tb.num_rows
75
+ rec["frames"] = [
76
+ jpeg(tb["image"][i].as_py()["bytes"], args.px, args.quality)
77
+ for i in (0, n // 2, n - 1)]
78
+ except Exception as ex:
79
+ rec["err"] = str(ex)[:60]
80
+ out["episodes"].append(rec)
81
+ with open(args.out, "w") as f:
82
+ json.dump(out, f)
83
+ mb = os.path.getsize(args.out) / 1e6
84
+ nf = sum(1 for e in out["episodes"] if "frames" in e)
85
+ print(f"[viz] wrote {args.out} {mb:.1f} MB "
86
+ f"{len(out['episodes'])} episodes, {nf} with frames", flush=True)
87
+
88
+
89
+ if __name__ == "__main__":
90
+ main()
frozen/rsm_libero_freeze_20261002/ibm_autoresearch.sh ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Autoresearch for "RSM beats BC-on-demos": screen settings on a VALIDATION set of initial
3
+ # conditions (protocol V: fresh inits, SEED=7, 20 per task = 200 episodes), select
4
+ # checkpoints on BOTH sides by arg-max over checkpoints on V, then confirm the winners on
5
+ # the untouched test protocols A/B x 3 seeds at n=500. Cells are named <arm>_<prop>_s7e7_V.
6
+ # usage: ibm_autoresearch.sh train | stage1 | bcsel | stage2 <beta> <depth> | stage3 <arm> <env> [prop] [policy] [hop]
7
+ set -uo pipefail
8
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; CACHE=$IB/cache/full_r256
9
+ S="ssh -o BatchMode=yes -o ConnectTimeout=20"
10
+ CB=$R/qsg_f/ckpt_best.pt; PROPL=$R/BCdemo_f/policy_last.pt; HOP=$R/HOPdemo_f/policy_r1.pt
11
+ V="SEED=7, QFCRN=1, QFPART=${QFPART:-256}"; VN=20
12
+ sub(){ echo "$(NINIT=$VN ./ibm_cell.sh "$1" "$2" 7 1 "$3" </dev/null) $1"; }
13
+ cell(){ $S bluevela "bsub -G grp_preemptable -q preemptable -r -gpu num=1 -n 8 -M 160G -R 'rusage[mem=160G]' -J $1 -o $R/logs/$1.out -e $R/logs/$1.err -env \"all, CELL=$1, CMD=$2, O=$R\" $IB/run_cell.sh" 2>&1 | grep -o "<[0-9]*>"; }
14
+ CR="train_rsm.py --cache $CACHE --d-z 256 --enc-width 1024 --flow-width 1024 --flow-depth 4 --chunk 10 --batch 512 --lr 3e-4 --ema 0.995 --var-floor 0.1 --w-reward 1.0 --flow-steps 8 --w-actcon 0.5 --warmup-reward 2000 --in-ram 1 --append-proprio 1 --resume 1 --steps 400000 --eval-every 10000 --seed 0 --reward-mode subgoal --subgoal-dir $R/subgoals_full --success-mask $R/verified_mask.npz --save-every 20000"
15
+ BC="bc_arm.py --cache $CACHE --chunk 10 --bc-steps 120000 --batch 1024 --lr 3e-4 --norm-pool demos --feat-scale center --policy-features raw --policy-family concat --in-ram 1 --reward-mode soft --success-gamma 0.995 --seed 0 --save-every 10000"
16
+ case "${1:?}" in
17
+ train) # BC with periodic checkpoints (for fair arg-max selection) + two critic variants
18
+ echo "$(cell BCdemo_c "$BC --pool demos --out $R/BCdemo_c" </dev/null) BCdemo_c"
19
+ echo "$(cell qsg_b90 "$CR --beta-lo 0.85 --beta-hi 0.95 --beta-q 0.90 --out $R/qsg_b90" </dev/null) qsg_b90"
20
+ echo "$(cell qsg_wide "$CR --beta-lo 0.93 --beta-hi 0.995 --beta-q 0.98 --flow-width 2048 --flow-depth 6 --out $R/qsg_wide" </dev/null) qsg_wide";;
21
+ stage1) # beta_q x depth on V, plus the value-free baselines
22
+ sub plain_DL_s7e7_V $PROPL "QFILTER=0, $V"
23
+ sub medoid8_DL_s7e7_V $PROPL "SELECT=medoid, QFILTER=8, QFDEPTH=1, QFBETA=0.98, QFPES=0, QFGATE=0, $V"
24
+ sub random8_DL_s7e7_V $PROPL "SELECT=random, QFILTER=8, QFDEPTH=1, QFBETA=0.98, QFPES=0, QFGATE=0, $V"
25
+ for b in 90 95 98; do for d in 1 2 3; do
26
+ sub RSMb${b}d${d}p${QFPART:-256}_DL_s7e7_V $PROPL "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=$d, QFILTER=8, QFBETA=0.$b, QFPES=0, QFGATE=0, $V"
27
+ done; done;;
28
+ bcsel) # plain BC at every periodic checkpoint of BCdemo_c, on V
29
+ for st in $($S bluevela "ls $R/BCdemo_c/policy_s*.pt 2>/dev/null | sed -E 's/.*policy_s([0-9]+)\.pt/\1/' | sort -n"); do
30
+ sub plainC${st}_DL_s7e7_V $R/BCdemo_c/policy_s${st}.pt "QFILTER=0, $V"
31
+ done;;
32
+ stage2) # around the best (beta, depth): N, selector, Q mode, critic ckpt, pessimism, CRN off
33
+ b=${2:?}; d=${3:?}; base="CRITIC=$CB, HOPPOL=$HOP, QFDEPTH=$d, QFBETA=0.$b, QFGATE=0, $V"
34
+ sub RSMb${b}d${d}n32_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=32, QFPES=0, $base"
35
+ sub RSMb${b}d${d}n16_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=16, QFPES=0, $base"
36
+ sub RSMb${b}d${d}q90_DL_s7e7_V $PROPL "SELECT=quantile, SELQ=0.9, QFILTER=8, QFPES=0, $base"
37
+ sub RSMb${b}d${d}q90n32_DL_s7e7_V $PROPL "SELECT=quantile, SELQ=0.9, QFILTER=32, QFPES=0, $base"
38
+ sub RSMb${b}d${d}near4_DL_s7e7_V $PROPL "SELECT=qnear, QNEARK=4, QFILTER=8, QFPES=0, $base"
39
+ sub RSMb${b}d${d}fold_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=0, QFMODE=fold, $base"
40
+ sub RSMb${b}d${d}pes1_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=1, $base"
41
+ sub RSMb${b}d${d}nocrn_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=0, CRITIC=$CB, HOPPOL=$HOP, QFDEPTH=$d, QFBETA=0.$b, QFGATE=0, SEED=7, QFCRN=0"
42
+ sub RSMb${b}d${d}cL_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=0, CRITIC=$R/qsg_f/ckpt.pt, HOPPOL=$HOP, QFDEPTH=$d, QFBETA=0.$b, QFGATE=0, $V";;
43
+ critsel) # critic checkpoint selection on V: RSM 3-hop at every periodic checkpoint of <run>
44
+ run=${2:?}; b=${3:-95}; d=${4:-3}
45
+ for st in $($S bluevela "ls $R/$run/ckpt_s*.pt 2>/dev/null | sed -E 's/.*ckpt_s([0-9]+)\.pt/\1/' | sort -n"); do
46
+ sub RSMc${run}S${st}_DL_s7e7_V $PROPL "CRITIC=$R/$run/ckpt_s${st}.pt, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=$d, QFILTER=8, QFBETA=0.$b, QFPES=0, QFGATE=0, SEED=7, QFCRN=1, QFPART=16"
47
+ done;;
48
+ stage3) # confirm: <arm> <env> on A/B x seeds 0,1e1,2e2 at n=500 (proposer = BC ckpt of record)
49
+ arm=${2:?}; env=${3:?}; prop=${4:-DL}; pol=${5:-$PROPL}
50
+ for s in 0 1 2; do for P in A B; do F=0; [ $P = B ] && F=1; sfx=$s; [ $s != 0 ] && sfx=${s}e${s}
51
+ echo "$(./ibm_cell.sh ${arm}_${prop}_s${sfx}_$P $pol $s $F "$env, SEED=$s" </dev/null) ${arm}_${prop}_s${sfx}_$P"
52
+ done; done;;
53
+ esac
frozen/rsm_libero_freeze_20261002/ibm_bias_diag.sh ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Proposer-bias diagnostic on IBM: no env, one GPU. Reuses ibm_eval.sh's environment block.
3
+ set -uo pipefail
4
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256
5
+ PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python
6
+ export RSM_TASKS_FILE=$IB/lib10_tasks.txt RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktree
7
+ export OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorch
8
+ export OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.model
9
+ export LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard MUJOCO_GL=egl PYOPENGL_PLATFORM=egl
10
+ export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1
11
+ export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/"
12
+ cd $IB/code
13
+ $PY proposer_bias_diag.py --cache $IB/cache/full_r256 --critic "${CRITIC:-$R/qsg_f/ckpt_best.pt}" \
14
+ --hop-policy "${HOP:-$R/HOPdemo_f/policy_r1.pt}" --pol1 $R/BCdemo_f/policy_last.pt --pol2 $R/BCsuccv_f2/policy_r1.pt \
15
+ --depth "${DEPTH:-3}" --beta "${BETA:-0.95}" --n "${N:-8}" --frames "${FRAMES:-512}" --particles "${PART:-16}" \
16
+ --out "${OUT:-$R/diag/proposer_bias_d${DEPTH:-3}.json}"
frozen/rsm_libero_freeze_20261002/ibm_cell.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Submit one eval cell on IBM as 10 single-task jobs + 1 assembly job.
3
+ # ibm_cell.sh <name> <policy> <pseed> <fresh> "<extra env, comma-separated>"
4
+ # Each task job gets its own GPU (a second env on a used GPU aborts on this EGL driver);
5
+ # the assembly job runs once all ten are done, resumes from the per-task partials, builds
6
+ # no env, and writes <name>.json. Wall-clock per cell drops ~10x.
7
+ set -uo pipefail
8
+ NAME=${1:?}; POLICY=${2:?}; PSEED=${3:-0}; FRESH=${4:-0}; EXTRA=${5:-}
9
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logs
10
+ Q=${LSF_QUEUE:-normal}; G=${LSF_GROUP:-grp_runtime}
11
+ MANIFEST_ONLY=${MANIFEST_ONLY:-0}
12
+ COMMON="all, POLICY=$POLICY, OUT=$E/$NAME.json, NINIT=${NINIT:-50}, PSEED=$PSEED, FRESH=$FRESH, CAMRES=256${EXTRA:+, $EXTRA}"
13
+ ssh -o BatchMode=yes -o ConnectTimeout=20 bluevela "
14
+ export MANIFEST_ONLY=$MANIFEST_ONLY
15
+ printf '%s' \"$COMMON\" > $E/$NAME.cell # manifest: the env this cell was submitted with (retries read it)
16
+ [ \"\${MANIFEST_ONLY:-0}\" = 1 ] && exit 0
17
+ for t in 0 1 2 3 4 5 6 7 8 9; do
18
+ bsub -G $G -q $Q -gpu num=1 -n 8 -M 64G -J ${NAME}_t\$t -o $L/${NAME}_t\$t.out -e $L/${NAME}_t\$t.err -env \"$COMMON, TASKS=\$t, PARTIALONLY=1\" $IB/code/ibm_eval.sh >/dev/null 2>&1
19
+ done
20
+ bsub -G $G -q $Q -n 4 -M 32G -J ${NAME}_asm -o $L/${NAME}_asm.out -e $L/${NAME}_asm.err -env \"$COMMON, ASM=1\" $IB/code/ibm_eval.sh 2>&1 | grep -o '<[0-9]*>'
21
+ " </dev/null 2>&1 | grep -v Authorized | tr -d '<>'
frozen/rsm_libero_freeze_20261002/ibm_crn_diag.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CRN diagnostic on IBM: no env, one GPU. Reuses ibm_eval.sh's environment block.
3
+ set -uo pipefail
4
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256
5
+ PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python
6
+ export RSM_TASKS_FILE=$IB/lib10_tasks.txt RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktree
7
+ export OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorch
8
+ export OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.model
9
+ export LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard MUJOCO_GL=egl PYOPENGL_PLATFORM=egl
10
+ export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1
11
+ export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/"
12
+ cd $IB/code
13
+ $PY crn_diag.py --critic $R/qsg_f/ckpt_best.pt --policy "${POLICY:?}" --hop "${HOP:?}" --depth "${DEPTH:-3}" --n "${N:-8}" --states "${STATES:-200}" --particles "${PART:-16}"
frozen/rsm_libero_freeze_20261002/ibm_eval.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Closed-loop LIBERO-10 eval on IBM. Same evaluator (eval_closed_loop.py), the pinned venv
3
+ # (version-identical to MIT), and the same 256 render -- results are admissible alongside
4
+ # MIT's. Env: POLICY OUT [CRITIC QFCKPT QFILTER SELECT PSEED FRESH NINIT TASKS CAMRES ...]
5
+ set -uo pipefail
6
+ IB=/proj/dmfexp/zwhong/rsm_libero
7
+ export RSM_TASKS_FILE=/proj/dmfexp/zwhong/rsm_libero/lib10_tasks.txt
8
+ export RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktree
9
+ export OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorch
10
+ export OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.model
11
+ export LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard
12
+ export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl
13
+ _G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)"; export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G"
14
+ export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1
15
+ # robosuite EGL context free() aborts the process on this driver: never close envs here
16
+ export RSM_NO_ENV_CLOSE=1
17
+ export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/"
18
+ PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python
19
+ TASKS=${TASKS:-0,1,2,3,4,5,6,7,8,9}; TASKS=${TASKS//;/,} # LSF -env cannot carry commas: pass task lists with ";"
20
+ cd $IB/code
21
+ # One LSF job = one GPU = one process. A second OffScreenRenderEnv on a GPU that already
22
+ # hosted one aborts on this EGL driver (even across processes), so a full n=500 cell is
23
+ # submitted as 10 single-task jobs (ibm_eval_matrix.sh) plus an assembly job that runs
24
+ # with every task already in <out>.partial.t* and therefore builds no env.
25
+ run_eval(){ $PY eval_closed_loop.py ${CRITIC:+--critic "$CRITIC"} --policy "${POLICY:?}" \
26
+ --tasks "${TASKS:-0,1,2,3,4,5,6,7,8,9}" --n-init "${NINIT:-50}" --seed "${SEED:-0}" --policy-seed "${PSEED:-0}" --fresh "${FRESH:-0}" \
27
+ --cam-res "${CAMRES:-256}" --q-filter "${QFILTER:-0}" --select "${SELECT:-argmaxq}" \
28
+ --qf-beta "${QFBETA:-0.98}" --qf-depth "${QFDEPTH:-1}" ${HOPPOL:+--hop-policy "$HOPPOL"} --qf-pessimism "${QFPES:-0}" --qf-gate "${QFGATE:-0}" --qnear-k "${QNEARK:-4}" --qf-crn "${QFCRN:-0}" --qf-particles "${QFPART:-16}" --select-q "${SELQ:-0.9}" ${POLICY2:+--policy2 "$POLICY2"} --q-filter2 "${QFILTER2:-0}" --qf-mode "${QFMODE:-restart}" \
29
+ ${QFCKPT:+--qf-ckpt "$QFCKPT"} --policy-temp "${TEMP:-1.0}" --policy-sde "${SDE:-0.0}" --policy-sde-anneal "${SDEANN:-0}" --probe-ood "${PROBEOOD:-0}" \
30
+ --suite libero_10 --max-steps "${MAXSTEPS:-520}" --execute 10 --out "${OUT:?}" --partial-only "${PARTIALONLY:-0}"; }
31
+ if [ "${ASM:-0}" = 1 ]; then
32
+ # Assembly: wait until every task's partial exists (task jobs retry on EGL aborts), then
33
+ # run with nothing left to do -- no env is built, the JSON is written.
34
+ for i in $(seq 1 360); do n=$(ls "${OUT}.partial.t"* 2>/dev/null | wc -l); [ "$n" -ge "${NTASKS:-10}" ] && break; sleep 60; done
35
+ echo "[eval] assembly: $n/${NTASKS:-10} partials present"; run_eval; echo "[eval] done rc=$?"; exit 0
36
+ fi
37
+ RETRY=${RETRY:-0}; PARTIALONLY=${PARTIALONLY:-0}
38
+ echo "[eval] start $(date -u +%FT%TZ) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}"
39
+ run_eval; RC=$?
40
+ echo "[eval] done rc=$RC $(date -u +%FT%TZ)"
41
+ # Some GPUs are left in a bad EGL state by earlier jobs: the first env creation aborts
42
+ # (SIGABRT 134 / SIGSEGV 139) with no traceback. Resubmit the task -- a different node is
43
+ # likely -- up to 6 times. Only for single-task partial jobs, and only if the partial is
44
+ # still missing.
45
+ if [ "${PARTIALONLY:-0}" = 1 ] && { [ "$RC" = 134 ] || [ "$RC" = 139 ]; } && [ ! -f "${OUT}.partial.t${TASKS}" ] && [ "${RETRY:-0}" -lt 6 ]; then
46
+ echo "[eval] EGL abort on $(hostname); resubmitting task ${TASKS} (retry $((RETRY+1)))"
47
+ bsub -G "${LSF_GROUP:-grp_runtime}" -q "${LSF_QUEUE:-normal}" -gpu num=1 -n 8 -M 64G -J "${LSB_JOBNAME}" \
48
+ -o "${LSB_OUTPUTFILE:-/dev/null}" -e "${LSB_ERRORFILE:-/dev/null}" \
49
+ -env "all, RETRY=$((RETRY+1))" $IB/code/ibm_eval.sh
50
+ fi
51
+ exit $RC
frozen/rsm_libero_freeze_20261002/ibm_eval_depth.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # beta-hop sweep cells only. usage: ibm_eval_depth.sh <proposer_run> <tag> <hop_run> [seeds] [depths]
3
+ set -uo pipefail
4
+ PROPRUN=${1:?}; TAG=${2:?}; HOPRUN=${3:?}; SEEDS=${4:-0}; DEPTHS=${5:-2,3}
5
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logs
6
+ S="ssh -o BatchMode=yes -o ConnectTimeout=20"
7
+ sub(){ ./ibm_cell.sh "$1" "$2" "$3" "$4" "$5"; }
frozen/rsm_libero_freeze_20261002/ibm_eval_matrix.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Extraction matrix on IBM over a given PROPOSER policy: n=500, protocols A/B, evaluator
3
+ # at 256, one LSF job per cell. usage: ibm_eval_matrix.sh <proposer_run_dir_name> <tag> [seeds]
4
+ # e.g. ibm_eval_matrix.sh BCdemo_f D 0,1,2 -> cells RSMsg8_D_s0_A ... (D = demos proposer)
5
+ # ibm_eval_matrix.sh BCsuccv_f2 S 0 -> the successes proposer ladder
6
+ set -uo pipefail
7
+ PROPRUN=${1:?proposer run dir}; TAG=${2:?tag}; SEEDS=${3:-0}; HOPRUN=${4:-} # 4th arg: latent hop policy run dir -> depth 2/3 cells
8
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logs
9
+ S="ssh -o BatchMode=yes -o ConnectTimeout=20"
10
+ sub(){ ./ibm_cell.sh "$1" "$2" "$3" "$4" "$5"; }
11
+ PROP=$R/$PROPRUN/policy_r1.pt; BON="QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=0, QFGATE=0"
12
+ for s in ${SEEDS//,/ }; do for P in A B; do F=0; [ $P = B ] && F=1
13
+ echo "$(sub RSMsg8_${TAG}_s${s}_$P $PROP $s $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=argmaxq, $BON") RSMsg8_$TAG s$s $P"
14
+ echo "$(sub medoid8_${TAG}_s${s}_$P $PROP $s $F "SELECT=medoid, $BON") medoid8_$TAG s$s $P"
15
+ echo "$(sub plain_${TAG}_s${s}_$P $PROP $s $F "QFILTER=0") plain_$TAG s$s $P"
16
+ done; done
17
+ # beta-hop sweep (depth 2, 3) with the matching latent hop policy (4th arg)
18
+ [ -n "$HOPRUN" ] && HOP=$R/$HOPRUN && for D in 2 3; do for s in ${SEEDS//,/ }; do for P in A B; do F=0; [ $P = B ] && F=1
19
+ echo "$(sub RSMsg8d${D}_${TAG}_s${s}_$P $PROP $s $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=argmaxq, HOPPOL=$HOP/policy_r1.pt, QFDEPTH=$D, QFILTER=8, QFBETA=0.98, QFPES=0, QFGATE=0") RSMsg8 depth$D $TAG s$s $P"
20
+ done; done; done
21
+ for P in A B; do F=0; [ $P = B ] && F=1
22
+ echo "$(sub RSMind8_${TAG}_s0_$P $PROP 0 $F "CRITIC=$R/qind_f/ckpt_best.pt, SELECT=argmaxq, $BON") RSMind8_$TAG s0 $P"
23
+ echo "$(sub random8_${TAG}_s0_$P $PROP 0 $F "SELECT=random, $BON") random8_$TAG s0 $P"
24
+ [ -n "${IQLQ:-}" ] && echo "$(sub IQL8_${TAG}_s0_$P $PROP 0 $F "QFCKPT=$IQLQ, SELECT=argmaxq, $BON") IQL8_$TAG s0 $P"
25
+ done
frozen/rsm_libero_freeze_20261002/ibm_eval_matrix_last.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Extraction matrix over the BC-demos LAST checkpoint proposer (tag DL). The held-out
3
+ # sampled-MSE proxy picked step 102k (policy_r1.pt) which evaluates ~0.10 SR below the
4
+ # final step-120k weights (policy_last.pt), so every "DL" cell uses the last checkpoint on
5
+ # the BC side. 3 seeds varying BOTH the policy sampling seed and the eval-init seed
6
+ # (s0, s1e1, s2e2), protocols A/B, n=500. Submission order = decision priority.
7
+ set -uo pipefail
8
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256
9
+ PROPL=$R/BCdemo_f/policy_last.pt; HOP=$R/HOPdemo_f/policy_r1.pt
10
+ CB=$R/qsg_f/ckpt_best.pt; CL=$R/qsg_f/ckpt.pt
11
+ BON="QFILTER=8, QFBETA=0.98, QFPES=0, QFGATE=0"
12
+ D3="SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=3, $BON"
13
+ sub(){ echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }
14
+ # 1) the claim: RSM-3hop vs BC-last plain, seeds 1,2 (seed 0 already done)
15
+ for s in 1 2; do for P in A B; do F=0; [ $P = B ] && F=1
16
+ sub RSMsg8d3_DL_s${s}e${s}_$P $PROPL $s $F "CRITIC=$CB, $D3, SEED=$s"
17
+ sub plain_DL_s${s}e${s}_$P $PROPL $s $F "QFILTER=0, SEED=$s"
18
+ done; done
19
+ # 2) value-free selectors on the same proposer (medoid / random of 8), all 3 seeds
20
+ for s in 0 1 2; do for P in A B; do F=0; [ $P = B ] && F=1
21
+ sfx=$s; [ $s != 0 ] && sfx=${s}e${s}
22
+ sub medoid8_DL_s${sfx}_$P $PROPL $s $F "SELECT=medoid, QFDEPTH=1, $BON, SEED=$s"
23
+ sub random8_DL_s${sfx}_$P $PROPL $s $F "SELECT=random, QFDEPTH=1, $BON, SEED=$s"
24
+ done; done
25
+ # 3) hop ladder (depth 1, 2) and the critic-LAST control for depth 3
26
+ for s in 0 1 2; do for P in A B; do F=0; [ $P = B ] && F=1
27
+ sfx=$s; [ $s != 0 ] && sfx=${s}e${s}
28
+ sub RSMsg8_DL_s${sfx}_$P $PROPL $s $F "CRITIC=$CB, SELECT=argmaxq, QFDEPTH=1, $BON, SEED=$s"
29
+ sub RSMsg8d2_DL_s${sfx}_$P $PROPL $s $F "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=2, $BON, SEED=$s"
30
+ done; done
31
+ for P in A B; do F=0; [ $P = B ] && F=1
32
+ sub RSMsg8d3L_DL_s0_$P $PROPL 0 $F "CRITIC=$CL, $D3"
33
+ done
34
+ # 4) hop-policy LAST checkpoint (HOPdemo_f best was step 36k of 120k) for depth 3
35
+ HOPL=$R/HOPdemo_f/policy_last.pt
36
+ for P in A B; do F=0; [ $P = B ] && F=1
37
+ sub RSMsg8d3H_DL_s0_$P $PROPL 0 $F "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOPL, QFDEPTH=3, $BON"
38
+ done
frozen/rsm_libero_freeze_20261002/ibm_eval_ocb.sh ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # OCBench block-quadruple techniques (hd_bon32 arm) transplanted onto LIBERO-10:
3
+ # best-of-32 candidates, all scored on shared noise (common random numbers), Q = the
4
+ # product fold Q_k = c_k + (1-c_k) gamma^(1/(1-beta)) Q_{k+1} over a FIXED number of
5
+ # hops, read-out c = success/progress head; proposer = a broad BC policy (their actor
6
+ # is BC on ALL data with q_coef=0; here BC-on-successes (S) is the broad one, BC-demos-
7
+ # last (DL) the strong one). Controls: random-of-32 (no critic) and our restart-Q at N=32.
8
+ # usage: ibm_eval_ocb.sh [critic_run=qsg_f] [tag_suffix]
9
+ set -uo pipefail
10
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256
11
+ CRIT=${1:-qsg_f}; SFX=${2:-}
12
+ CB=$R/$CRIT/ckpt_best.pt
13
+ sub(){ echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }
14
+ for spec in "S:$R/BCsuccv_f2/policy_r1.pt:$R/HOPsucc_f/policy_r1.pt" "DL:$R/BCdemo_f/policy_last.pt:$R/HOPdemo_f/policy_r1.pt"; do
15
+ IFS=: read TAG PROP HOP <<<"$spec"
16
+ for P in A B; do F=0; [ $P = B ] && F=1
17
+ for D in 1 2 3; do
18
+ sub RSMfold${D}n32${SFX}_${TAG}_s0_$P $PROP 0 $F "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=$D, QFILTER=32, QFBETA=0.98, QFPES=0, QFGATE=0, QFCRN=1, QFMODE=fold"
19
+ done
20
+ sub RSMsg32d3crn${SFX}_${TAG}_s0_$P $PROP 0 $F "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=3, QFILTER=32, QFBETA=0.98, QFPES=0, QFGATE=0, QFCRN=1"
21
+ [ -z "$SFX" ] && sub random32_${TAG}_s0_$P $PROP 0 $F "SELECT=random, QFDEPTH=1, QFILTER=32, QFBETA=0.98, QFPES=0, QFGATE=0"
22
+ done
23
+ done
frozen/rsm_libero_freeze_20261002/ibm_eval_robust.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Robustness grid for the RSM-3hop claim on the demos proposer:
3
+ # (a) eval-seed variation: SEED 1,2 (init randomness) x PSEED 1,2, both protocols, for
4
+ # RSM-3hop / plain / medoid
5
+ # (b) checkpoint selection on both sides: critic LAST (400k) vs BEST (220k, win-rate
6
+ # selected); BC-demos LAST (120k) vs BEST (102k, held-out-MSE selected)
7
+ set -uo pipefail
8
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256
9
+ PROP=$R/BCdemo_f/policy_r1.pt; PROPL=$R/BCdemo_f/policy_last.pt; HOP=$R/HOPdemo_f/policy_r1.pt
10
+ CB=$R/qsg_f/ckpt_best.pt; CL=$R/qsg_f/ckpt.pt
11
+ D3="SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=3, QFILTER=8, QFBETA=0.98, QFPES=0, QFGATE=0"
12
+ BON="QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=0, QFGATE=0"
13
+ sub(){ echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }
14
+ # (a) eval seeds
15
+ for es in 1 2; do for P in A B; do F=0; [ $P = B ] && F=1
16
+ sub RSMsg8d3_D_s${es}e${es}_$P $PROP $es $F "CRITIC=$CB, $D3, SEED=$es"
17
+ sub plain_D_s${es}e${es}_$P $PROP $es $F "QFILTER=0, SEED=$es"
18
+ sub medoid8_D_s${es}e${es}_$P $PROP $es $F "SELECT=medoid, $BON, SEED=$es"
19
+ done; done
20
+ # (b) checkpoint selection
21
+ for P in A B; do F=0; [ $P = B ] && F=1
22
+ sub RSMsg8d3L_D_s0_$P $PROP 0 $F "CRITIC=$CL, $D3" # critic LAST checkpoint
23
+ sub plainL_D_s0_$P $PROPL 0 $F "QFILTER=0" # BC LAST checkpoint
24
+ sub RSMsg8d3_DL_s0_$P $PROPL 0 $F "CRITIC=$CB, $D3" # RSM over the BC-last proposer
25
+ done
frozen/rsm_libero_freeze_20261002/ibm_eval_sde.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Noisy-proposal cells: the flow BC policy's 8 ODE samples are near-copies (action std
3
+ # 0.03 vs data 0.42), so a ranker has nothing to choose. Inject SDE noise during
4
+ # integration (SDE=0.5; SDEANN=1 anneals it to zero by the last step) and compare the RSM
5
+ # 3-hop pick against a RANDOM pick of the same noisy candidates (isolates the ranking) and
6
+ # against plain ODE BC (the baseline). Seed 0, protocols A/B, both proposers.
7
+ set -uo pipefail
8
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256
9
+ CB=$R/qsg_f/ckpt_best.pt; BON="QFILTER=8, QFBETA=0.98, QFPES=0, QFGATE=0"
10
+ sub(){ echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }
11
+ for spec in "S:$R/BCsuccv_f2/policy_r1.pt:$R/HOPsucc_f/policy_r1.pt" "DL:$R/BCdemo_f/policy_last.pt:$R/HOPdemo_f/policy_r1.pt"; do
12
+ IFS=: read TAG PROP HOP <<<"$spec"
13
+ for nz in "sde5:SDE=0.5, SDEANN=0" "sde5a:SDE=0.5, SDEANN=1" "sde25a:SDE=0.25, SDEANN=1"; do
14
+ IFS=: read NZ ENV <<<"$nz"
15
+ for P in A B; do F=0; [ $P = B ] && F=1
16
+ sub RSMsg8d3${NZ}_${TAG}_s0_$P $PROP 0 $F "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=3, $BON, $ENV"
17
+ sub random8${NZ}_${TAG}_s0_$P $PROP 0 $F "SELECT=random, QFDEPTH=1, $BON, $ENV"
18
+ done
19
+ done
20
+ done
frozen/rsm_libero_freeze_20261002/ibm_full_wave.sh ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Full-corpus wave on IBM (williamd4112/gen_q#252). Phases, run from MIT:
3
+ # sync-code rsync rsm_libero -> IBM code dir
4
+ # pack bsub: pack full_r256 on IBM from the pinned episode list (CPU, 220G)
5
+ # meta-back scp IBM meta.npz -> MIT so the CPU labellers run without MIT's pack
6
+ # sync-labels rsync subgoals_full + verified_mask -> IBM
7
+ # train bsub: BC arms + critics + IQL (self-resubmitting preemptable cells)
8
+ # eval bsub: n=500 A/B evals at 256 via IBM's run_eval.sh (self-check gated)
9
+ set -uo pipefail
10
+ PH=${1:?phase}
11
+ G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero
12
+ S="ssh -o BatchMode=yes -o ConnectTimeout=20"
13
+ IB=/proj/dmfexp/zwhong/rsm_libero; ID=/proj/dmfexp/zwhong/data
14
+ CACHE=$IB/cache/full_r256; RUNS=$IB/runs/full_r256; LOGS=$RUNS/logs
15
+ PYT=/proj/dmfexp/zwhong/venvs/lerobot_env/bin/python
16
+ MIT_META=/data/pulkitag/users/rli14/rsm_libero_cache/full_r256
17
+ case $PH in
18
+ sync-code)
19
+ rsync -a --exclude __pycache__ --exclude '*.pt' -e "$S" $G/ bluevela:$IB/code/ && echo "code synced";;
20
+ pack)
21
+ $S bluevela "mkdir -p $LOGS $CACHE && bsub -G grp_preemptable -q preemptable -n 32 -M 220G -R 'rusage[mem=220G]' -J pack_full_r256 -o $LOGS/pack.out -e $LOGS/pack.err \
22
+ \"cd $IB/code && $PYT pack.py --src $ID/pi05_lib10_ogpo_fl15_v1 --demos $ID/libero10_demo_ogpo_cache_cam256 --out $CACHE --max-eps 0 --stride 1 --keep-all-demos --workers 32 --cam-res 256 --episode-list $ID/full_r256_episodes.txt --tasks-file $IB/lib10_tasks.txt\"";;
23
+ meta-back)
24
+ mkdir -p $MIT_META && scp -q -o BatchMode=yes bluevela:$CACHE/meta.npz bluevela:$CACHE/PACK.json bluevela:$CACHE/RENDER.json $MIT_META/ && ls -la $MIT_META;;
25
+ sync-labels)
26
+ rsync -a -e "$S" /data/pulkitag/users/rli14/rsm_libero_runs/subgoals_full bluevela:$RUNS/ && \
27
+ rsync -a -e "$S" /data/pulkitag/users/rli14/rsm_libero_runs/verify_full/verified_mask.npz bluevela:$RUNS/ && echo "labels+mask synced";;
28
+ train|train-nomask)
29
+ SG=$RUNS/subgoals_full; MASK=$RUNS/verified_mask.npz
30
+ BC="bc_arm.py --cache $CACHE --chunk 10 --bc-steps 120000 --batch 1024 --lr 3e-4 --norm-pool demos --feat-scale center --policy-features raw --policy-family concat --in-ram 1 --reward-mode soft --success-gamma 0.995 --seed 0"
31
+ CR="train_rsm.py --cache $CACHE --d-z 256 --enc-width 1024 --flow-width 1024 --flow-depth 4 --chunk 10 --beta-lo 0.93 --beta-hi 0.995 --beta-q 0.98 --batch 512 --lr 3e-4 --ema 0.995 --var-floor 0.1 --w-reward 1.0 --flow-steps 8 --w-actcon 0.5 --warmup-reward 2000 --in-ram 1 --append-proprio 1 --resume 1 --steps 400000 --eval-every 10000 --seed 0"
32
+ cell(){ # name cmd
33
+ $S bluevela "bsub -G grp_preemptable -q preemptable -r -gpu num=1 -n 8 -M 160G -R 'rusage[mem=160G]' -J $1 -o $LOGS/$1.out -e $LOGS/$1.err -env \"all, CELL=$1, CMD=$2, O=$RUNS\" $IB/run_cell.sh" 2>&1 | grep -o "<[0-9]*>"; }
34
+ NOMASK="BCd_f|$BC --pool demos --out $RUNS/BCd_f
35
+ BCroll_f|$BC --pool rollsucc --out $RUNS/BCroll_f"
36
+ MASKED="BCrollv_f|$BC --pool rollsucc --success-mask $MASK --out $RUNS/BCrollv_f
37
+ BCsucc_f|$BC --pool succ --success-mask $MASK --out $RUNS/BCsucc_f
38
+ qind_f|$CR --reward-mode subgoal_ind --subgoal-dir $SG --success-mask $MASK --out $RUNS/qind_f
39
+ qsg_f|$CR --reward-mode subgoal --subgoal-dir $SG --success-mask $MASK --out $RUNS/qsg_f"
40
+ [ "$PH" = train-nomask ] && LIST="$NOMASK" || LIST="$MASKED"
41
+ # </dev/null: ssh inside cell() would otherwise swallow the rest of the list from stdin
42
+ while IFS='|' read -r n c; do [ -n "$n" ] && echo "$(cell "$n" "$c" </dev/null) $n"; done <<< "$LIST";;
43
+ *) echo "unknown phase $PH"; exit 1;;
44
+ esac
frozen/rsm_libero_freeze_20261002/ibm_pack_onpol.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Pack the on-policy corpus (eval_closed_loop --collect output) into a second cache with the
3
+ # SAME feature normalisation as full_r256, plus subgoal labels. CPU job.
4
+ set -euo pipefail
5
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256
6
+ PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python
7
+ SRC=${SRC:-$R/collect_onpol/corpus}; OUT=${OUT:-$IB/cache/onpol_r256}
8
+ cd $IB/code
9
+ $PY pack.py --src $SRC --out $OUT --tasks-file $IB/lib10_tasks.txt --cam-res 256 --encoder pi05_base_pytorch --workers 16
10
+ cp $IB/cache/full_r256/feat_stats.npz $IB/cache/full_r256/feat_stats_demos.npz $OUT/
11
+ $PY subgoals_from_npz.py --cache $OUT --out $R/subgoals_onpol
12
+ echo "[pack_onpol] DONE"
frozen/rsm_libero_freeze_20261002/ibm_rerender.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # rerender_rollouts.py on IBM (GPU/EGL). Env: POOL OUT CAMRES [DEMOCACHE ...]
3
+ set -uo pipefail
4
+ IB=/proj/dmfexp/zwhong/rsm_libero
5
+ export RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktree RSM_TASKS_FILE=$IB/lib10_tasks.txt
6
+ export RSM_DEMO_H5=/proj/dmfexp/zwhong/rli14_lib10/libero_datasets/libero_10
7
+ export OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorch
8
+ export OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.model
9
+ export LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard
10
+ export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl
11
+ _G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)"; export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G"
12
+ export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1
13
+ PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python
14
+ cd $IB/code
15
+ $PY rerender_rollouts.py --pool "${POOL:?}" --out "${OUT:?}" --cam-res "${CAMRES:-256}" \
16
+ --demo-cache "${DEMOCACHE:-/proj/dmfexp/zwhong/data/libero10_demo_ogpo_cache_cam256}" \
17
+ --stats /proj/dmfexp/zwhong/rsm_libero/cache/full_r256/feat_stats_demos.npz
18
+ echo "[rr] done rc=$?"
frozen/rsm_libero_freeze_20261002/ibm_resubmit_missing.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Resubmit, through the per-task fan-out, every planned cell that has no final JSON on IBM.
3
+ # Cells are re-derived from the plan (proposer x selector x seed x protocol); tasks whose
4
+ # partial already exists are skipped by the evaluator's resume, so nothing done is redone.
5
+ set -uo pipefail
6
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval
7
+ S="ssh -o BatchMode=yes -o ConnectTimeout=20"
8
+ have=$($S bluevela "ls $E/*.json 2>/dev/null | xargs -n1 basename | sed 's/.json$//'" </dev/null 2>/dev/null | grep -v Authorized)
9
+ IQLQ=$R/iql_f_mit/iql_q.pt; BON="QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=0, QFGATE=0"
10
+ plan(){ # name policy pseed fresh extra
11
+ if [ "${MANIFEST_ONLY:-0}" = 1 ]; then MANIFEST_ONLY=1 ./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null >/dev/null; echo "manifest $1"; return; fi
12
+ echo "$have" | grep -qx "$1" && return
13
+ echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }
14
+ for spec in "D|BCdemo_f|HOPdemo_f|0 1 2" "S|BCsuccv_f2|HOPsucc_f|0"; do IFS='|' read -r TAG PR HOPR SEEDS <<< "$spec"
15
+ PROP=$R/$PR/policy_r1.pt; HOP=$R/$HOPR/policy_r1.pt
16
+ for s in $SEEDS; do for P in A B; do F=0; [ $P = B ] && F=1
17
+ plan RSMsg8_${TAG}_s${s}_$P $PROP $s $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=argmaxq, $BON"
18
+ plan medoid8_${TAG}_s${s}_$P $PROP $s $F "SELECT=medoid, $BON"
19
+ plan plain_${TAG}_s${s}_$P $PROP $s $F "QFILTER=0"
20
+ for D in 2 3; do plan RSMsg8d${D}_${TAG}_s${s}_$P $PROP $s $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=$D, QFILTER=8, QFBETA=0.98, QFPES=0, QFGATE=0"; done
21
+ done; done
22
+ for P in A B; do F=0; [ $P = B ] && F=1
23
+ plan RSMind8_${TAG}_s0_$P $PROP 0 $F "CRITIC=$R/qind_f/ckpt_best.pt, SELECT=argmaxq, $BON"
24
+ plan random8_${TAG}_s0_$P $PROP 0 $F "SELECT=random, $BON"
25
+ plan IQL8_${TAG}_s0_$P $PROP 0 $F "QFCKPT=$IQLQ, SELECT=argmaxq, $BON"
26
+ [ $TAG = D ] && { plan RSMsg8pes1_D_s0_$P $PROP 0 $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=argmaxq, QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=1, QFGATE=0"
27
+ plan RSMsg8pes2_D_s0_$P $PROP 0 $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=argmaxq, QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=2, QFGATE=0"
28
+ plan RSMsg8near4_D_s0_$P $PROP 0 $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=qnear, QNEARK=4, QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=0, QFGATE=0"; }
29
+ done
30
+ done
frozen/rsm_libero_freeze_20261002/ibm_retry_tasks.sh ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Resubmit per-task eval jobs whose partial is missing and which are not RUN/PEND, using
3
+ # the cell manifest (<cell>.cell) written at submission. Idempotent; run repeatedly.
4
+ set -uo pipefail
5
+ ssh -o BatchMode=yes -o ConnectTimeout=20 bluevela '
6
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logs; n=0
7
+ active=$(bjobs -noheader -w 2>/dev/null | awk "\$3==\"RUN\"||\$3==\"PEND\" {print \$7}")
8
+ for m in $E/*.cell; do cell=$(basename $m .cell); [ -f $E/$cell.json ] && continue
9
+ env=$(cat $m)
10
+ for t in 0 1 2 3 4 5 6 7 8 9; do
11
+ [ -f $E/$cell.json.partial.t$t ] && continue
12
+ echo "$active" | grep -qx "${cell}_t$t" && continue
13
+ bsub -G grp_runtime -q normal -gpu num=1 -n 8 -M 64G -J ${cell}_t$t -o $L/${cell}_t$t.out -e $L/${cell}_t$t.err -env "$env, TASKS=$t, PARTIALONLY=1" $IB/code/ibm_eval.sh >/dev/null 2>&1 && n=$((n+1))
14
+ done
15
+ echo "$active" | grep -qx "${cell}_asm" || bsub -G grp_runtime -q normal -n 4 -M 32G -J ${cell}_asm -o $L/${cell}_asm.out -e $L/${cell}_asm.err -env "$env, ASM=1" $IB/code/ibm_eval.sh >/dev/null 2>&1
16
+ done; echo "resubmitted $n task jobs"'
frozen/rsm_libero_freeze_20261002/ibm_table.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assemble the RSM-vs-baselines table from IBM eval JSONs, with PAIRED tests.
2
+
3
+ Cells are named <arm>_<proposer>_s<pseed>[e<evalseed>]_<A|B>. Two cells with the same
4
+ proposer, pseed/evalseed and protocol share initial conditions (init_sha256 per episode),
5
+ so arm differences are paired: McNemar exact test on discordant episodes, plus the paired
6
+ throughput difference. Reports every arm against `plain` (BC single action) and against
7
+ `medoid8` (the value-free selector) on the same cell.
8
+ """
9
+ import argparse, glob, json, os, re, sys
10
+ from collections import defaultdict
11
+ from math import comb
12
+
13
+ def mcnemar(b, c):
14
+ n = b + c
15
+ if n == 0: return 1.0
16
+ k = min(b, c); p = sum(comb(n, i) for i in range(0, k + 1)) / 2 ** n
17
+ return min(1.0, 2 * p)
18
+
19
+ def load(d):
20
+ cells = {}
21
+ for f in glob.glob(f"{d}/*.json"):
22
+ n = os.path.basename(f)[:-5]
23
+ m = re.match(r"(.+)_(D|S|DL|R|RL|DC)_s(\d)(?:e(\d))?_(A|B|V)$", n)
24
+ if not m: continue
25
+ arm, prop, ps, es, P = m.groups(); es = es or "0"
26
+ j = json.load(open(f))
27
+ eps = {}
28
+ for t, lst in j["episodes_detail"].items():
29
+ for e in lst: eps[(t, e["episode"], e["init_sha256"])] = (bool(e["success"]), int(e["steps"]))
30
+ cells[(arm, prop, ps, es, P)] = dict(sr=j["pooled_SR"], thr=j["throughput_all"], n=j["episodes"], eps=eps)
31
+ return cells
32
+
33
+ def pair(a, b):
34
+ keys = set(a["eps"]) & set(b["eps"])
35
+ if not keys: return None
36
+ sa = [a["eps"][k][0] for k in keys]; sb = [b["eps"][k][0] for k in keys]
37
+ B = sum(1 for x, y in zip(sa, sb) if x and not y); C = sum(1 for x, y in zip(sa, sb) if y and not x)
38
+ ta = [520 * a["eps"][k][0] / a["eps"][k][1] for k in keys]; tb = [520 * b["eps"][k][0] / b["eps"][k][1] for k in keys]
39
+ return dict(n=len(keys), dsr=(sum(sa) - sum(sb)) / len(keys), b=B, c=C, p=mcnemar(B, C),
40
+ dthr=(sum(ta) - sum(tb)) / len(keys))
41
+
42
+ def main():
43
+ ap = argparse.ArgumentParser(); ap.add_argument("--dir", required=True); ap.add_argument("--prop", default="D")
44
+ a = ap.parse_args(); cells = load(a.dir)
45
+ arms = sorted({k[0] for k in cells if k[1] == a.prop})
46
+ print(f"proposer={a.prop} cells: {sum(1 for k in cells if k[1]==a.prop)}\n")
47
+ print(f"{'arm':<14} {'seed':>6} {'P':>2} {'SR':>6} {'thr':>6} | {'vs plain dSR':>12} {'p':>7} {'dthr':>7} | {'vs medoid dSR':>13} {'p':>7} {'dthr':>7}")
48
+ for arm in arms:
49
+ for (ar, pr, ps, es, P), c in sorted(cells.items()):
50
+ if ar != arm or pr != a.prop: continue
51
+ row = f"{arm:<14} {ps+'/'+es:>6} {P:>2} {c['sr']:6.3f} {c['thr']:6.3f} |"
52
+ for base in ("plain", "medoid8"):
53
+ bc = cells.get((base, pr, ps, es, P))
54
+ if bc is None or base == arm: row += f" {'':>12} {'':>7} {'':>7} |"; continue
55
+ r = pair(c, bc); row += f" {r['dsr']:+12.3f} {r['p']:7.3f} {r['dthr']:+7.3f} |" if r else f" {'no overlap':>28} |"
56
+ print(row)
57
+ # pooled across seeds for the headline arms
58
+ print("\npooled over available (seed, protocol) pairs, arm minus baseline:")
59
+ for arm in arms:
60
+ for base in ("plain", "medoid8"):
61
+ if arm == base: continue
62
+ B = C = n = 0; dth = 0.0
63
+ for (ar, pr, ps, es, P), c in cells.items():
64
+ if ar != arm or pr != a.prop: continue
65
+ bc = cells.get((base, pr, ps, es, P)); r = pair(c, bc) if bc else None
66
+ if r: B += r["b"]; C += r["c"]; n += r["n"]; dth += r["dthr"] * r["n"]
67
+ if n: print(f" {arm:<14} vs {base:<8} n={n:5d} dSR={(B-C)/n:+.3f} McNemar p={mcnemar(B,C):.4f} dthr={dth/n:+.3f}")
68
+
69
+ if __name__ == "__main__":
70
+ main()
frozen/rsm_libero_freeze_20261002/ibm_train_onpol.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Retrain the RSM critic with the on-policy pack mixed into training batches.
3
+ # env: MIX2 (fraction from cache2, default 0.5), OUT (run dir), STEPS (default 300000)
4
+ set -uo pipefail
5
+ IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256
6
+ PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python
7
+ export PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1
8
+ export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/"
9
+ cd $IB/code
10
+ $PY train_rsm.py --cache $IB/cache/full_r256 --subgoal-dir $R/subgoals_full --reward-mode subgoal \
11
+ --cache2 $IB/cache/onpol_r256 --subgoal-dir2 $R/subgoals_onpol --mix2 "${MIX2:-0.5}" \
12
+ --reward-loss bce --append-proprio 1 --d-z 256 --enc-width 1024 --flow-width 1024 --flow-depth 4 \
13
+ --beta-lo 0.93 --beta-hi 0.995 --beta-q 0.98 --w-actcon 0.5 --batch 512 --lr 3e-4 --ema 0.995 \
14
+ --steps "${STEPS:-300000}" --save-every 20000 --eval-every 10000 --in-ram 1 --seed "${SEED:-0}" \
15
+ --out "${OUT:?}"
frozen/rsm_libero_freeze_20261002/iql.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """IQL critic + policy extraction, as the standard offline-RL baseline for RSM.
2
+
3
+ Matched to the RSM arms on purpose: same latents, same reward labels, same
4
+ FlowPolicy class, same AWR extraction, same offline score. The ONLY thing that
5
+ differs is where the advantage comes from -- IQL's expectile-regressed Q - V
6
+ versus RSM's occupancy read-out. That is what makes the comparison a test of the
7
+ critic rather than of the pipeline around it.
8
+
9
+ IQL (Kostrikov et al., ICLR 2022):
10
+ L_V = E[ expectile_tau( Q_target(z,a) - V(z) ) ]
11
+ L_Q = E[ ( r + gamma * V(z') - Q(z,a) )^2 ]
12
+ advantage = Q(z,a) - V(z)
13
+ Reward is the same DENSE P(success|z) label the RSM critic reads, so neither method
14
+ gets a reward the other does not see.
15
+ """
16
+ from __future__ import annotations
17
+ import sys as _sys, os as _os
18
+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
19
+ import argparse, json
20
+ from pathlib import Path
21
+ import numpy as np
22
+ import torch
23
+ import torch.nn.functional as F
24
+
25
+ from model import Encoder, mlp, FlowPolicy
26
+ from data import LiberoRSMData
27
+ from is_ope import make_policy, policy_nll, train_bc, policy_features
28
+ from train_rsm import auc
29
+
30
+
31
+ class QNet(torch.nn.Module):
32
+ def __init__(self, d_z, d_act, n_task, d_task=64, width=512, depth=3):
33
+ super().__init__()
34
+ self.task = torch.nn.Embedding(n_task, d_task)
35
+ self.net = mlp([d_z + d_act + d_task] + [width] * depth + [1], norm=True)
36
+
37
+ def load_state_dict(self, sd, strict=True):
38
+ # Self-describing checkpoints: rebuild the MLP to the saved width/depth if the
39
+ # caller constructed the default size (evaluator constructs QNet(d_z, d_act, n_task)
40
+ # and is edited by more than one session; the checkpoint is the source of truth).
41
+ lin = sorted((int(k.split(".")[1]), sd[k]) for k in sd
42
+ if k.startswith("net.") and k.endswith(".weight") and sd[k].dim() == 2)
43
+ if lin:
44
+ d_in = int(lin[0][1].shape[1]); sizes = [d_in] + [int(w.shape[0]) for _, w in lin]
45
+ mine = [m for m in self.net if isinstance(m, torch.nn.Linear)]
46
+ if [d_in] + [m.out_features for m in mine] != sizes:
47
+ self.net = mlp(sizes, norm=True).to(lin[0][1].device)
48
+ return super().load_state_dict(sd, strict=strict)
49
+
50
+ def forward(self, z, a, task):
51
+ return self.net(torch.cat([z, a, self.task(task)], -1)).squeeze(-1)
52
+
53
+
54
+ class VNet(torch.nn.Module):
55
+ def __init__(self, d_z, n_task, d_task=64, width=512, depth=3):
56
+ super().__init__()
57
+ self.task = torch.nn.Embedding(n_task, d_task)
58
+ self.net = mlp([d_z + d_task] + [width] * depth + [1], norm=True)
59
+
60
+ def forward(self, z, task):
61
+ return self.net(torch.cat([z, self.task(task)], -1)).squeeze(-1)
62
+
63
+
64
+ def expectile_loss(diff, tau):
65
+ return torch.where(diff > 0, tau, 1 - tau) * diff.pow(2)
66
+
67
+
68
+ def train_iql(d, enc, args, device, steps):
69
+ """Expectile V + TD Q on the frozen reward-predictive latent."""
70
+ d_act = d.chunk * d.adim
71
+ q = QNet(args.d_z, d_act, d.n_task).to(device)
72
+ q_t = QNet(args.d_z, d_act, d.n_task).to(device)
73
+ q_t.load_state_dict(q.state_dict())
74
+ for p in q_t.parameters():
75
+ p.requires_grad_(False)
76
+ v = VNet(args.d_z, d.n_task).to(device)
77
+ opt = torch.optim.AdamW(list(q.parameters()) + list(v.parameters()),
78
+ lr=3e-4, weight_decay=0.01)
79
+ rng = np.random.default_rng(args.seed + 3)
80
+ for step in range(1, steps + 1):
81
+ b = d.sample_frames(args.batch, rng, "train", device)
82
+ # next state: one action-chunk ahead, clamped to the episode end
83
+ t_next = np.minimum(b["t_idx"] + d.chunk, d.ep_to[b["ep"]] - 1)
84
+ with torch.no_grad():
85
+ z = enc(b["x"])
86
+ xn = torch.from_numpy(d._feat(t_next)).to(device)
87
+ zn = enc(xn)
88
+ r = torch.from_numpy(d.r[t_next]).to(device)
89
+ done = torch.from_numpy(
90
+ (t_next >= d.ep_to[b["ep"]] - 1).astype(np.float32)).to(device)
91
+ qt = q_t(z, b["a"], b["task"])
92
+ vv = v(z, b["task"])
93
+ l_v = expectile_loss(qt - vv, args.tau).mean()
94
+ with torch.no_grad():
95
+ vn = v(zn, b["task"])
96
+ target = r + args.gamma * (1 - done) * vn
97
+ l_q = (q(z, b["a"], b["task"]) - target).pow(2).mean()
98
+ loss = l_v + l_q
99
+ opt.zero_grad(); loss.backward()
100
+ torch.nn.utils.clip_grad_norm_(list(q.parameters()) + list(v.parameters()), 1.0)
101
+ opt.step()
102
+ with torch.no_grad():
103
+ for pt, po in zip(q_t.parameters(), q.parameters()):
104
+ pt.mul_(0.995).add_(po.detach(), alpha=0.005)
105
+ if step % 1000 == 0:
106
+ with torch.no_grad():
107
+ adv = (q(z, b["a"], b["task"]) - vv)
108
+ print(f"[iql] {step} l_v={float(l_v):.4f} l_q={float(l_q):.4f} "
109
+ f"|adv|={float(adv.abs().mean()):.4f}", flush=True)
110
+ q.eval(); v.eval()
111
+ return q, v
112
+
113
+
114
+ def main():
115
+ ap = argparse.ArgumentParser()
116
+ ap.add_argument("--cache", required=True)
117
+ ap.add_argument("--norm-pool", default="all", choices=["all", "demos"],
118
+ help="frames the feature statistics come from. demos is worth +0.15 closed-loop over rollout-dominated statistics.")
119
+
120
+ ap.add_argument("--adv-norm", default="std", choices=["std", "none"],
121
+ help="standardise the advantage inside the AWR weight. "
122
+ "Without it beta is uninterpretable and the weight "
123
+ "collapses to a hard sign filter.")
124
+
125
+ ap.add_argument("--init-pool", default="succ",
126
+ choices=["succ", "demos", "demos_succ", "all"],
127
+ help="episodes the pi_0 clone is fit on. Both critic arms must "
128
+ "use the SAME value or the comparison measures the initialisation rather than the critic.")
129
+
130
+ ap.add_argument("--lr", type=float, default=3e-4)
131
+
132
+ ap.add_argument("--feat-scale", default="zscore", choices=["zscore", "center"],
133
+ help="how the POLICY sees the observation. zscore matches the "
134
+ "lane BC recipe that reaches 0.584; center keeps relative "
135
+ "dim importance. Ranked on held-out sampled action MSE, "
136
+ "never on the CFM loss.")
137
+
138
+ ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"],
139
+ help="what the POLICY reads: raw = full observation (BC-baseline "
140
+ "parity), latent = critic bottleneck. Advantage always "
141
+ "comes from the critic latent.")
142
+
143
+ ap.add_argument("--critic", required=True,
144
+ help="RSM checkpoint -- used ONLY for its frozen encoder, so "
145
+ "IQL and RSM read the same latent")
146
+ ap.add_argument("--out", required=True)
147
+ ap.add_argument("--chunk", type=int, default=25)
148
+ ap.add_argument("--tau", type=float, default=0.7, help="IQL expectile")
149
+ ap.add_argument("--gamma", type=float, default=0.99)
150
+ ap.add_argument("--awr-beta", type=float, default=1.0)
151
+ ap.add_argument("--w-max", type=float, default=20.0)
152
+ ap.add_argument("--iql-steps", type=int, default=12000)
153
+ ap.add_argument("--bc-steps", type=int, default=3000)
154
+ ap.add_argument("--awr-steps", type=int, default=1500)
155
+ ap.add_argument("--rounds", type=int, default=2)
156
+ ap.add_argument("--batch", type=int, default=256)
157
+ ap.add_argument("--awr-pool", default="succ",
158
+ choices=["all", "succ", "demos"],
159
+ help="episodes AWR regresses on. succ draws from the noisy\n pi0.5 rollouts (SDE noise 0.5); demos keeps the policy\n inside the distribution it was cloned on, so the advantage\n can only re-weight demonstrations rather than drag the\n policy toward a noisier behaviour.")
160
+ ap.add_argument("--policy-family", default="concat", choices=["concat", "flow", "gauss"])
161
+ ap.add_argument("--in-ram", type=int, default=0)
162
+ ap.add_argument("--success-gamma", type=float, default=0.98,
163
+ help="discount for reward-mode=soft: the label is "
164
+ "success_gamma ** (frames until success)")
165
+ ap.add_argument("--subgoal-dir", default="", help="per-frame satisfied-conjunct labels (reward-mode subgoal*)")
166
+ ap.add_argument("--success-mask", default="", help="admissibility mask npz (keep); drops non-reproducing successes")
167
+ ap.add_argument("--q-only", type=int, default=0,
168
+ help="train IQL Q/V, save them as iql_q.pt for best-of-N ranking in the evaluator, and stop. "
169
+ "No BC clone, no AWR: the extraction is then IDENTICAL to the RSM arm except for where Q comes from.")
170
+ ap.add_argument("--reward-mode", default="dense", choices=["dense","terminal","soft","subgoal","subgoal_ind"],
171
+ help="dense = P(task succeeds|z), every frame of a success is a "
172
+ "positive (~50%%). terminal = last k frames only (~0.5%%), which "
173
+ "leaves Q near-constant in the action.")
174
+ ap.add_argument("--seed", type=int, default=0)
175
+ args = ap.parse_args()
176
+
177
+ torch.manual_seed(args.seed)
178
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
179
+ d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed,
180
+ in_ram=bool(args.in_ram), reward_mode=args.reward_mode,
181
+ success_gamma=getattr(args, 'success_gamma', 0.98),
182
+ norm_pool=args.norm_pool, subgoal_dir=args.subgoal_dir,
183
+ success_mask=args.success_mask)
184
+ from is_ope import load_critic
185
+ enc, _rew, _flow, _rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task,
186
+ dev, data=d)
187
+ args.d_z = cfg["d_z"]
188
+ pfeat, d_pol = policy_features(args, enc, d, cfg, dev)
189
+ Path(args.out).mkdir(parents=True, exist_ok=True)
190
+ print(f"[iql] {d.n_ep} eps, chunk={d.chunk}, d_z={args.d_z}, tau={args.tau}",
191
+ flush=True)
192
+
193
+ q, v = train_iql(d, enc, args, dev, args.iql_steps)
194
+ torch.save({"iql_q": True, "cam_res": getattr(d, "cam_res", "UNKNOWN"),
195
+ "q": q.state_dict(), "v": v.state_dict(), "config": vars(args),
196
+ "d_act": d.chunk * d.adim, "d_z": args.d_z, "n_task": d.n_task,
197
+ "critic": args.critic}, Path(args.out) / "iql_q.pt")
198
+ print(f"[iql] saved Q/V -> {Path(args.out) / 'iql_q.pt'}", flush=True)
199
+ if args.q_only:
200
+ print("[iql] DONE (q-only)", flush=True); return
201
+
202
+ from awr import offline_score
203
+ rng = np.random.default_rng(args.seed + 23)
204
+ pol = train_bc(d, enc, args, dev, only_success=args.init_pool, steps=args.bc_steps,
205
+ pfeat=pfeat, d_policy=d_pol,
206
+ resume_path=str(Path(args.out) / 'bc_resume.pt'))
207
+ log = {"config": vars(args),
208
+ "pi_0": offline_score(d, enc, pol, rng, dev, pfeat=pfeat), "rounds": []}
209
+ print(f"[iql] pi_0 {log['pi_0']}", flush=True)
210
+
211
+ for r in range(1, args.rounds + 1):
212
+ new = make_policy(args, d, dev, d_z=d_pol)
213
+ new.load_state_dict(pol.state_dict())
214
+ opt = torch.optim.AdamW(new.parameters(), lr=1e-4, weight_decay=0.01)
215
+ rg = np.random.default_rng(args.seed + 11 + r)
216
+ stats = []
217
+ for step in range(1, args.awr_steps + 1):
218
+ b = d.sample_frames(args.batch, rg, "train", dev)
219
+ if args.awr_pool != "all":
220
+ keep = ((b["succ"] > 0.5) if args.awr_pool == "succ"
221
+ else (b["demo"] > 0.5))
222
+ if keep.sum() < 8:
223
+ continue
224
+ km = keep.cpu().numpy()
225
+ b = {k: (v_[km] if isinstance(v_, np.ndarray)
226
+ else (v_[keep] if torch.is_tensor(v_) else v_))
227
+ for k, v_ in b.items()}
228
+ with torch.no_grad():
229
+ z = enc(b["x"]) # critic latent -> advantage
230
+ zp = pfeat(b["x"]) # policy features -> action head
231
+ adv = q(z, b["a"], b["task"]) - v(z, b["task"])
232
+ # See awr.awr_step: the raw advantage saturates the exponent and
233
+ # turns AWR into a hard sign filter on a critic whose action win
234
+ # rate is 0.568.
235
+ if args.adv_norm == "std":
236
+ adv = (adv - adv.mean()) / adv.std().clamp_min(1e-6)
237
+ w = (args.awr_beta * adv).exp().clamp(0, args.w_max)
238
+ w = w / w.mean().clamp_min(1e-6)
239
+ loss = (w * policy_nll(new, zp, b["task"], b["a"], reduce=False)).mean()
240
+ opt.zero_grad(); loss.backward()
241
+ torch.nn.utils.clip_grad_norm_(new.parameters(), 1.0); opt.step()
242
+ if step % 500 == 0:
243
+ stats.append({"step": step, "loss": float(loss),
244
+ "mean_abs_adv": float(adv.abs().mean())})
245
+ print(f"[iql-awr] r{r} {step} loss={float(loss):.3f} "
246
+ f"|adv|={float(adv.abs().mean()):.4f}", flush=True)
247
+ new.eval(); pol = new
248
+ sc = offline_score(d, enc, pol, rng, dev, pfeat=pfeat)
249
+ log["rounds"].append({"round": r, "awr": stats, "score": sc})
250
+ print(f"[iql] round {r} {sc}", flush=True)
251
+ out = Path(args.out); out.mkdir(parents=True, exist_ok=True)
252
+ torch.save({"pol": pol.state_dict(), "round": r, "config": vars(args)},
253
+ out / f"policy_r{r}.pt")
254
+ (out / "loop.json").write_text(json.dumps(log, indent=2))
255
+ print("[iql] DONE", flush=True)
256
+
257
+
258
+ if __name__ == "__main__":
259
+ main()
frozen/rsm_libero_freeze_20261002/is_ope.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Importance-sampled off-policy evaluation of Q^pi with the RSM occupancy.
2
+
3
+ Implements the notes' Sections 7-9 without ever needing a normalized action
4
+ density, which matters because the behavior policy here is a pi0.5 flow model
5
+ sampled as an SDE at noise 0.5 and has no tractable likelihood.
6
+
7
+ Step 1 per-decision ratio by CLASSIFICATION. Train c(z, A) to separate a
8
+ logged chunk (label 0, from mu) from a chunk sampled from pi at the
9
+ SAME logged state (label 1). On balanced classes the logit is exactly
10
+ log pi/mu, so `w_j = exp(logit)` replaces pi(a_j|s_j)/mu(a_j|s_j).
11
+
12
+ Step 2 chunk product. A beta-hop spans several 10-step decisions; the first
13
+ is conditioned on, so W = prod over the INTERIOR decisions only. With
14
+ a 10-action chunk a 50-frame hop carries ~5 factors instead of 50,
15
+ which is the variance argument for doing the correction per hop rather
16
+ than over a flat trajectory.
17
+
18
+ Step 3 Rao-Blackwellize onto the endpoint. Regress W onto (z, A, z') under
19
+ squared loss; the minimizer is E[W | endpoint] = d^pi_beta / d^mu_beta.
20
+ This is the only form usable at inference, because the occupancy model
21
+ emits an endpoint and never the intervening actions.
22
+
23
+ Step 4 recursive read. Q^pi = E[ C * r(z_end) ] / (1-gamma) with C the
24
+ product of endpoint weights along the hops, self-normalized. Boundary
25
+ actions are drawn from pi, so only chunk interiors need correcting.
26
+
27
+ VALIDATION (the gate, and it can fail): a synthetic target policy whose
28
+ occupancy we can compute directly. Take pi := "mu restricted to episodes that
29
+ succeed". d^pi is then estimable by fitting the occupancy on successes only,
30
+ while the IS estimate reweights the all-data model. If the corrected estimate
31
+ does not move toward the success-only reference, the weights are not working and
32
+ no policy is trained on them.
33
+ """
34
+ from __future__ import annotations
35
+ import sys as _sys, os as _os
36
+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
37
+ import argparse, json, time
38
+ from pathlib import Path
39
+ import numpy as np
40
+ import torch
41
+ import torch.nn.functional as F
42
+
43
+ from types import SimpleNamespace
44
+
45
+ from model import (Encoder, RewardHead, OccFlow, RatioNet, EndpointRatio,
46
+ BCHead, FlowPolicy)
47
+ from data import LiberoRSMData
48
+ from train_rsm import sample_future, auc
49
+
50
+
51
+ class _LatWithProprio(torch.nn.Module):
52
+ """Encoder wrapper that re-appends the proprio channel to the latent.
53
+
54
+ Training may append n_pr normalised proprio dims to the 256-d latent so the
55
+ successor has to PREDICT an action-sensitive channel (action-proprio |r| 0.98
56
+ vs action-latent 0.49). The checkpoint therefore carries a d_z+n_pr latent,
57
+ and rebuilding the heads at d_z alone fails with a size mismatch.
58
+ """
59
+
60
+ def __init__(self, enc, n_pr, mu, sd):
61
+ super().__init__()
62
+ self.enc = enc; self.n_pr = n_pr
63
+ self.register_buffer("mu", mu); self.register_buffer("sd", sd)
64
+
65
+ def forward(self, x):
66
+ z = self.enc(x)
67
+ if not self.n_pr:
68
+ return z
69
+ return torch.cat([z, (x[:, -self.n_pr:] - self.mu) / self.sd], -1)
70
+
71
+ def back(self, z):
72
+ """PCA checkpoints only: latent -> full state (n_pr == 0 there)."""
73
+ return self.enc.back(z)
74
+
75
+
76
+ def load_critic(path, d_in, n_task, device, data=None):
77
+ ck = torch.load(path, map_location=device, weights_only=False)
78
+ c = ck["config"]
79
+ n_pr = int(ck.get("n_pr", 0) or 0)
80
+ enc_kind = ck.get("enc_kind", c.get("enc", "mlp")) or "mlp"
81
+ if enc_kind == "identity":
82
+ # train_rsm.py --enc identity: the z-scored feature is the latent (d_z == feature dim).
83
+ # The blob's d_in records the feature width the run saw; a cache of another width
84
+ # would silently mis-size every head, so refuse it here.
85
+ d_ck = int(ck.get("d_in", c["d_z"]))
86
+ if int(d_in) != d_ck:
87
+ raise RuntimeError(f"identity-encoder checkpoint was trained on {d_ck}-d features, "
88
+ f"cache provides {d_in}-d")
89
+ from model import IdentityEncoder
90
+ base = IdentityEncoder(d_in).to(device)
91
+ d_lat = d_in + n_pr
92
+ elif enc_kind == "pca":
93
+ d_ck = int(ck.get("d_in", d_in))
94
+ if int(d_in) != d_ck:
95
+ raise RuntimeError(f"PCA checkpoint was fitted on {d_ck}-d features, cache provides {d_in}-d")
96
+ from model import PCAEncoder
97
+ base = PCAEncoder(d_in, int(c["pca_dim"])).to(device)
98
+ base.load_state_dict(ck["enc"]) # mean + W buffers
99
+ d_lat = int(c["pca_dim"]) + n_pr
100
+ else:
101
+ d_lat = c["d_z"] + n_pr
102
+ base = Encoder(d_in, c["d_z"], c["enc_width"]).to(device)
103
+ base.load_state_dict(ck["enc"])
104
+ if n_pr:
105
+ if data is None or data.proprio is None:
106
+ raise RuntimeError(f"checkpoint appends {n_pr} proprio dims; pass data=")
107
+ pr = np.asarray(data.proprio[::37], np.float32)
108
+ mu = torch.tensor(pr.mean(0), device=device)
109
+ sd = torch.tensor(pr.std(0) + 1e-6, device=device)
110
+ else:
111
+ mu = sd = torch.zeros(0, device=device)
112
+ enc = _LatWithProprio(base, n_pr, mu, sd).to(device)
113
+ rew = RewardHead(d_lat, n_task).to(device)
114
+ flow = OccFlow(d_lat, ck["d_act"], n_task, width=c["flow_width"],
115
+ depth=c["flow_depth"], norm=bool(c.get("flow_norm", 0)),
116
+ dropout=float(c.get("flow_dropout", 0.0) or 0.0)).to(device)
117
+ rew.load_state_dict(ck["rew"])
118
+ flow.load_state_dict(ck["flow"])
119
+ for m in (enc, rew, flow):
120
+ m.eval()
121
+ for p in m.parameters():
122
+ p.requires_grad_(False)
123
+ c = dict(c); c["d_z"] = d_lat # downstream sizes policies by the FULL latent
124
+ c["enc_kind"] = enc_kind
125
+ return enc, rew, flow, ck["rms"].to(device), c
126
+
127
+
128
+ # --------------------------------------------------------------------------- #
129
+ # pi_0: behaviour cloning on a chosen slice of the corpus
130
+ # --------------------------------------------------------------------------- #
131
+ def make_policy(args, d, device, d_act=None, d_z=None):
132
+ """Flow by default. A Gaussian target against a flow-SDE behaviour policy let
133
+ the ratio classifier hit 100% accuracy by recognising the SAMPLER rather than
134
+ the policy: E_mu[W] came out 0.181 in BOTH the signal gate and the null gate
135
+ where the two policies were meant to be the same. Matching the family removes
136
+ that shortcut."""
137
+ fam = getattr(args, "policy_family", "concat")
138
+ da = d_act or (d.chunk * d.adim)
139
+ dz = args.d_z if d_z is None else d_z
140
+ if fam == "gauss":
141
+ return BCHead(dz, da, d.n_task).to(device)
142
+ if fam == "flow":
143
+ return FlowPolicy(dz, da, d.n_task).to(device)
144
+ from model import ConcatFlowPolicy
145
+ return ConcatFlowPolicy(dz, da, d.n_task,
146
+ width=int(getattr(args, "pol_width", 1024) or 1024),
147
+ depth=int(getattr(args, "pol_depth", 4) or 4)).to(device)
148
+
149
+
150
+ def policy_features(args, enc, d, cfg, device=None):
151
+ """(module, width) feeding the POLICY -- deliberately separate from the
152
+ critic's latent. See model.RawFeat for why raw is the default."""
153
+ from model import RawFeat
154
+ mode = getattr(args, "policy_features", "raw")
155
+ if mode != "raw":
156
+ return enc, cfg["d_z"]
157
+ scale = np.ones(d.feat_dim, np.float32)
158
+ if getattr(args, "feat_scale", "zscore") == "center" and d.norm_sd is not None:
159
+ n_pr = 0 if d.proprio is None else d.proprio.shape[1]
160
+ n_z = d.feat_dim - n_pr
161
+ sd_z = d.norm_sd[:n_z]
162
+ scale[:n_z] = sd_z / max(float(sd_z.mean()), 1e-6) # undo the whitening
163
+ rf = RawFeat(d.feat_dim, torch.from_numpy(scale))
164
+ return (rf if device is None else rf.to(device)), d.feat_dim
165
+
166
+
167
+ def policy_nll(pol, z, task, a, reduce=True):
168
+ """-log pi surrogate: exact for the Gaussian head, per-sample flow-matching
169
+ loss for the flow head (the substitution the smolvla AWR run used)."""
170
+ if hasattr(pol, "fm_loss"):
171
+ return pol.fm_loss(z, task, a, reduce=reduce)
172
+ lp = -pol.log_prob(z, task, a)
173
+ return lp.mean() if reduce else lp
174
+
175
+
176
+ @torch.no_grad()
177
+ def sampled_action_mse(pol, d, pfeat, rng, device, pool, n=2048, chunk_len=None):
178
+ """Held-out ODE-sampled reconstruction MSE -- THE flow-BC metric.
179
+
180
+ The raw conditional-flow-matching loss is a velocity residual at a random
181
+ flow time and does NOT track how good the ACTIONS the policy emits are: on
182
+ this corpus it ranked raw features best (0.158) while the closed loop said
183
+ otherwise. What the lane's own BC sweep ranks on, and what we rank on here,
184
+ is the MSE between the logged chunk and the chunk the policy actually
185
+ integrates out of noise."""
186
+ cl = chunk_len or d.chunk
187
+ eps_pool = np.array([e for e in d.val_eps if pool[e]])
188
+ if not len(eps_pool):
189
+ return float("nan")
190
+ w = d.ep_len[eps_pool].astype(np.float64); w /= w.sum()
191
+ e = rng.choice(eps_pool, size=n, p=w)
192
+ lo, hi = d.ep_from[e], d.ep_to[e]
193
+ t = lo + (rng.random(n) * (hi - lo)).astype(np.int64)
194
+ x = torch.from_numpy(d._feat(t)).to(device)
195
+ a = torch.from_numpy(d._chunk_at(t, e, chunk_len=cl)).to(device)
196
+ tk = torch.from_numpy(d.ep_task[e]).long().to(device)
197
+ out = []
198
+ for i in range(0, n, 512):
199
+ z = pfeat(x[i:i + 512])
200
+ out.append(((pol.sample(z, tk[i:i + 512]) - a[i:i + 512]) ** 2).mean(-1))
201
+ return float(torch.cat(out).mean())
202
+
203
+
204
+ # Optional W&B run for the BC loop (set by bc_arm.py when RSM_WANDB_ENTITY is set; None = off).
205
+ # Kept as a module global rather than an args attribute so that vars(args) stays JSON/torch-serialisable.
206
+ WANDB_RUN = None
207
+
208
+
209
+ def train_bc(d, enc, args, device, only_success=True, steps=8000, chunk_len=None,
210
+ pfeat=None, d_policy=None, resume_path=None):
211
+ """chunk_len=None fits the occupancy's action window. Pass the behaviour
212
+ policy's DECISION period to fit a policy directly comparable to logged
213
+ decisions: scoring the first 10 actions of a 100-action plan is not the same
214
+ distribution a 10-action policy emits, and that mismatch alone kept the ratio
215
+ classifier at 0.98 accuracy."""
216
+ cl = chunk_len or d.chunk
217
+ pf = enc if pfeat is None else pfeat
218
+ pol = make_policy(args, d, device, d_act=cl * d.adim, d_z=d_policy)
219
+ # pool selector: "succ" = successful episodes, "demos" = demonstrations only
220
+ # (the BC-on-demos baseline), None/False = everything.
221
+ # plain Adam, no weight decay: the 0.584 recipe's optimiser
222
+ opt = torch.optim.Adam(pol.parameters(), lr=getattr(args, "lr", 3e-4))
223
+ rng = np.random.default_rng(args.seed + 1)
224
+ # ONE chain. This used to be two (the rollsucc branch was added as a fresh `if`
225
+ # after the mask block), so the trailing `elif only_success:` -- true for any
226
+ # non-empty string -- silently overrode "demos" with ALL successes. BC-on-demos
227
+ # arms trained on 24,673 episodes instead of 500, and looked identical to the
228
+ # successes arm on both clusters (2026-09-14).
229
+ _mask = getattr(args, "success_mask", "") or ""
230
+ _ver = None
231
+ if _mask:
232
+ _ver = np.load(_mask)["keep"].astype(bool)
233
+ print(f"[bc] success mask: {int(_ver.sum())}/{len(_ver)} episodes verified", flush=True)
234
+ if only_success == "demos":
235
+ # a replayed demo that did not reproduce success is inadmissible (legacy demo
236
+ # caches mark every demo successful, so this is a no-op for them)
237
+ ok = d.ep_demo & d.ep_success
238
+ elif only_success == "demos_succ":
239
+ ok = d.ep_demo | d.ep_success
240
+ elif only_success == "rollsucc_mix":
241
+ _k = int(getattr(args, "demos_per_task", 5) or 0)
242
+ ok = (d.ep_success & ~d.ep_demo).copy()
243
+ _rs = np.random.default_rng(args.seed + 77)
244
+ _added = 0
245
+ for _t in range(d.n_task):
246
+ _cand = np.where(d.ep_demo & (d.ep_task == _t))[0]
247
+ if len(_cand) == 0 or _k <= 0:
248
+ continue
249
+ _pick = _rs.choice(_cand, size=min(_k, len(_cand)), replace=False)
250
+ ok[_pick] = True
251
+ _added += len(_pick)
252
+ print(f"[bc] rollsucc_mix: {int((d.ep_success & ~d.ep_demo).sum())} rollout "
253
+ f"successes + {_added} demos ({_k}/task)", flush=True)
254
+ elif only_success == "rollsucc":
255
+ ok = d.ep_success & ~d.ep_demo
256
+ elif only_success: # True / "succ": demos + successful rollouts
257
+ ok = d.ep_success.copy()
258
+ else:
259
+ ok = np.ones(d.n_ep, bool)
260
+ # Admissibility: a logged success that does not reproduce in the eval env is never
261
+ # cloned. Applied to every pool that contains rollout successes (demos are always kept).
262
+ if _ver is not None and only_success != "demos":
263
+ _before = int(ok.sum()); ok = ok & (_ver | d.ep_demo)
264
+ print(f"[bc] verified filter: {_before} -> {int(ok.sum())} episodes", flush=True)
265
+ print(f"[bc] pool={only_success!r}: {int(ok.sum())} episodes "
266
+ f"({int((ok & d.ep_demo).sum())} demos + {int((ok & ~d.ep_demo).sum())} rollouts)", flush=True)
267
+ pool = np.array([e for e in d.train_eps if ok[e]])
268
+ # Init-density ablation: cap the number of EPISODES per task. Every demo and
269
+ # every fresh-reset rollout starts from its own independent BDDL draw, so
270
+ # episodes-per-task IS distinct-initial-conditions-per-task. Holding the pool
271
+ # (hence data quality) fixed and varying this isolates coverage density from
272
+ # quality, which the demos-vs-rollouts comparison confounds.
273
+ _cap = int(getattr(args, "eps_per_task", 0) or 0)
274
+ if _cap > 0:
275
+ _keep, _seen = [], {}
276
+ _rs = np.random.default_rng(args.seed + 5150)
277
+ for _e in _rs.permutation(pool):
278
+ _t = int(d.ep_task[_e])
279
+ if _seen.get(_t, 0) < _cap:
280
+ _keep.append(_e); _seen[_t] = _seen.get(_t, 0) + 1
281
+ pool = np.array(sorted(_keep))
282
+ print(f"[bc] init-density cap: {_cap} episodes/task -> {len(pool)} episodes "
283
+ f"over {len(_seen)} tasks", flush=True)
284
+ ev_every = max(1, steps // 20)
285
+ ev_rng = np.random.default_rng(args.seed + 77)
286
+ best, best_sd, best_step = float("inf"), None, 0
287
+ # Resume support. These arms run on a preemptible queue; without it a
288
+ # preemption at step 96000 restarts from zero and the arm never finishes.
289
+ start = 0
290
+ if resume_path is not None and Path(resume_path).exists():
291
+ ck = torch.load(resume_path, map_location=device, weights_only=False)
292
+ pol.load_state_dict(ck["pol"]); opt.load_state_dict(ck["opt"])
293
+ start, best, best_step = ck["step"], ck["best"], ck["best_step"]
294
+ best_sd = ck["best_sd"]
295
+ rng = np.random.default_rng(ck["rng_seed"])
296
+ print(f"[bc] resumed at step {start} (best {best:.5f} @ {best_step})",
297
+ flush=True)
298
+ # Hard Q-filter on the TRAINING DATA (the port's `qfilter_frac`, never run here).
299
+ # Distinct from ranking (picks actions at test time) and from AWR (re-weights
300
+ # gradients): this decides which logged (s,a) pairs are cloned at all, and the
301
+ # resulting policy needs no test-time sampling -- so a value-free selector like
302
+ # medoid cannot reproduce it.
303
+ qf_frac = float(getattr(args, "qfilter_frac", 0.0) or 0.0)
304
+ qf_ctx = None
305
+ if qf_frac > 0:
306
+ _enc, _rew, _flow, _rms, _cfg = load_critic(args.critic, d.feat_dim, d.n_task,
307
+ device, data=d)
308
+ qf_ctx = (_enc, _rew, _flow, _rms)
309
+ print(f"[bc] Q-filter ON: cloning the top {qf_frac:.0%} of each "
310
+ f"oversampled batch by critic advantage", flush=True)
311
+
312
+ for step in range(start + 1, steps + 1):
313
+ nb = args.batch if qf_frac <= 0 else int(args.batch / qf_frac)
314
+ w = d.ep_len[pool].astype(np.float64)
315
+ _dw = float(getattr(args, "demo_weight", 1.0) or 1.0)
316
+ if _dw != 1.0:
317
+ w = w * np.where(d.ep_demo[pool], _dw, 1.0) # up-weight demonstrations in a mixed pool
318
+ w /= w.sum()
319
+ e = rng.choice(pool, size=nb, p=w)
320
+ lo, hi = d.ep_from[e], d.ep_to[e]
321
+ t = lo + (rng.random(nb) * (hi - lo)).astype(np.int64)
322
+ x = torch.from_numpy(d._feat(t)).to(device)
323
+ a = torch.from_numpy(d._chunk_at(t, e, chunk_len=cl)).to(device)
324
+ task = torch.from_numpy(d.ep_task[e]).long().to(device)
325
+ if qf_frac > 0:
326
+ with torch.no_grad():
327
+ _e2, _r2, _f2, _rm2 = qf_ctx
328
+ zc = _e2(x)
329
+ q, _ = q_recursive(zc, a, task, rew=_r2, flow=_f2, rms=_rm2,
330
+ pol=None, wend=None,
331
+ beta=getattr(args, "beta_q", 0.98), gamma=0.99,
332
+ depth=1, n_particles=8, use_is=False,
333
+ pessimism=0.0)
334
+ keep = torch.topk(q, args.batch).indices
335
+ x, a, task = x[keep], a[keep], task[keep]
336
+ with torch.no_grad():
337
+ z = pf(x)
338
+ loss = policy_nll(pol, z, task, a)
339
+ opt.zero_grad(); loss.backward()
340
+ torch.nn.utils.clip_grad_norm_(pol.parameters(), 1.0); opt.step()
341
+ if step % ev_every == 0 or step == steps:
342
+ pol.eval()
343
+ m = sampled_action_mse(pol, d, pf, ev_rng, device, ok, chunk_len=cl)
344
+ pol.train()
345
+ tag = ""
346
+ if m == m and m < best:
347
+ best, best_step = m, step
348
+ best_sd = {k: v.detach().clone() for k, v in pol.state_dict().items()}
349
+ tag = " <- best"
350
+ print(f"[bc] {step} cfm={float(loss):.4f} sampled_mse={m:.5f}{tag}",
351
+ flush=True)
352
+ if WANDB_RUN is not None:
353
+ try:
354
+ WANDB_RUN.log({"bc/loss": float(loss), "bc/sampled_mse": m,
355
+ "bc/best_sampled_mse": best, "bc/best_step": best_step}, step=step)
356
+ except Exception as _e: # logging must never kill a run
357
+ print(f"[bc] wandb log failed: {_e}", flush=True)
358
+ if resume_path is not None:
359
+ tmp = str(resume_path) + ".tmp"
360
+ torch.save({"pol": pol.state_dict(), "opt": opt.state_dict(),
361
+ "step": step, "best": best, "best_step": best_step,
362
+ "best_sd": best_sd, "rng_seed": args.seed + 1}, tmp)
363
+ _os.replace(tmp, resume_path) # atomic: a kill mid-write is safe
364
+ _se = int(getattr(args, "save_every", 0) or 0)
365
+ if resume_path is not None and _se and step % _se == 0:
366
+ # Periodic checkpoints so the policy can be selected by arg-max over
367
+ # checkpoints on a held-out set of VALIDATION initial conditions --
368
+ # the sampled-MSE proxy above picked a checkpoint 0.10 SR below the
369
+ # last one (BCdemo_f: 102k vs 120k), so it is not a usable selector.
370
+ torch.save({"pol": pol.state_dict(), "round": 1, "step": step,
371
+ "config": vars(args),
372
+ "cam_res": getattr(d, "cam_res", "UNKNOWN"),
373
+ "encoder": getattr(d, "encoder", "pi05_base_pytorch")},
374
+ str(Path(resume_path).parent / f"policy_s{step}.pt"))
375
+ # Keep the checkpoint that emits the best ACTIONS, not the last one.
376
+ if best_sd is not None:
377
+ pol.load_state_dict(best_sd)
378
+ print(f"[bc] restored best sampled_mse={best:.5f} from step {best_step}",
379
+ flush=True)
380
+ pol.eval()
381
+ pol.best_sampled_mse = best
382
+ return pol
383
+
384
+
385
+ # --------------------------------------------------------------------------- #
386
+ # Step 1: per-decision density ratio by classification
387
+ # --------------------------------------------------------------------------- #
388
+ class LikelihoodRatio:
389
+ """Genuine likelihood ratio pi(a|z)/mu_hat(a|z), no classifier.
390
+
391
+ The identity control killed the discriminative route: two BC policies trained
392
+ on IDENTICAL data with different seeds are 0.945-0.977 separable, the same as
393
+ target-vs-behaviour (0.941). A classifier reads WHICH NETWORK produced a
394
+ sample -- sampler artifacts, generator fingerprints -- long before it reads a
395
+ density difference, so its logit is not log pi/mu at all.
396
+
397
+ Evaluating densities AT THE LOGGED ACTION removes that channel: nothing is
398
+ asked to tell samples apart. mu has no tractable density (pi0.5 flow SDE), so
399
+ we fit `mu_hat`, a Gaussian behaviour model, by maximum likelihood on the
400
+ logged actions. Both sides are then tractable and the ratio is a real one.
401
+
402
+ Null test is exact by construction: with pi == mu_hat the ratio is identically
403
+ 1, which no classifier-based estimator could guarantee.
404
+ """
405
+
406
+ def __init__(self, pi, mu_hat, clip=1.5):
407
+ self.pi = pi; self.mu_hat = mu_hat; self.clip = clip
408
+
409
+ @torch.no_grad()
410
+ def __call__(self, z, a, task):
411
+ lr = self.pi.log_prob(z, task, a) - self.mu_hat.log_prob(z, task, a)
412
+ return lr.clamp(-self.clip, self.clip)
413
+
414
+ def eval(self):
415
+ return self
416
+
417
+ def state_dict(self):
418
+ return {"pi": self.pi.state_dict(), "mu_hat": self.mu_hat.state_dict(),
419
+ "clip": self.clip}
420
+
421
+
422
+ def train_likelihood_ratio(d, enc, args, device, steps=6000, only_success=True,
423
+ chunk_len=None):
424
+ """Fit tractable Gaussian densities for BOTH policies, then take their ratio."""
425
+ cl = chunk_len or d.chunk
426
+ ga = SimpleNamespace(d_z=args.d_z, batch=args.batch, seed=args.seed,
427
+ policy_family="gauss")
428
+ print(f"[likratio] fitting mu_hat (Gaussian behaviour model, chunk {cl})", flush=True)
429
+ mu_hat = train_bc(d, enc, ga, device, only_success=False, steps=steps,
430
+ chunk_len=cl)
431
+ gb = SimpleNamespace(d_z=args.d_z, batch=args.batch, seed=args.seed + 5,
432
+ policy_family="gauss")
433
+ print(f"[likratio] fitting pi ({'successes' if only_success else 'all data'})",
434
+ flush=True)
435
+ pi = train_bc(d, enc, gb, device, only_success=only_success, steps=steps,
436
+ chunk_len=cl)
437
+ # sanity: E_mu[pi/mu_hat] over LOGGED actions must be ~1
438
+ rng = np.random.default_rng(args.seed + 41)
439
+ acc = []
440
+ with torch.no_grad():
441
+ for _ in range(8):
442
+ b = d.sample_frames(1024, rng, "val", device)
443
+ z = enc(b["x"])
444
+ a = torch.from_numpy(
445
+ d._chunk_at(b["t_idx"], b["ep"], chunk_len=cl)).to(device)
446
+ lr = (pi.log_prob(z, b["task"], a)
447
+ - mu_hat.log_prob(z, b["task"], a)).clamp(-1.5, 1.5)
448
+ acc.append(lr.exp())
449
+ w = torch.cat(acc)
450
+ print(f"[likratio] E_mu[w] = {float(w.mean()):.4f} (target 1.0) "
451
+ f"median {float(w.median()):.4f} ESS "
452
+ f"{float((w.sum()**2)/(w.pow(2).sum()*len(w))):.3f} "
453
+ f"p95 {float(w.quantile(0.95)):.3f}", flush=True)
454
+ return LikelihoodRatio(pi, mu_hat), pi
455
+
456
+
457
+ def train_ratio(d, enc, pol, args, device, steps=6000):
458
+ """Density-ratio classifier, optionally on SMOOTHED chunks.
459
+
460
+ Measured: with a Gaussian target vs the flow-SDE behaviour policy the
461
+ classifier hit acc 0.999 (bce 0.0035) -- it was recognising the sampler.
462
+ Matching the family (FlowPolicy) dropped it to acc 0.98 (bce 0.076), a 20x
463
+ drop in confidence, but the two are still near-separable because the logged
464
+ data was collected with SDE noise 0.5 while the target policy samples an ODE.
465
+
466
+ `ratio_smooth` adds the SAME Gaussian kernel to both classes before the
467
+ classifier. That estimates the ratio of the SMOOTHED densities, which is
468
+ well-defined by construction and trades a controlled bias for overlap. A
469
+ ratio between two near-disjoint distributions is not estimable at all, so a
470
+ blurred but finite ratio is the more useful object.
471
+ """
472
+ rc = int(getattr(args, "ratio_chunk", 0) or d.chunk)
473
+ net = RatioNet(args.d_z, rc * d.adim, d.n_task).to(device)
474
+ opt = torch.optim.AdamW(net.parameters(), lr=3e-4, weight_decay=0.01)
475
+ rng = np.random.default_rng(args.seed + 2)
476
+ sm = float(getattr(args, "ratio_smooth", 0.0))
477
+ # Per-dimension kernel: the 7 action dims span std 0.031 to 0.975 (the
478
+ # gripper is near-binary), so one scalar sigma would erase the fine dims
479
+ # while barely touching the gripper. sigma_i = smooth * std_i.
480
+ a_scale = None
481
+ if sm > 0:
482
+ _b = d.sample_frames(4096, np.random.default_rng(args.seed + 99),
483
+ "train", device)
484
+ _am = torch.from_numpy(
485
+ d._chunk_at(_b["t_idx"], _b["ep"], chunk_len=rc)).to(device)
486
+ a_scale = _am.std(0).clamp_min(1e-3) * sm
487
+ print(f"[ratio] per-dim smoothing on, mean sigma "
488
+ f"{float(a_scale.mean()):.4f}", flush=True)
489
+ for step in range(1, steps + 1):
490
+ b = d.sample_frames(args.batch, rng, "train", device)
491
+ with torch.no_grad():
492
+ z = enc(b["x"])
493
+ a_pi = pol.sample(z, b["task"])
494
+ if a_pi.shape[-1] != rc * d.adim:
495
+ a_pi = a_pi[:, :rc * d.adim]
496
+ a_mu = torch.from_numpy(
497
+ d._chunk_at(b["t_idx"], b["ep"], chunk_len=rc)).to(device)
498
+ if sm > 0:
499
+ a_mu = a_mu + a_scale * torch.randn_like(a_mu)
500
+ a_pi = a_pi + a_scale * torch.randn_like(a_pi)
501
+ logit_mu = net(z, a_mu, b["task"]) # logged -> label 0
502
+ logit_pi = net(z, a_pi, b["task"]) # from pi -> label 1
503
+ loss = (F.binary_cross_entropy_with_logits(logit_mu, torch.zeros_like(logit_mu))
504
+ + F.binary_cross_entropy_with_logits(logit_pi, torch.ones_like(logit_pi)))
505
+ opt.zero_grad(); loss.backward()
506
+ torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0); opt.step()
507
+ if step % 1000 == 0:
508
+ with torch.no_grad():
509
+ acc = ((logit_pi > 0).float().mean() + (logit_mu < 0).float().mean()) / 2
510
+ print(f"[ratio] {step} bce={float(loss):.4f} acc={float(acc):.3f}", flush=True)
511
+ net.eval()
512
+ return net
513
+
514
+
515
+ # --------------------------------------------------------------------------- #
516
+ # Step 2+3: chunk product -> endpoint weight
517
+ # --------------------------------------------------------------------------- #
518
+ @torch.no_grad()
519
+ def precompute_decision_logratio(d, enc, ratio, device, batch=4096, rc=None):
520
+ """One pass over the cache -> per-frame log pi/mu at DECISION points, plus a
521
+ per-episode prefix sum.
522
+
523
+ The logged policy re-decided every `chunk` frames, so the only frames that
524
+ carry a ratio factor are ep_from + chunk*j. Prefix-summing them turns the
525
+ chunk product of Section 7 into an O(1) lookup per sample, instead of one
526
+ network call per interior decision (16x fewer forwards per training step).
527
+ """
528
+ N = int(d.ep_to[-1])
529
+ rc = rc or d.chunk
530
+ lr = np.zeros(N, np.float32)
531
+ dec = np.zeros(N, bool)
532
+ for i in range(d.n_ep):
533
+ lo, hi = int(d.ep_from[i]), int(d.ep_to[i])
534
+ dec[np.arange(lo, hi, rc)] = True
535
+ idx = np.nonzero(dec)[0]
536
+ ep_of = np.searchsorted(d.ep_to, idx, side="right")
537
+ for s in range(0, len(idx), batch):
538
+ sl = idx[s:s + batch]
539
+ x = torch.from_numpy(d._feat(sl)).to(device)
540
+ a = torch.from_numpy(
541
+ d._chunk_at(sl, ep_of[s:s + batch], chunk_len=rc)).to(device)
542
+ tk = torch.from_numpy(d.ep_task[ep_of[s:s + batch]]).long().to(device)
543
+ lr[sl] = ratio(enc(x), a, tk).float().cpu().numpy() # log pi/mu
544
+ pre = np.zeros(N + 1, np.float64)
545
+ np.cumsum(lr, out=pre[1:])
546
+ # restart the prefix at every episode boundary so no product spans episodes
547
+ for i in range(d.n_ep):
548
+ lo = int(d.ep_from[i])
549
+ pre[lo + 1:int(d.ep_to[i]) + 1] -= pre[lo]
550
+ return pre
551
+
552
+
553
+ def chunk_logW_fast(pre, t_idx, fut_idx):
554
+ """log W over decisions strictly inside (t, fut). The decision AT t is the
555
+ conditioned-on action a_t and is excluded, matching w_{t,k} in the notes."""
556
+ lo = np.minimum(t_idx + 1, fut_idx)
557
+ return (pre[fut_idx] - pre[lo]).astype(np.float32)
558
+
559
+
560
+ def train_endpoint_ratio(d, enc, ratio, args, device, steps=6000, logw_clip=4.0):
561
+ """Squared-loss regression of W onto (z, A, z'): the minimizer is E[W|endpoint]."""
562
+ rc = int(getattr(args, "ratio_chunk", 0) or d.chunk)
563
+ pre = precompute_decision_logratio(d, enc, ratio, device, rc=rc)
564
+ # Sized by the OCCUPANCY chunk: w*(z, A, z') conditions on the action the
565
+ # successor was conditioned on. Only the per-decision classifier uses rc.
566
+ net = EndpointRatio(args.d_z, d.chunk * d.adim, d.n_task).to(device)
567
+ opt = torch.optim.AdamW(net.parameters(), lr=3e-4, weight_decay=0.01)
568
+ rng = np.random.default_rng(args.seed + 3)
569
+ for step in range(1, steps + 1):
570
+ b = d.sample(args.batch, rng, args.beta_q, args.beta_q, "train", device)
571
+ logW = torch.from_numpy(
572
+ chunk_logW_fast(pre, b["t_idx"], b["fut_idx"])).to(device)
573
+ W = logW.clamp(-logw_clip, logw_clip).exp()
574
+ with torch.no_grad():
575
+ z = enc(b["x_now"]); zf = enc(b["x_fut"])
576
+ pred = net(z, b["a_now"], zf, b["task"])
577
+ loss = (pred - W).pow(2).mean()
578
+ opt.zero_grad(); loss.backward()
579
+ torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0); opt.step()
580
+ if step % 1000 == 0:
581
+ print(f"[wend] {step} mse={float(loss):.4f} "
582
+ f"E_mu[W]={float(W.mean()):.3f} E_mu[what]={float(pred.mean()):.3f}",
583
+ flush=True)
584
+ net.eval()
585
+ # Global calibration: E_mu[w] must be 1 for a correct density ratio. Rescale
586
+ # on held-out data and RECORD the factor -- a factor far from 1 means the
587
+ # ratio is mis-fit, and that is a finding, not something to silently absorb.
588
+ with torch.no_grad():
589
+ acc = []
590
+ for _ in range(8):
591
+ b = d.sample(1024, rng, args.beta_q, args.beta_q, "val", device)
592
+ z = enc(b["x_now"]); zf = enc(b["x_fut"])
593
+ acc.append(net(z, b["a_now"], zf, b["task"]))
594
+ m = float(torch.cat(acc).mean())
595
+ net.calib = 1.0 / max(m, 1e-3)
596
+ print(f"[wend] calibration E_mu[w]={m:.3f} -> scale x{net.calib:.3f}", flush=True)
597
+ return net
598
+
599
+
600
+ # --------------------------------------------------------------------------- #
601
+ # Step 4: recursive, importance-corrected Q
602
+ # --------------------------------------------------------------------------- #
603
+ @torch.no_grad()
604
+ def q_recursive(enc_z, a_chunk, task, *, rew, flow, rms, pol, wend, beta, gamma,
605
+ depth=2, n_particles=16, flow_steps=8, self_norm=True,
606
+ use_is=True, logw_clip=4.0, pessimism=0.0, crn=False):
607
+ """Q^pi(z,A) by composing beta-hops. Boundary actions come from pi, so only
608
+ chunk interiors carry a weight. depth is small on purpose (2-3).
609
+
610
+ crn=True: common random numbers across the B rows (candidates). Particle i of
611
+ every candidate uses the same flow noise, the same restart coin and the same hop-
612
+ policy noise, so Q differences between candidates are paired and the Monte-Carlo
613
+ error cancels in the arg-max (the OCBench recipe scores all N candidates on one
614
+ shared z0 for exactly this reason). With independent draws, near-identical
615
+ candidates are ranked by noise."""
616
+ dev = enc_z.device
617
+ B = enc_z.shape[0]
618
+ D = enc_z.shape[1]
619
+ def _tile(t): # [n_particles, ...] -> [B*n_particles, ...] matching repeat_interleave
620
+ return t.repeat(B, *([1] * (t.dim() - 1)))
621
+ p = (gamma - beta) / (gamma * (1.0 - beta)) # restart probability
622
+ p = float(np.clip(p, 0.0, 0.95))
623
+ # Truncating the recursion at `depth` is not free: the composition needs an
624
+ # unbounded number of hops, so a finite depth realises a SHORTER effective
625
+ # horizon than the nominal gamma. Report it rather than claim gamma.
626
+ # E[hops] = (1 - p^L)/(1 - p), each hop covering 1/(1-beta) frames.
627
+ z = enc_z.repeat_interleave(n_particles, 0)
628
+ a = a_chunk.repeat_interleave(n_particles, 0)
629
+ tk = task.repeat_interleave(n_particles, 0)
630
+ bq = torch.full((z.shape[0],), beta, device=dev)
631
+ logC = torch.zeros(z.shape[0], device=dev)
632
+ alive = torch.ones(z.shape[0], dtype=torch.bool, device=dev)
633
+ z_end = z.clone()
634
+ for h in range(depth):
635
+ x0 = _tile(torch.randn(n_particles, D, device=dev)) if crn else None
636
+ zp = sample_future(flow, z, a, tk, bq, rms, flow_steps, n=1, x0=x0)
637
+ if use_is and wend is not None:
638
+ w = (wend(z, a, zp, tk) * getattr(wend, "calib", 1.0)).clamp_min(1e-4)
639
+ logC = logC + torch.where(alive, w.log().clamp(-logw_clip, logw_clip),
640
+ torch.zeros_like(logC))
641
+ z_end = torch.where(alive[:, None], zp, z_end)
642
+ if h == depth - 1:
643
+ break
644
+ coin = _tile(torch.rand(n_particles, device=dev)) if crn else torch.rand(z.shape[0], device=dev)
645
+ cont = alive & (coin < p)
646
+ if not cont.any():
647
+ break
648
+ z = torch.where(cont[:, None], zp, z)
649
+ if crn and hasattr(pol, "sample_eps"):
650
+ a_new = pol.sample_eps(z, tk, _tile(torch.randn(n_particles, pol.d_act, device=dev)))
651
+ else:
652
+ a_new = pol.sample(z, tk)
653
+ a = torch.where(cont[:, None], a_new, a)
654
+ alive = cont
655
+ r = torch.sigmoid(rew(z_end, tk)).view(B, n_particles)
656
+ C = logC.exp().view(B, n_particles)
657
+ if self_norm:
658
+ q = (C * r).sum(1) / C.sum(1).clamp_min(1e-6)
659
+ else:
660
+ q = (C * r).mean(1)
661
+ if pessimism:
662
+ # Penalise DISAGREEMENT between particles. The measured failure mode of
663
+ # this critic is off-support optimism: conditioned on an action the data
664
+ # never took, the occupancy flow produces diffuse samples that drift
665
+ # toward the dataset mean, where the reward head returns roughly the base
666
+ # rate -- which outranks a confident low reward on a genuinely failing
667
+ # taken action. The action win rate accordingly starts near 0.55 and
668
+ # decays below chance as the flow sharpens. Particle spread is exactly
669
+ # the signal that separates the two cases, and subtracting it is the
670
+ # standard offline-RL pessimism penalty.
671
+ q = q - pessimism * r.std(1)
672
+ ess = (C.sum(1) ** 2) / (C.pow(2).sum(1)).clamp_min(1e-9) / n_particles
673
+ return q / (1 - gamma), ess
674
+
675
+
676
+ def q_fold(enc_z, a_chunk, task, *, rew, flow, rms, pol, beta, gamma, depth=1,
677
+ n_particles=16, flow_steps=8, crn=True):
678
+ """The OCBench product fold (ocbench_unified_rsm, rsm_core.step_q):
679
+
680
+ Q_k = c_k + (1 - c_k) * gamma**h * Q_{k+1}, h = 1/(1-beta), Q_{depth+1} = 0
681
+
682
+ read as reach-or-continue: c_k = read-out at the k-th hop state ("already at a
683
+ success/goal state"), otherwise pay one hop of discount and inherit the next hop.
684
+ Hop 1 is decoded from the QUERY action; hop k+1 from pol(hop_k). A FIXED number of
685
+ hops (no restart coin), per-particle fold, Monte-Carlo mean over n_particles, all
686
+ candidates (rows of enc_z) scored on the same noise when crn=True -- exactly the
687
+ recipe's estimator. With the subgoal-fraction head, c_k is the fraction of the goal
688
+ reached at hop k (partial credit); with the indicator head it is P(success state).
689
+ Returns Q in [0, 1]."""
690
+ dev = enc_z.device
691
+ B, D = enc_z.shape
692
+ h = 1.0 / (1.0 - beta)
693
+ def _tile(t):
694
+ return t.repeat(B, *([1] * (t.dim() - 1)))
695
+ z = enc_z.repeat_interleave(n_particles, 0)
696
+ a = a_chunk.repeat_interleave(n_particles, 0)
697
+ tk = task.repeat_interleave(n_particles, 0)
698
+ bq = torch.full((z.shape[0],), beta, device=dev)
699
+ cs = []
700
+ for k in range(depth):
701
+ x0 = _tile(torch.randn(n_particles, D, device=dev)) if crn else None
702
+ z = sample_future(flow, z, a, tk, bq, rms, flow_steps, n=1, x0=x0)
703
+ cs.append(torch.sigmoid(rew(z, tk)))
704
+ if k == depth - 1:
705
+ break
706
+ if crn and hasattr(pol, "sample_eps"):
707
+ a = pol.sample_eps(z, tk, _tile(torch.randn(n_particles, pol.d_act, device=dev)))
708
+ else:
709
+ a = pol.sample(z, tk)
710
+ q = torch.zeros_like(cs[-1])
711
+ for c in reversed(cs): # backward fold
712
+ q = c + (1.0 - c) * (gamma ** h) * q
713
+ q = torch.nan_to_num(q, nan=0.0).clamp(0.0, 1.0).view(B, n_particles)
714
+ return q.mean(1), torch.ones(B, device=dev)
715
+
716
+
717
+ def effective_horizon(beta, gamma, depth):
718
+ """What a depth-truncated recursion actually estimates."""
719
+ p = float(np.clip((gamma - beta) / (gamma * (1.0 - beta)), 0.0, 0.95))
720
+ hops = (1.0 - p ** depth) / (1.0 - p)
721
+ frames = hops / (1.0 - beta)
722
+ return {"restart_p": p, "mean_hops": hops,
723
+ "mean_hops_untruncated": 1.0 / (1.0 - p),
724
+ "effective_frames": frames,
725
+ "gamma_effective": 1.0 - 1.0 / max(frames, 1.0),
726
+ "gamma_nominal": gamma,
727
+ "truncation_mass": p ** depth}
frozen/rsm_libero_freeze_20261002/label_full.sbatch ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --job-name=label_full
3
+ #SBATCH --account=vision-pulkitag
4
+ #SBATCH --qos=tig-main
5
+ #SBATCH --partition=tig-cpu
6
+ #SBATCH --cpus-per-task=4 --mem=32G
7
+ #SBATCH --array=0-39
8
+ #SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%a_%A.out
9
+ #SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%a_%A.err
10
+ set -uo pipefail
11
+ B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation
12
+ S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion
13
+ export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard
14
+ export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1
15
+ T=$((SLURM_ARRAY_TASK_ID / 4)); K=$((SLURM_ARRAY_TASK_ID % 4))
16
+ OUT=/data/pulkitag/users/rli14/rsm_libero_runs/subgoals_full; mkdir -p $OUT
17
+ $B/venvs/rlinf-libero-eval-venv/bin/python \
18
+ /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/label_subgoals.py \
19
+ --cache /data/pulkitag/scratch/rli14/rsm_libero_cache/full_r256 \
20
+ --task $T --shard $K --num-shards 4 --out $OUT/task${T}_s${K}.npz --stride 5