rsm_rise code snapshot (HF_PUSH_ALL)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+4
- README.mdAdded+34
- THIRD_PARTY.mdAdded+18
- frozen/rsm_libero_freeze_20261002/CLAUDE.mdAdded+291
- frozen/rsm_libero_freeze_20261002/FINDINGS.mdAdded+344
- frozen/rsm_libero_freeze_20261002/FREEZE_COMMITAdded+1
- frozen/rsm_libero_freeze_20261002/README.mdAdded+737
- frozen/rsm_libero_freeze_20261002/audit_logged_goal.pyAdded+93
- frozen/rsm_libero_freeze_20261002/audit_logged_goal.sbatchAdded+17
- frozen/rsm_libero_freeze_20261002/autoresearch_driver.pyAdded+78
- frozen/rsm_libero_freeze_20261002/awr.pyAdded+275
- frozen/rsm_libero_freeze_20261002/bc_arm.pyAdded+153
- frozen/rsm_libero_freeze_20261002/calib_dwm.pyAdded+106
- frozen/rsm_libero_freeze_20261002/capture_cpu.sbatchAdded+32
- frozen/rsm_libero_freeze_20261002/capture_init_feats.pyAdded+88
- frozen/rsm_libero_freeze_20261002/crn_diag.pyAdded+58
- frozen/rsm_libero_freeze_20261002/data.pyAdded+587
- frozen/rsm_libero_freeze_20261002/df_readout.pyAdded+228
- frozen/rsm_libero_freeze_20261002/dinowm_readout.pyAdded+168
- frozen/rsm_libero_freeze_20261002/dwm_model.pyAdded+562
- frozen/rsm_libero_freeze_20261002/dwm_readout.pyAdded+314
- frozen/rsm_libero_freeze_20261002/dwm_readout_timing.pyAdded+78
- frozen/rsm_libero_freeze_20261002/encode_parquet.pyAdded+83
- frozen/rsm_libero_freeze_20261002/encode_t5.pyAdded+52
- frozen/rsm_libero_freeze_20261002/encode_t5.sbatchAdded+16
- frozen/rsm_libero_freeze_20261002/eval_closed_loop.pyAdded+1025
- frozen/rsm_libero_freeze_20261002/eval_slurm.sbatchAdded+90
- frozen/rsm_libero_freeze_20261002/extract_clips.pyAdded+98
- frozen/rsm_libero_freeze_20261002/extract_viz.pyAdded+90
- frozen/rsm_libero_freeze_20261002/ibm_autoresearch.shAdded+53
- frozen/rsm_libero_freeze_20261002/ibm_bias_diag.shAdded+16
- frozen/rsm_libero_freeze_20261002/ibm_cell.shAdded+21
- frozen/rsm_libero_freeze_20261002/ibm_crn_diag.shAdded+13
- frozen/rsm_libero_freeze_20261002/ibm_eval.shAdded+51
- frozen/rsm_libero_freeze_20261002/ibm_eval_depth.shAdded+7
- frozen/rsm_libero_freeze_20261002/ibm_eval_matrix.shAdded+25
- frozen/rsm_libero_freeze_20261002/ibm_eval_matrix_last.shAdded+38
- frozen/rsm_libero_freeze_20261002/ibm_eval_ocb.shAdded+23
- frozen/rsm_libero_freeze_20261002/ibm_eval_robust.shAdded+25
- frozen/rsm_libero_freeze_20261002/ibm_eval_sde.shAdded+20
- frozen/rsm_libero_freeze_20261002/ibm_full_wave.shAdded+44
- frozen/rsm_libero_freeze_20261002/ibm_pack_onpol.shAdded+12
- frozen/rsm_libero_freeze_20261002/ibm_rerender.shAdded+18
- frozen/rsm_libero_freeze_20261002/ibm_resubmit_missing.shAdded+30
- frozen/rsm_libero_freeze_20261002/ibm_retry_tasks.shAdded+16
- frozen/rsm_libero_freeze_20261002/ibm_table.pyAdded+70
- frozen/rsm_libero_freeze_20261002/ibm_train_onpol.shAdded+15
- frozen/rsm_libero_freeze_20261002/iql.pyAdded+259
- frozen/rsm_libero_freeze_20261002/is_ope.pyAdded+727
- frozen/rsm_libero_freeze_20261002/label_full.sbatchAdded+20
32 unmodified lines3334353637383932 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textfrozen/rsm_libero_freeze_20261002/notes/action_contrast.pdf filter=lfs diff=lfs merge=lfs -textfrozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -textfrozen/rsm_libero_rsmpi/notes/action_contrast.pdf filter=lfs diff=lfs merge=lfs -textfrozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728293031323334---license: othertags: [robotics, offline-rl, successor-measure, rise, robomimic]---# rsm_rise -- code snapshot
Code for **RSM (successor model) as the value function on top of the RISE stack** (RISE: arXiv 2510.19495):the pipeline, training/eval launchers and the paper tables' source docs. Snapshot taken 2026-11-22.
| folder | what it is ||---|---|| `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) || `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 || `frozen/rsm_libero_rsmpi/` | RSM policy-iteration (RSM-pi) variant || `frozen/rsm_libero_snap_20261030/` | later RSM snapshot (2026-10-30, source only) || `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 || `rsm_rise/scripts/` | cluster launchers, eval cells, table builders (`scripts/real` = real-robot cooking, `scripts/rsmpi` = RSM-pi) || `rsm_rise/docs/` | plan of record, master table, checkpoint choice, LaTeX sources of the reports (`docs/tex`) || `THIRD_PARTY.md` | upstream repos + commits (RISE code, robomimic fork, robosuite, mimicgen, diffusion_policy, ...) that are not vendored |
Secrets (HF / W&B tokens) are excluded and the staged tree was scanned for token patterns before upload.
## Checkpoints| repo | content ||---|---|| [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 || [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) || `hf://buckets/rsm-bucket/rsm-shared/` | v6/v7 real-robot bulk exports (bucket) |
```pythonfrom huggingface_hub import hf_hub_downloadp = hf_hub_download("rli14/rsm_rise_sim_checkpoints", "square_sub_20100/rsm/M/ckpt_best.pt")```or `hf download rli14/rsm_rise_sim_checkpoints --include "square_sub_20100/*" --local-dir ckpts/`.123456789101112131415161718# Third-party code used by rsm_rise (not vendored here)
| dir under rsm_rise/code | upstream remote | commit | note ||---|---|---|---|| df_rise | (vendored source-only copy in code_src/df_rise) | - | as run, incl. local edits || diffusion_forcing | https://github.com/buoyancy99/diffusion-forcing.git | 475e0bcab87545e48b24b39fb46a81fe59d80594 | 2025-02-22 13:48:31 -0500 || diffusion_forcing_paper | (not a git checkout) | - | || diffusion_policy | https://github.com/UWRobotLearning/diffusion_policy.git | 078ce1ee2064cde28074db239ff0af2f9254069b | 2025-01-27 04:42:52 -0800 || gen_q_rsm_snap_20261030 | (not a git checkout) | - | || ifql | (vendored source-only copy in code_src/ifql) | - | as run, incl. local edits || mimicgen_environments | https://github.com/UWRobotLearning/mimicgen_environments.git | 14d8eb5709b38c6b75ecf140c3608ff984196832 | 2025-02-17 16:06:34 -0800 || ogbench_beta | (not a git checkout) | - | || rise_code | (vendored source-only copy in code_src/rise_code) | - | as run, incl. local edits || rise_robomimic | (vendored source-only copy in code_src/rise_robomimic) | - | as run, incl. local edits || robosuite | https://github.com/UWRobotLearning/robosuite.git | 9ea2411569d66776bd476d3c4e5944a6a8482ae1 | 2024-12-02 02:46:43 -0800 || rsm_libero_rpred | (not a git checkout) | - | || tdmpc2 | https://github.com/nicklashansen/tdmpc2.git | e9f59321933cbc8e11a002b842adc7d4ffae8ff1 | 2026-07-13 15:26:47 -0700 || tdmpc2_rise | (vendored source-only copy in code_src/tdmpc2_rise) | - | as run, incl. local edits |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291# rsm_libero — LIBERO-10 RSM critic evaluation
## INVALIDATION (2026-09-13): every result before this date is void
Every run directory under `rsm_libero_runs/mit/` suffixed `_wrong_eval_env` (105 of them) andevery eval JSON under `rsm_libero_runs/eval/wrong_eval_env/` (143) was produced with the rolloutlatents and the evaluator in DIFFERENT feature spaces. Do not cite, compare against, or resumefrom them. The results tables further down in this file are retained only as a record of whatwas believed; they are superseded. Valid runs are `*_r` and later, trained on`rsm_libero_cache/full_demo_r256` (or its full-corpus successor) and evaluated at `--cam-res 256`.
## PINNED INPUT FORMAT (offline data == online environment, or the run is inadmissible)
| item | value | why ||---|---|---|| camera render | **256x256**, both cameras (`--cam-res 256`, the default) | RLinf `config/env/libero_10.yaml`; the collector rendered at 256 || orientation | raw render `[::-1, ::-1]` -> serving orientation | parquet images are stored already upright; demo hdf5 stores raw || resize | 256 -> 224 bilinear, **round and clamp to uint8** | `to224`: float input alone moves the latent 3 sigma || encoder | the latent-cache BUILDER's PaliGemma, base||wrist 2048+2048 | same module the evaluator imports || proprio | eef_pos(3) ++ ee_ori **axis-angle**(3) ++ gripper_qpos(2) | Euler was the #243 bug || demos | `libero10_demo_ogpo_cache_r256` (re-rendered from hdf5 `states` at 256) | the 128 demo cache is off-manifold under this evaluator || normalisation | `feat_stats*.npz` of the cache being trained on | eval reads `norm_pool` from the checkpoint |
**Naming and marker convention (2026-09-13).** Every dataset, cache and checkpoint carries the renderresolution it was produced at, twice: in the NAME (`_cam128`, `_cam256`; a mix is `_MIXED_..._INVALID`)and in a machine-readable marker (`RENDER.json` / `PACK.json` `cam_res`; checkpoints store `cam_res`).`eval_closed_loop.py` REFUSES a policy, critic or Q whose declared resolution differs from`--cam-res`, and refuses an undeclared one (`--allow-cam-mismatch 1` overrides; never for a reportednumber). `pack.py --cam-res` is how a cache gets its declaration.
| asset | name | cam_res ||---|---|---|| rollout latents | `pi05_lib10_ogpo_fl15_v1` (+RENDER.json) | 256 || demos, LIBERO hdf5 render | `libero10_demo_ogpo_cache_cam128` | 128 -- invalid under the 256 evaluator || demos, re-rendered | `libero10_demo_ogpo_cache_cam256` | 256 || subset cache | `rsm_libero_cache/full_demo_cam256` (`full_demo_r256` is a symlink for running jobs) | 256 || full cache | `rsm_libero_cache/full_r256` | 256 || old subset cache | `full_demo_MIXED_128demos_256rollouts_INVALID` | mixed |
Rule, extended from reward labels to features: **a latent the eval environment cannot produce isinadmissible for offline training.** Verify with `rerender_rollouts.py --validate-rollouts` /`--validate-demos` (re-render from logged state in the evaluator's env; L2 to the cached latentmust sit at the within-cloud scale, ~4-12, not 60+).
## RULE: offline data must reproduce its reward labels in the EVAL environment
**A trajectory is admissible for offline training only if replaying its logged actionsin the environment we evaluate in reproduces its reward labels. If it does notreproduce, drop the trajectory.**
This is not a data-cleaning nicety, it is a correctness condition. An offline learnerfits $(s,a,r,s')$ tuples and is then scored in the simulator. If those tuples cannot bereproduced there, they describe different dynamics than the ones the policy is gradedagainst, and the learner is being fit to an environment that does not exist. That is thestandard way offline RL silently fails.
Three consequences that are easy to get wrong:
1. **"The label was honest" is NOT the admissibility test.** Evaluating the goal predicate at an episode's own logged final state answers whether the recorder told the truth about the state it reached. Useful diagnostics, wrong question. A truthful label on a trajectory that will not reproduce here is still inadmissible.2. **The replay must run in the SAME configuration as eval** — same venv, same package versions, same renderer and device. A trajectory that reproduces on CPU/osmesa but not on the GPU/EGL path we actually evaluate on is not admissible, because the eval path is the one that defines the environment.3. **If the eval environment changes, admissibility must be recomputed.** Moving eval to a different cluster, venv or `bddl` version invalidates the existing mask. See the pinned versions below: IBM's `bddl` is 1.0.1 against MIT's 3.6.0, and `bddl` defines the goal predicates, so a mask built for MIT does not transfer.
Measured on R1 (`pi05_lib10_sde_v1`): replaying logged successes reproduces **~81%**(per task 0.620--0.938). The remaining ~19% are inadmissible and are dropped by`merge_verify.py --shards`, leaving ~1800 usable rollout successes. For contrast, thediagnostic goal-predicate check passes ~87% — the gap between the two is exactly theset of trajectories that were honestly recorded but do not reproduce, and **those areinadmissible too**.
## THE TWO EVALUATION PROTOCOLS — always report both
There are two initial-state distributions, they give materially different numbers,and **which one you use decides who wins**. Never report one without saying which.
| protocol | flag | what it does | who is at home in it ||---|---|---|---|| **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) || **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") |
```bash# A: stock init statessbatch --export=ALL,POLICY=$P,NINIT=50,OUT=$E/x.json eval_slurm.sbatch# B: continuous regionsbatch --export=ALL,POLICY=$P,NINIT=50,FRESH=1,OUT=$E/x_fresh.json eval_slurm.sbatch```
### How an initial condition is actually defined
Per episode, indexed by task `tid` and episode `k` (both protocols):
```pythonpseed = 7_919_003 + policy_seed*500_009 + tid*1_013 + k # policy sampling RNGtorch.manual_seed(pseed); torch.cuda.manual_seed_all(pseed)np.random.seed(seed*100_003 + tid*1_009 + k)env.seed(seed*100_003 + tid*1_009 + k) # env RNGenv.reset() # B stops hereif not fresh: env.set_init_state(inits[k % 50]) # A overrides the reset```
**Protocol A** — `env.set_init_state()` writes one of LIBERO's 50 stored full sim-statevectors (`bench.get_task_init_states(tid)`), overwriting whatever `reset()` sampled.Object poses are therefore a deterministic replay of a fixed, finite, curated set.`NINIT=10` replays inits 0-9, which is why it is biased (see above); `NINIT=50` useseach stored state exactly once.
**Protocol B** — no override, so object poses come from the task's BDDL placementregions (`bddl_base_domain.py`: `regions[name]["ranges"]` → `UniformRandomSampler`,uniform in x/y over the task's rectangle plus a z-rotation). Under B, `NINIT=10` is asmall unbiased sample rather than a curated subset — noisy, but not systematically easy.
**MEASURED (`probe_inits.py`, 2026-09-12): protocol B is NARROWER than protocol A.**Mean std of the randomised sim-state DoF, over 50 states per task:
| protocol | mean std | note ||---|---|---|| A, stock init states | **0.0236** | wider on all 10 tasks || B, `env.reset()` | **0.0138** | 0.58x of A |
So `--fresh 1` is **not** an "expanded region" — it is a tighter one, and A is the moredemanding of the two. (`stock_inside_fresh_support = 0.00` is a consequence of A beingwider, not of a distribution shift.)
**Neither protocol reproduces the rollout corpus's init distribution.** The corpus wascollected with RLinf's `fresh_reset=true`, documented as "fresh 5 cm inits" — 0.05would be wider than both A and B. Our evaluator has no equivalent. Evaluating on thegenuine 5 cm region would require explicit jitter of object free-joint xy after reset;until that exists, the critic and the success-pool policies are under a mild initshift under BOTH protocols.
**Protocol A CANNOT be replicated by varying `SEED`.** `set_init_state` overwriteswhatever `env.reset()` sampled, so `env.seed` has no effect; `np.random.seed` is set butnever used in the rollout loop; and the policy stream is keyed on `--policy-seed`, not`--seed`. Re-running protocol A at a different `SEED` reproduces the identical 500episodes. **A is hard-capped at 500 distinct episodes** (50 stored inits x 10 tasks).Its only legitimate replication is `PSEED=1,2,...`, which resamples the policy on thosesame inits. Protocol B draws fresh placements per episode, so `SEED` gives genuine newepisodes and n scales without limit — it is the only protocol that supports replication.
**Both protocols are PAIRED across arms.** The env seed depends only on`(seed, tid, k)` and the policy seed only on `(policy_seed, tid, k)` — neither dependson which policy or critic is being evaluated. So with `SEED=0` every arm sees theidentical sequence of initial conditions and the identical policy-sampling RNG stream.Differences between arms are attributable to the arm, and variance on a *difference*is lower than the independent-sample formula implies. Never vary `SEED` between armsyou intend to compare.
### Why this is not a detail
Provenance of every component, verified 2026-09-12 from the corpus `DATASET.md` files:
| component | source | init distribution ||---|---|---|| 500 demos → BC-on-demos | `libero10_demo_ogpo_cache_srv` (official LIBERO-10 human demos) | **stock init states** || 4500 rollouts → BC-on-successes, **93% of critic training** | `pi05_lib10_ogpo_fl15_v1` ← `pi05_lib10_sde_v1` | **fresh 5 cm**, `fresh_reset=true` |
Under protocol A we evaluate on exactly the configurations the demos were collectedfrom, while the rollout corpus — which trains the critic and the success-pool policies— comes from a different, wider region. That is a structural advantage forBC-on-demos and a distribution shift against everything else. Protocol B is the onewhere the critic's training distribution matches the test distribution.
## PINNED: simulator versions, and where eval may run
**All LIBERO evaluation and the R1 rollout collection run in the SAME MIT venv**, sothey are comparable by construction. Do not change this venv without re-deriving everynumber in this file.
```venv continual_learning_for_manipulation/venvs/rlinf-libero-eval-venv (python 3.11.15)mujoco 3.8.1 robosuite 1.4.1 bddl 3.6.0 libero vendoredinstalled 2026-08-31 (corpus R1 collected 2026-09-05 with this same venv, unchanged since)collection driver: logs/09052026_pi05_lib10_collect.sh -> PYE=.../rlinf-libero-eval-venv/bin/python```
**IBM cannot run LIBERO eval, and its stack is not equivalent:**
| | MIT (eval + collection) | IBM `/proj/dmfexp/zwhong/venvs/lerobot_env` ||---|---|---|| mujoco | 3.8.1 | 3.8.1 || robosuite | **1.4.1** | **1.4.0** || bddl | **3.6.0** | **1.0.1** || libero | vendored | **absent** |
`bddl` differs by a major version and **bddl defines the goal predicates**, so a"success" computed on IBM would not be the same event. IBM is **training-only**; everyclosed-loop number must come from MIT.
**The replay divergence is NOT a version mismatch.** Collection and replay share thevenv and the versions, installed before collection and untouched since. Re-executinglogged actions reproduces only ~81% of successes because contact-rich manipulation ischaotic and the two runs differ in floating-point detail (collection on GPU nodes underEGL, replay on CPU under osmesa). This is why label correctness must be measured byevaluating the goal predicate at the LOGGED FINAL state (~87% correct) rather than byreplay (~81%) -- replay conflates label error with non-reproducibility and overstatesit by roughly 3x on the worst task.
## Other measurement traps in this directory
**`NINIT=10` is a fixed easier subset, not a sample.** Init states are selected as`inits[k % 50]`, so `n_init=10` always replays inits 0–9. Measured on one policy:**0.630 at n=100 vs 0.532 at n=500**, a +0.098 mean per-task gap on 8 of 10 tasks.It is deterministic and does not shrink with repetition. Control: a Q-filter gatefiring on 0.5% of decisions (≈ BC) returned exactly 0.630 at n=100.**Use `NINIT=50` for any number you intend to quote.** At n=100 the standard error ona *difference* is ±0.069, so sub-14-point effects are unresolvable.
**Success labels are ~16% optimistic.** A replay audit of the source corpus found 5 of32 logged successes did not actually succeed. BC-on-successes clones a pool where~1 in 6 "successes" is a failure, and the critic's `γ^steps-to-success` reward givesthose episodes a full progress curve toward a success that never happened.
**Held-out action win rate does not predict closed-loop.** `ckpt_best.pt` selects onit, but it went 0.478 → 0.784 → 0.896 across critics while closed-loop went0.496 → 0.490. A collapse to 0.363 cost only 0.046. Treat it as a broken-critic alarm,not a selection criterion.
**A silent 0% means a config mismatch**, not a bad policy — a chunk-25 flow policy runthrough the chunk-10 concat harness scores exactly 0/350. Same signature as theoriginal Euler-vs-axis-angle proprio bug.
## Results, n=500, both protocols
Protocol B column is filled as arms land; `--` = not yet run.
| arm | uses demo labels? | A: stock | B: 5 cm continuous ||---|---|---|---|| BC-on-demos | yes (pool) | **0.532** | **0.520** || BC-on-successes | no | 0.438 | -- || RSM ranking, successes proposal, N=32 | **no** | 0.416 | -- || IQL extraction (200k steps) | yes (pool) | 0.416 | -- || RSM ranking, demos proposal (best: `c1Mb`, β 0.98/0.99) | yes | **0.540** | -- || RSM ranking, successes proposal | **no** | -- | -- || AWR extraction on success pool | **no** | -- | -- |
**Measured 2026-09-12: BC-on-demos scores 0.532 (A) vs 0.520 (B) — it does NOTmemorise the stock init states.** Protocol A is not inflating the baseline; the bar isreal. The remaining reason to run B is the reverse concern: the critic and thesuccess-pool policies were trained on the continuous-region corpus, so protocol A puts*them* under mild shift.
Scoring rule (PI): using the demo *label* is a privilege that only counts if it beatsBC-on-demos. Using demo *data* without the label is unprivileged; beatingBC-on-successes there is already signal, and beating BC-on-demos is the strong claim.
### Critic ablations (protocol A, n=500, demos proposal)
| knob | result ||---|---|| **trained β band** 0.85–0.97 / **0.93–0.995** / 0.96–0.999 | 0.490 / **0.540** / 0.502 — inverted-U, optimum found || read-out β 0.95 / 0.98 / 0.99 / 0.995 | 0.524 / 0.540 / 0.540 / 0.500 — plateau 0.98–0.99 || critic steps 12k → 110k (same band) | 0.496 → 0.490 — **no effect** || best-of-N 8 → 32 | flat to harmful || confidence gate (6 thresholds, 0.5%–60% fire) | 0.488–0.532 — no regime beats BC || candidate noise (SDE 0.3) | 0.510 → 0.290 — strongly harmful || demo-chunk retrieval (+4 / +8 / retrieval-only) | 0.516 / 0.392 / 0.352 — **strongly harmful** || action chunk 10 → 16 / 24 / 32 | 0.630 → 0.49 / 0.29 / 0.25 (n=100) — strongly harmful || AWR advantage into the actor (demos pool) | 0.520 → 0.350 vs its own `w≡1` control — strongly harmful |
**The critic cannot rank off-proposal candidates.** Noise, N=32 and retrieval all fail,and retrieval fails *in proportion to how often the retrieved chunk is used*. Itsordering is calibrated only on the proposal's own distribution; outside it the rankingis actively misleading, not merely uninformative. Corollary: AWR on a pool of uniformlyexpert demos can only damage it — run advantage weighting on the **success** pool,where quality actually varies.
## Paths
```code /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_liberocache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo # 5000 eps = 500 demo + 4500 rolloutruns /data/pulkitag/users/rli14/rsm_libero_runs/mitevals /data/pulkitag/users/rli14/rsm_libero_runs/evalbest critic runs/mit/critic_1M_b995/ckpt_best.pt # band 0.93-0.995, step 110kBC-demos runs/mit/A_nd/policy_r1.pt # 0.532 (A, n=500)BC-successes runs/mit/B_nd/policy_r1.pt # 0.438 (A, n=500)```
Compute: MIT slurm, `--qos=vision-pulkitag-free-cycles`. Never `vision-pulkitag-main`.`lab-free`/`csail-shared-h200` gets root-cancelled within seconds — use`vision-pulkitag-l40s,vision-pulkitag-a6000`. Training is resumable (`--resume 1`,saves optimiser state); chain with `--dependency=afterany`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344# RSM on the LIBERO-10 pi0.5 rollout corpus: findings
Branch `rsm-libero10-ope`. All closed-loop numbers: 10 tasks x 10 initial states(n=100), 520-step cap, action chunk 10 with 10 executed, seed 0, measured by`eval_closed_loop.py` after the fix described in section 2.
---
## 1. Headline
Behaviour cloning on the 500 demonstrations is the best policy in this lane, andno value-guided extraction beats it.
| arm | succ/n | SR | thr succ | thr all ||---|---|---|---|---|| **BC on demonstrations** | **63/100** | **0.630** | 1.132 | 0.874 || lane reference `bcdemos_h1024d4`, our harness | 53/100 | 0.530 | 0.946 | 0.691 || RSM Q-filter, 16 candidates | 51/100 | 0.510 | 0.951 | 0.668 || IQL + AWR (demo pool) | 50/100 | 0.500 | 0.963 | 0.658 || IQL + AWR (success pool) | 49/100 | 0.490 | 0.839 | 0.615 || BC on successful rollouts | 48/100 | 0.480 | 0.807 | 0.596 || PARL + RSM value (collapsed proposal) | 44/100 | 0.440 | - | - || RSM + AWR (demo pool) | 43/100 | 0.430 | 0.758 | 0.528 || RSM + AWR (success pool) | 41/100 | 0.410 | 0.802 | 0.513 |
Our BC also clears the published 0.584 reference: that checkpoint scores 0.530through this harness, and ours scores 0.630 under the same protocol.
Both critic arms start from the *same* 0.630 clone and move it **down**. Theadvantage signal is harmful, not merely uninformative.
---
## 2. The bug that invalidated everything before it
For most of this work every arm scored **0%**. The cause was in our evaluator, notin any policy: it converted the end-effector quaternion to **Euler angles**, whilethe latent cache stores robosuite **axis-angle**. Three of the eightproprioception dimensions were a different physical quantity at every timestep ofevery episode.
Proof, same machine and same weights, on the lane's own 0.584 policy:
| evaluator | task 5 ||---|---|| lane's `09032026_latent_head_eval.py` (axis-angle) | 5/5 || ours before the fix (Euler) | 0/5 || ours after the fix | 5/5 |
Why every existing check missed it:
* The visual latent is 4096 of 4104 input dimensions, so the three corrupted ones never moved a **cosine similarity**. Our encoder reproduces the cache at cos 0.9999 offline and 0.9903 from live frames; both stayed green throughout.* The **offline fit** is computed on cached proprio, which is correct, so held-out sampled action MSE looked healthy at 0.049.* A **bit-exact comparison of the first action chunk** passed, because it called the same helper on both sides.
Only an end-to-end control with a known-good policy exposes it. That control didnot exist in this lane before now; `eval_closed_loop.py --lane-norm` runs it.
A second, smaller deviation in the same file: `to224` returned the raw float32interpolation where the cache builder rounds to uint8, shifting the latent by upto 0.31 against a per-dim std of 0.107. Fixed, though not the cause of the 0%.
**Anything measured through this evaluator before commit `b64ebddf` says nothingabout the policy it was measuring.**
---
## 3. What the main-branch recipe gave us, and what it did not
Adopted from `ogbench_unified_rsm/RECIPE.md` and the lane's BC:
| item | effect here ||---|---|| flow-matching occupancy on residuals, per-dim RMS normalised | works; CFM val loss 0.17-0.30 || EMA target encoder, variance floor | no collapse observed (latent std min 0.10-0.41) || Fourier beta conditioning, FiLM in the successor | retained || beta band + query beta | see section 5: the band is not the lever || action-contrastive term | does not fix the action gap at any weight || concatenation flow head for the policy (their BC head) | matches their fit exactly || select on ODE-sampled MSE, not the CFM loss | correct, but see section 6 || SWA at deploy, two-tower `q_readout=lik` | **not implemented** |
Two things we added that mattered more than any recipe item:
1. **The policy must not read the critic's latent.** That encoder is trained to predict reward and discards what an action head needs. On the 264-d latent a flow policy beat a predict-the-mean baseline by 14% in action MSE with a biased gripper channel. Reading the full observation is what took arms off the floor.2. **Policy input scaling**, section 4.
---
## 4. Normalisation is worth more than any algorithm here
| policy input | SR ||---|---|| centred with DEMONSTRATION statistics | **0.630** || centred with rollout-dominated statistics | 0.430 || per-dim z-scored | 0.010 |
Centring matters because the mean feature vector has norm 51.1 against aper-frame deviation of 9.0, so 85% of the raw magnitude is a constant. *Which*frames the statistics come from matters because the rollout corpus is a differentdistribution (pi0.5 with SDE noise 0.5, about half failures). Whitening iscatastrophic because per-dim std spans 0.048 to 3.675, so it shrinks the fewinformative directions up to 34x relative to the median.
Note the sign flip against intuition: whitening *improved* the critic's action gap(-0.086 to a +0.103 peak) while destroying the policy. The critic and the policywant different input geometry, which is why they are scaled separately.
---
## 5. The critic ranks states well and actions barely at all
Held-out within-task action win rate versus reward AUC, across every intervention:
| critic | action win | reward AUC ||---|---|---|| chunk 10, w_actcon 0.5 (deployed) | 0.568 | 0.96 || w_actcon 1.0, d_z 512 | 0.532 | 0.96 || w_actcon 2.0 | 0.533 | 0.96 || inverse dynamics 1.0 | 0.445 | 0.96 || inverse dynamics 5.0 | 0.534 | 0.96 || chunk 10, hop 0.97 | 0.558 | 0.96 || chunk 10, hop 0.99 | 0.551 | 0.96 || chunk 30, hop 0.967 | 0.597 | 0.96 || chunk 100, hop 0.99 | **0.613** | 0.95 |
All peak between step 1000 and 2000 and then decay below chance. The state valueis excellent throughout; only the action channel is missing.
**The lever is the action window, not the hop.** Holding chunk at 10 and sweepingthe hop is flat (0.568 / 0.558 / 0.551). Widening the window to 100 frames is theonly thing that moves it. A 10-frame chunk does not determine enough about theoutcome on these tasks.
This is consistent with the lane's own earlier measurement: over 5 frames theexecuted action correlates with the **proprio** delta at |r| up to 0.98 but withthe **visual-latent** delta at only 0.49 (mean 0.10). A mean-pooled PaliGemmaembedding barely resolves what a short chunk does.
And the trade is strictly unfavourable, because the policy moves the other way:
| chunk | BC on demos | RSM extraction | critic win ||---|---|---|---|| 10 | **0.630** | 0.430 | 0.568 || 30 | 0.440 | 0.160 | 0.597 || 100 | 0.080 | 0.020 | 0.613 |
---
## 6. The experiment that settles it: PARL with proposal diversity
PARL ranks N=32 proposal samples by Q, keeps the argmax, and distills. Its ownprecondition is that the proposal must be diverse, because ranking N copies of oneaction cannot improve anything. Measured action std against the data's 0.421:
| proposal | action std | ratio ||---|---|---|| BC on demos, 120k steps, best-MSE checkpoint | 0.029 | 0.070 || BC on demos, 20k steps | 0.053 | 0.126 || the same, sampling temperature 1.5 | 0.103 | 0.244 || the same, sampling temperature 2.5 | 0.222 | 0.527 |
**Selecting a checkpoint by best held-out sampled MSE picks the mostmean-collapsed policy.** Our earlier Q-filter was therefore ranking 32 near-copiesof one action, which is why it returned 0.510 instead of anything informative.This is a trap for anyone reusing `train_bc`'s selection for a proposal.
Result:
| proposal diversity | PARL SR ||---|---|| 0.070 | 0.350 || 0.126 | 0.440 || 0.244 | 0.230 || 0.527 | **0.000** |
and dropping the variance penalty, so selection follows the raw value instead ofhugging the mode, makes it worse again:
| selection rule | T=1.5 | T=2.5 ||---|---|---|| Q minus 2 particle std | 0.230 | 0.000 || pure expected success | 0.130 | 0.010 |
Critic, N, distillation and evaluator are fixed across every row; the onlyvariable is how much freedom the value has to choose. A value carrying signal gets*better* with a wider candidate set. This one destroys the policy.
**Conclusion: Q responds to the action, but the direction of its response isuncorrelated with action quality.** Measured directly with`probe_perturb.py` on demonstration frames, where the logged chunk is byconstruction the good action:
| perturbation noise | mean Q | expert wins ||---|---|---|| 0 (expert chunk) | 48.749 | - || 0.05 | 48.800 | 0.489 || 0.10 | 48.674 | 0.508 || 0.20 | 48.769 | 0.508 || 0.40 | 48.962 | 0.490 || 0.80 | 49.243 | 0.483 |
The data's own action std is 0.421, so noise 0.80 destroys the action completely,and mean Q moves by 1%, with the expert winning half the comparisons at everylevel.
That alone is ambiguous: it is equally consistent with "Q ignores the action" andwith "the Monte-Carlo estimator cannot resolve the action", because q_recursivedraws fresh flow noise per call. `probe_crn.py` separates them by scoringcandidates under COMMON random numbers, which cancels the shared noise from thepaired difference:
| perturbation | paired abs dQ (CRN) | expert wins | ratio to repeat noise ||---|---|---|---|| 0.10 | 0.399 | 0.481 | 0.18 || 0.20 | 0.719 | 0.503 | 0.32 || 0.40 | 1.588 | 0.482 | 0.71 || 0.80 | 3.793 | 0.502 | 1.69 |
(repeat noise, same action under independent draws: 2.246)
So Q is **not** blind. It moves substantially when the action changes, roughlylinearly in the perturbation size, and at noise 0.8 the paired response exceedsthe estimator noise. What is missing is the SIGN: perturbing an expert action isexactly as likely to raise Q as to lower it, even at the smallest perturbation andeven with the shared noise cancelled.
The occupancy model has therefore learned an action-conditioned map whosecounterfactual gradient is meaningless. It is trained only on (state, actionactually taken, observed future); it never sees a counterfactual action with areal outcome, so off the logged action it extrapolates confidently andarbitrarily. Magnitude without direction.
This explains every downstream result coherently, and explains the PARL sweepbetter than "weak critic" does. Selection follows an arbitrary direction, so PARLeffectively picks a random member of its candidate set; the wider the set, thefurther off-support the winner, and the worse the policy -- exactly the monotonecollapse 0.440 -> 0.230 -> 0.000. AWR weights become noise that dilutes the clone.A collapsed proposal looks harmless because a random choice among 32 copies of oneaction is still that action, and it is also the only configuration that staysinside the region where the model was ever trained.
It also explains why the 0.568 offline win rate looked survivable: comparing thelogged chunk against a DIFFERENT episode's chunk is dominated by on-support versusoff-support, which the occupancy model does capture. Ranking a policy's owncandidates at the same state is a different question, and there the model hasnothing to say.
The 0.568 offline win rate did not reveal this, because ranking *dataset*alternatives is dominated by on-support versus off-support. That is a differentquestion from ranking a policy's *own* candidates, which is what every extractionmethod actually does. `probe_perturb.py` asks the right question directly: does Qprefer the expert chunk over noisy perturbations of it.
### The filtering test the corpus was collected for
One configuration tests the critic's whole reason to exist. Fit the proposal tothe WHOLE corpus, failures included, so its candidate set genuinely contains bothgood and bad behaviour, then let the value filter it. A critic that can separatesuccess-like from failure-like actions should recover demonstration-levelperformance from a proposal that on its own is poor.
| proposal | PARL SR ||---|---|| demonstrations only (diversity 0.126) | 0.440 || whole corpus incl. failures (diversity 0.132) | **0.170** |
It does not filter. Given a candidate set that by construction contains thefailure modes the critic was trained on, selection makes things worse, not better.
That run also shows candidate diversity cannot be bought with data: fitting theproposal to the whole corpus gives action std 0.056, against 0.053 fordemonstrations only. Flow matching learns the conditional mean regardless of howvaried the data behind it is. The only lever that moved diversity was samplingtemperature, and that pushes candidates off the manifold -- exactly where thevalue's response was measured to be arbitrary. On-manifold and diverse are notjointly available from a flow behaviour clone here.
---
## 7. Bugs fixed along the way
Each of these alone produced a zero or a badly wrong number.
1. Evaluator sent Euler angles where the cache holds axis-angle (section 2).2. Evaluator fed float32 pixels where the builder quantises to uint8.3. `import_file` given an absolute path: ValueError before any env was built.4. The featuriser imported from the rollout producer, which does not define it.5. `RawFeat` left on CPU once it carried a buffer.6. `offline_score` indexed an empty failure pool on a demos-only cache.7. `bc_arm` scored before saving, discarding a finished 120k-step run.8. Launchers ended with `echo`, so crashed jobs exited 0 and every `--dependency=afterok` eval ran against a checkpoint never written.9. AWR weight degeneracy: advantage std ~8 at beta 3 saturates the exponent, so the "soft" weight was a hard sign filter on a 0.568-accurate critic. Worth 0.11 (IQL 0.380 to 0.490 once the advantage is standardised).10. `q_recursive` called the extracted policy to re-draw continuation actions in latent space, which a raw-feature policy cannot answer; it now uses a separate latent-space continuation policy.
---
## 8. Where to iterate next
The blocker is specific: the latent does not carry the action, so no read-outbuilt on it can rank actions, and the horizon over which a short chunk matters istoo short to recover the signal. In rough order of expected value:
1. ~~Ask whether the ranking is inverted or absent.~~ **Answered: neither.** Q responds to the action with the right magnitude and an arbitrary sign (section 6). There is no sign to flip and no variance to average away -- common random numbers make the paired response exceed the estimator noise and the expert still wins only half the time. The defect is that the model's COUNTERFACTUAL response is untrained: it only ever sees the action that was actually taken. Everything below attacks that.2. **A latent that is action-predictive by construction.** The inverse-dynamics auxiliary tried here (`--w-invdyn`) is the weak version: it shares the encoder with a reward objective that dominates. Stronger: train the occupancy in a latent whose *only* objectives are reward AND inverse dynamics, or concatenate a proprio-history channel that already correlates with the action at 0.98.3. **The recipe's `q_readout=lik`.** The two-tower InfoNCE goal likelihood is the one main-branch item not implemented here. `GoalLikelihood` already exists in `model.py`, unused. A contrastive read-out is better calibrated than a saturating reward head and may rank where the sigmoid cannot.4. **Decouple the critic's action window from the policy's.** The measured trade-off is that the critic wants 100 frames and the policy wants 10. A model-based lookahead that scores the policy's 10-frame chunk followed by occupancy-rolled continuation would give the critic its long window without forcing the policy to emit one. This is the most promising direction and the most work; the pieces (`q_recursive`, a latent continuation policy) exist.5. **Richer features.** Mean-pooled PaliGemma is the root constraint. Patch tokens or an explicitly action-conditioned encoder would change the ceiling rather than work around it.
What is NOT worth repeating: action-contrastive weight sweeps, latent width,recursion depth, hop length, and AWR pool choice. All were measured and none movesthe action win rate off ~0.57.195842af1aa0e0854934b1fbf67f88a2cd6df850e123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737# RSM + importance-sampled OPE on the LIBERO-10 rollout corpus
Goal: learn an occupancy critic on the pi0.5 LIBERO-10 rollout corpus (43,135episodes, ~49.5% success), evaluate a target policy off-policy with theimportance-sampling correction, and distil a policy that beats behaviour cloning.
## Why this corpus and not the demos
The smolvla RSM critic was fit on demonstrations only. Its AWR extraction was anull result for a mechanical reason recorded in `rsm_vla/smolvla_rsm/README.md`:the mean absolute advantage was **0.019**, because a BC actor that imitates thedemos scores its own action the same as the demo action. Half of this corpus isfailure, so the advantage has real spread.
## Pipeline
| stage | file | what it produces ||---|---|---|| pack | `pack.py` | flat memmap cache from the per-episode npz corpus || critic | `train_rsm.py` | reward-predictive latent + action-conditioned occupancy || OPE | `is_ope.py`, `run_ope.py` | ratio nets, endpoint weight, recursive Q, gate || improvement | `awr.py` | advantage-weighted regression, looped with re-fitted ratios |
## Tricks carried over from `main` (ogbench_unified_rsm)
Taken from `RECIPE.md` and `notes/COLLAPSE_ANALYSIS.md`:
* train over a **beta band**, not one discount, with Fourier features on the log-horizon* **residual** successor, normalised per dimension by the dataset RMS of the residual* **EMA target encoder** supplies the future target, with a variance floor against latent collapse* condition on the action chunk and the task **equally**, concat plus FiLM* keep recursion **shallow** (2 hops here), and never prune mid checkpoints
Deliberately not carried over: the goal-ball arrival likelihood. LIBERO has noprivileged success ball in this latent, so the read-out is a learned rewarddecoder, which is what the image branch of `CLAUDE.md` requires anyway.
The collapse analysis' central lesson drives the diagnostics: a value that ranksSTATES but cannot rank ACTIONS shows flat batch losses and then falls off acliff in closed loop. So the headline validation metric here is the **action gap**,Q on the logged chunk minus Q on a foreign chunk at the same state, not thestate-level success AUC.
## The importance-sampling correction
The behaviour policy is a flow model sampled as an SDE at noise 0.5 and has **notractable density**, which is open question 2 in the notes. We never ask for one:
1. a classifier separates a logged chunk from a chunk sampled from the target policy at the same state, and its logit is `log pi/mu` on balanced classes;2. the chunk product runs over the interior decisions of a beta-hop only, which with a 10-action chunk is ~5 factors per hop rather than ~50;3. that product is regressed onto the endpoint under squared loss, whose minimizer is `E[W | endpoint] = d^pi_beta / d^mu_beta`, the only form usable at inference because the occupancy model emits endpoints and not actions;4. the recursive read multiplies endpoint weights along hops and self-normalises.
Decision-point ratios are prefix-summed once per ratio fit, so the chunk productis an O(1) lookup rather than one forward pass per interior decision.
## Data notes
* `task_index` is 0 in every episode of this corpus. The producer that caused it is already fixed upstream; the packer takes ids from the canonical benchmark order in `09052026_lib10_tasks.txt` and refuses to run on a task directory that is not in that list.* Failed episodes are all exactly 520 frames while successes end early, so episode length nearly determines the outcome. Any label built from "frames remaining" leaks it. The reward label is therefore defined on terminal states of successful episodes, and action ranking is the headline metric.
## Findings so far (dev cache: 2,350 episodes, 954k frames, 50% success)
### The critic learns states well and actions weakly
Reward AUC 0.99, occupancy loss 0.27 -> 0.13, state AUC 0.50 -> 0.66 over 16k steps.The pooled action win rate never left chance in eight checkpoints.
### The action-ranking metric has to use an ON-SUPPORT alternative
Comparing Q on the logged chunk against a chunk permuted across the whole batchcompares against an action from a *different task*. Once the successor isaction-conditioned that lands off-manifold, and the frozen reward decoder scoresoff-manifold latents arbitrarily -- the win rate fell to 0.361, i.e. the critic"preferred" the off-support action 2 times in 3. The same bug was latent in thesweep, whose recursion originally used an untrained continuation head.
With a within-task alternative and 8,192 pairs, the base critic ranks actionsabove chance near the goal: 0.61 mean near-terminal win, vs a cross-task controlpinned at 0.47-0.52 in all twelve cells.
### Recursion depth costs action signal; longer single hops do not
Base arm, near-terminal win pooled over four discounts:
| depth | mean win | n | 95% CI ||---|---|---|---|| 1 | 0.630 | ~4000 | [0.615, 0.645] || 2 | 0.608 | ~4000 | [0.592, 0.623] || 3 | 0.580 | ~3000 | [0.562, 0.598] |
The query action conditions only the first hop, so each extra hop hands more ofthe trajectory to the continuation policy. Meanwhile reach at depth 1 grows from25 to 200 frames as beta goes 0.96 -> 0.995 with the win rate flat at 0.61-0.64.**A single long hop dominates stacked short hops here** -- but only because theoccupancy was trained on a beta BAND covering the query horizon. Recursion earnsits place when composing *beyond* the trained band, which is not what this tested.
### The action-contrastive term: better actions, worse states, and an artifact
At weight 1.0 it reaches its own objective (contrastive loss 0.68 -> 0.39) andranks near-terminal actions better (0.667 vs 0.609 over 12,000 pairs), but stateAUC drops 0.66 -> 0.59 and the occupancy loss stalls.
It also shows a **perfect depth-parity artifact**: pooled win 0.460 / 0.617 /0.542 at depths 1 / 2 / 3, with the value gap negative at odd depth and positiveat even depth in 12 of 12 cells. The base arm is flat at 0.505 for every depth.Unexplained; not built on.
### Contrastive weight: 0.1 is free, 1.0 is destructive
| arm | w_actcon | state AUC | occupancy loss ||---|---|---|---|| base | 0 | 0.660 | 0.132 || actcon01 | 0.1 | **0.676** | 0.133 || actcon | 1.0 | 0.587 | 0.175 |
The damage at 1.0 is an over-weighting artifact, not something inherent to thecontrastive idea. The 1.0 arm is also the one carrying the unexplaineddepth-parity behaviour, so treat it as suspect.
### The importance-sampling correction FAILED its null control
Both gates use the same critic and differ only in whether the target policy isgenuinely different from the behaviour policy.
| metric | signal (pi = BC on successes) | null (pi = BC on all ~ mu) ||---|---|---|| ratio classifier accuracy | 1.000 | 0.999 || raw `E_mu[W]` (must be 1.0) | 0.181 | 0.181 || calibration factor | x5.229 | x5.238 || weight ESS | 0.563 | 0.559 || corr(endpoint w, chunk W) | 0.432 | 0.434 || relative value shift from IS | 0.1925 | 0.1842 || success AUC change | +0.0019 | -0.0054 |
Identical to within noise. The correction shifts values ~19% whether or notthere is a policy difference to correct, and never improves discrimination.
**Cause, and it is an implementation error not a property of the method:** thetarget policy was a diagonal Gaussian while the behaviour policy is a flowsampled as an SDE. The classifier reached 100% accuracy by recognising theSAMPLER, not the policy, so `log pi/mu` was a parametric-family artifact. This isopen question 2 of the notes -- a likelihood-free ratio only works if bothpolicies come from the same family, else the classifier solves the easier problem.
Note how well the signal gate looked in isolation: weights calibrated to 1.016,ESS 0.56, and the best success AUC in the run (0.6645). Without the null controlthat would have been reported as a working correction.
**Fix:** `FlowPolicy` in `model.py` -- a flow-matching target policy that matchesthe behaviour family. AWR weights the per-sample flow-matching loss in place of alog-density. The fix is confirmed only if classifier accuracy drops below 1.0 ANDthe null gate moves to `E_mu[W]` near 1 while the signal gate does not.
### The residual cause is the collection noise, not just the family
Same critic, same null gate, only the ratio estimator changes:
| configuration | classifier acc | `E_mu[W]` (must be 1.0) ||---|---|---|| Gaussian policy, no smoothing | 0.999 | 0.181 || flow policy, no smoothing | 0.98 | 0.184 || flow policy + per-dim smoothing (0.5) | 0.934 | 0.219 |
Matching the family cut classifier confidence 20x (bce 0.0035 -> 0.076) and moved`E_mu[W]` **not at all**. The corpus was collected with pi0.5 flow **SDE noise0.5** deliberately injected for exploration; any policy fit to that data withoutthe same dispersion stays distinguishable from it. Exploration noise atcollection time is exactly what makes the behaviour distribution broad, andbreadth is what makes a target policy trivially separable from it.
Across 3 critics and 2 policy families the correction consistently shifts values18-26% and consistently fails to improve what the values are for:
| critic / policy | rel value shift | success AUC with IS | without IS ||---|---|---|---|| base / gaussian, signal | 0.192 | 0.6645 | 0.6626 || base / gaussian, null | 0.184 | 0.6577 | 0.6631 || actcon / flow, signal | 0.256 | 0.5741 | 0.5768 |
### Smoothing helps the diagnostics and not the estimator
Null gate, where a correct weight must do NOTHING:
| configuration | acc | `E_mu[W]` | weight ESS | rel value shift | AUC change ||---|---|---|---|---|---|| gaussian, no smoothing | 0.999 | 0.181 | 0.559 | 0.184 | -0.005 || flow, no smoothing | 0.98 | 0.184 | - | - | - || flow + smoothing 0.5 | 0.934 | 0.219 | 0.625 | 0.219 | **+0.018** |
Smoothing did what it was meant to (acc 0.999 -> 0.934, ESS 0.559 -> 0.625) anddid not fix the estimator. The clearest tell is the **+0.018 AUC gain in the NULLgate**: a correction that improves discrimination when there is nothing tocorrect is fitting something other than the policy difference. The endpointregression also went unstable under smoothing (loss 0.11 -> 5.73 at step 3000).
**Verdict: across 3 critics x 2 policy families x 2 smoothing levels, theper-decision importance weight fails its null control every time.**
### AWR made the policy WORSE, and the mechanism is dilution
| metric | pi_0 (cloned on successes) | after 1 AWR round ||---|---|---|| flow loss on SUCCESS chunks | 0.1706 | 0.1708 || flow loss on FAILURE chunks | 0.1876 | **0.1713** || separation gap | **0.0170** | **0.00046** |
Round 2 is worse still: success loss 0.1770 (up from 0.1706), failure loss 0.1672(down from 0.1876), gap **-0.0098**. The gap declines monotonically and CROSSESZERO -- after two rounds the policy fits FAILED chunks better than successfulones. Iterating the loop does not merely fail to improve the policy, itprogressively inverts it.
The policy did not improve on successes; it got much better at fitting FAILURES.`awr_step` samples from ALL training episodes and relies on the advantage todownweight the bad ones. With an advantage this weak (the critic ranks actions at0.608 near the goal and at chance beyond one hop) that reduces to behaviourcloning on the full half-failure corpus, undoing the success filtering that madepi_0 good. It is the offline echo of this lane's own `bcall` 0.108 vs `bcdemos`0.584.
Normalised, the advantage is **not** larger than the demonstration-only baselineit was supposed to beat: 0.0160-0.0221 in probability units vs the smolvla nullresult's 0.0190. The raw printout reads 1.60-2.21 only because Q is divided by(1-gamma). **The premise that failure data would give AWR a bigger signal is notsupported by this measurement.**
**The correction is NOT what breaks the loop.** Turning it off changes nothingqualitative:
| arm | pi_0 gap | after round 1 | change ||---|---|---|---|| IS on | 0.0170 | 0.00046 | -97% || IS off | 0.0089 | 0.00111 | -87% |
Both collapse. So the loop failure and the IS failure are INDEPENDENT negatives:the weights never tracked the policy difference (they fail their null control),and separately the advantage is too weak to stop AWR diluting a success-clonedpolicy with the failure half of the corpus.
**Caveat on the AWR arms:** `awr.py` seeded numpy but not torch, so the IS-on andIS-off arms started from different policies (pi_0 gaps 0.0170 vs 0.0089). Eacharm's trajectory relative to its OWN baseline is valid; the absolute numbers arenot matched across arms. Fixed for future runs.
### FINAL: no policy-extraction win. All three AWR arms lose ground.
Separation gap between success and failure chunks (higher is better):
| arm | pi_0 | round 1 | round 2 ||---|---|---|---|| IS on, pool=all | +0.0170 | +0.00046 | **-0.0098** || IS off, pool=all | +0.0089 | +0.00111 | **-0.0082** || IS off, pool=succ (dilution control) | +0.0211 | +0.0166 | **+0.0054** |
Two of three INVERT: the policy ends up fitting FAILED chunks better thansuccessful ones. Restricting the pool slows the collapse a lot but still loses3/4 of the starting gap. **None improves on its own starting point.** Theadvantage from this critic is too weak to drive improvement even when it cannotdilute.
### FINAL: the smoothed IS pair is backwards
| gate | rel value shift | AUC with IS | AUC without ||---|---|---|---|| NULL (pi ~ mu, should do nothing) | 0.219 | 0.6675 | 0.6499 || SIGNAL (pi better, should help) | 0.247 | 0.6510 | **0.6557** |
It helps +0.018 where it should do nothing and hurts -0.005 where it shouldhelp. Inverted. That closes the question.
## Status
COMPLETE. Critic works; every off-policy result is negative. See the two FINALsections above. Raw artifacts in `results/`; runs under`/data/pulkitag/users/rli14/rsm_libero_runs/`.
## FINAL RESULTS
### The AWR loop WORKS once the action chunk spans the hop it conditions
Every failing arm conditioned the occupancy on 10 frames of action while asking itto predict a 50-frame hop, so 4/5 of the transition came from actions the criticnever saw. A model-free probe shows the action's contribution to predicting successrises monotonically with sequence length: +0.0237 (10 frames) -> +0.0627 (100).
With `--chunk 100` spanning a 100-frame hop:
| critic | pooled action win | near-terminal | state AUC ||---|---|---|---|| chunk=100, depth 2 | **0.580** [0.569,0.591] | **0.73** | 0.698 || chunk=10, depth 2 | 0.519 | 0.60 | 0.664 |
**Depth 2 beats depth 1** (0.580 vs 0.547), reversing the earlier "depth hurts"result and supporting the 2-3 hop intuition once the chunk spans the hop.
| AWR arm | pi_0 | round 1 | round 2 ||---|---|---|---|| **chunk=100, pool=succ** | **+0.0671** | **+0.0791** | **+0.0825** || chunk=10, IS on | +0.0170 | +0.00046 | -0.0098 || chunk=10, IS off | +0.0089 | +0.00111 | -0.0082 || chunk=10, pool=succ | +0.0211 | +0.0166 | +0.0054 |
Advantage is 0.068-0.080 in probability units vs the demo-only smolvla nullresult's 0.019 -- ~4x more. The original premise holds at the RIGHT granularity.
### ROOT CAUSE of every IS failure: the classifier measures NETWORK IDENTITY
Six confounds were found and removed (gaussian-vs-flow family mismatch, missingsmoothing, ratio scored over the conditioning window instead of decisions, targetpolicy at the wrong granularity, and two shape/order bugs). Overlap improved everytime -- classifier bce 0.0035 -> 0.286 -- and the weights still collapsed.
The identity control explains why. Train two BC policies on **identical data** withdifferent seeds; they are the SAME policy, so a ratio classifier must be at chance:
| comparison | classifier acc ||---|---|| two policies, same data, different seed | **0.945-0.977** || target policy vs behaviour policy | 0.941 |
Identical. The classifier detects **which network generated a sample** -- samplerartifacts and generator fingerprints -- not a density difference. Every ratio itproduced was meaningless. `E_mu[W]` sat at 0.13-0.22 in all six configurationsregardless of critic, family, smoothing or granularity, and the final clean nullgate applied a **0.537 relative value shift where zero is correct**.
**This RETRACTS the intermediate conclusion** that flow SDE noise 0.5 at collectionmade the policies too separable and that the fix was data collection. Theseparability was never between policies; less injected noise would not have helped.
**Actual cause:** discriminative density-ratio estimation does not work oncontinuous high-dimensional action chunks in this setup. It is an ESTIMATORproperty, not a data property. The notes' likelihood-free route -- classify insteadof requiring normalised densities -- is not viable here. A working correction needsa genuine likelihood ratio (tractable densities on both sides) or a correction thatdoes not route through sample classification.
### The likelihood ratio FIXES the estimator; the product length still kills it
Replacing the classifier with a genuine `pi/mu_hat` (two tractable Gaussians, onefit to the logged actions by maximum likelihood, densities evaluated AT the loggedaction so nothing has to tell samples apart):
| route | E_mu[w] | median w | ESS | null-gate value shift ||---|---|---|---|---|| classifier | 0.156 | - | 0.52 | 0.537 || **likelihood** | **1.756** | **0.974** | 0.526 | 0.607 |
The per-decision weight is now RIGHT IN THE BULK (median 0.974 vs a required 1.0);the classifier's was wrong everywhere. But the null gate still fails, and theendpoint regression needed a x10 calibration.
**Cause is arithmetic.** At `beta_q=0.99` a hop spans 100 frames = **10 policydecisions**, so W is a product of 10 factors each with p95 = 4.48. That product iscatastrophically heavy-tailed however well-calibrated each factor is.
This is precisely the variance argument in the notes, and the real case for myopicbeta: keep each hop SHORT so the product has few factors, then recurse. The tensionis now measured on both sides:
* action signal needs LONG action windows (+0.0237 at 10 frames -> +0.0627 at 100)* estimable weights need SHORT hops (1 decision per hop, not 10)
**Untested middle ground:** chunk = hop = ~25 frames, i.e. ~2.5 decisions perproduct, where the probe still shows +0.0334 action contribution (40% above the10-frame case). That is the configuration most likely to satisfy both, and it isthe obvious next experiment.
## What would come next
1. Run the loop **without** the correction: `--chunk 100 --awr-pool succ --use-is 0`. This is the only configuration that improves the policy monotonically.1b. To make IS viable, test chunk = hop = ~25 frames (~2.5 decisions per product) with `--ratio-mode likelihood`. Both requirements are measured; this is where they might overlap.2. Condition the occupancy on an action window that **spans its hop** -- the single highest-impact setting found.3. For IS, replace the classifier with a genuine likelihood ratio, or drop it.4. Closed-loop LIBERO eval is NOT run here. Nothing in this file supports a claim of beating BC on demos (0.584 +- 0.025 step-matched in the lane).
## Closed-loop results, 2026-09-10 (MIT)
### The control that was missing
The lane's own bcdemos policy, run through the lane's own evaluator on thismachine, scores **0.20 / 0.20 / 0.70 on tasks 0-2 (11/30 = 0.367)** before slurmpreempted it. The environment, EGL rendering, pi0.5 encoder, initial states andsuccess detection here are therefore sound, and any 0% is ours to fix. Two thingswere needed to get it to run: `FL15_TASKS` must name the 10 libero_10 tasks (itdefaults to a 15-task list and the head's task embedding then refuses thecheckpoint), and the evaluation-protocol freeze needs a fresh output directory.
### What actually caused the 0% across every arm
The policy was conditioned on the critic's 264-d encoder output. That encoder istrained to predict REWARD, so it keeps what separates success from failure anddiscards what an action head needs. On a trained arm the policy beat apredict-the-mean action baseline by only 14% in MSE (0.1456 vs 0.1701) with abiased gripper channel. The policy now reads the full 4104-d observation; onlythe advantage comes from the critic.
### Whitening the policy input breaks the closed loop
Four runs, one consistent pattern:
| policy input | head | steps | pooled SR ||---|---|---|---|| raw, chunk 25 | FiLM | 60k | 0.040 || **center**, chunk 10 | FiLM | 60k | **0.110** || z-score, chunk 10 | FiLM | 60k | 0.000 || z-score, chunk 10 | concat | 120k | 0.000 |
The z-scored arm had the BEST offline fit of any arm (sampled action MSE 0.0374against 0.042 for the others) and still scored 0/100. Per-dim std on this corpusspans 0.048 to 3.675, so whitening shrinks the few high-variance directions by upto 34x relative to the median and flattens the spectrum. Offline the networksimply relearns its weights; at deployment the small online-vs-cache featurisationdifference is then comparable to the signal that survives. Centering removes theuninformative common mode (mean vector norm 51.1 against a per-frame deviation of9.0) without flattening the spectrum, and is what the arms now use.
### Not the cause, established by measurement
* **Featurisation.** Our encoder reproduces the demo latent cache at cos 0.9999 offline and 0.9903 from live env frames; demo and rollout latents agree at 0.991; env obs shares the h5 orientation (pixel MAE 13.9 as-is vs 101 flipped), so the evaluator's ROT180 is right. The previously reported 0.6015 mismatch does not reproduce.* **Policy architecture.** Their concatenation head, their loader and their loss, trained here for 20k steps, reach val_mse 0.0495 -- the same as our pipeline at the same budget (0.0471). Their published 0.0032 is reachable only with their `--train-all` flag, which puts the validation demos into training.
### Bugs fixed (each alone produced a zero)
1. `import_file` given an absolute path -- ValueError before any env was built.2. The featuriser imported from the producer, which does not define it.3. `RawFeat` left on CPU once it carried a buffer.4. `offline_score` indexed an empty failure pool on a demos-only cache.5. `bc_arm` scored before saving, discarding a finished 120k-step run.6. Launchers ended with `echo`, so crashed jobs exited 0 and every `--dependency=afterok` eval ran against a checkpoint that was never written.
## Results with the FIXED evaluator (2026-09-11)
All runs: 10 tasks x 10 initial states, max 520 steps, chunk 10, executed 10.Throughput = pooled SR * max_steps / mean_steps.
| arm | succ/n | pooled SR | thr (succ) | thr (all) ||---|---|---|---|---|| reference bcdemos, **our** harness | 53/100 | 0.530 | 0.946 | 0.691 || reference bcdemos, **its own** harness | 46/100 | 0.460 | 0.888 | 0.591 || **A: BC on demos (ours)** | **58/100** | **0.580** | **1.082** | **0.794** || B: BC on successful rollouts | 47/100 | 0.470 | 0.831 | 0.591 || C: IQL critic + AWR | 38/100 | 0.380 | 0.607 | 0.443 || ablation: A with z-scored input | 1/100 | 0.010 | 0.014 | 0.010 |
The harness control (0.530 ours vs 0.460 theirs, same weights) confirms thisevaluator is equivalent to the lane's; the 0.07 spread is seed variation atn=100.
### The whitening ablation is now clean
A trained on demonstrations, center-scaled, scores 0.580. The identical run withper-dim z-scored input scores 0.010. Same data, same head, same budget, sameseed -- only the input scaling differs. Whitening flattens a spectrum whoseper-dim std spans 0.048 to 3.675, shrinking the informative high-variancedirections by up to 34x relative to the median.
### AWR currently HURTS
C starts from a BC-on-successes clone (0.470) and IQL-weighted AWR takes it to0.380. Both critic arms initialised on successes alone, which starts them 0.11below the BC-on-demos bar they must clear. `--init-pool demos_succ` now lets botharms start from demonstrations plus successful rollouts, so the comparisonmeasures the critic rather than the initialisation.
## Matched four-arm comparison (2026-09-11, demonstration statistics)
Every arm: full_demo cache, demo-pool feature statistics, center scaling, theconcatenation flow head, chunk 10, batch 1024, 120k steps, seed 0. The criticarms start from the SAME behaviour clone as arm A, so the comparison isolates theimprovement signal.
| arm | succ/n | SR | thr succ / all ||---|---|---|---|| **A: BC on demonstrations** | **63/100** | **0.630** | 1.183 / 0.788 || B: BC on successful rollouts | 48/100 | 0.480 | 0.807 / 0.596 || C: IQL critic + AWR (soft) | 49/100 | 0.490 | 0.839 / 0.615 || D: RSM critic + AWR (soft, pessimism 2.0) | running | | |
Reference: the lane's own bcdemos policy scores 0.530 through this harness and0.460 through its own.
### Two normalisation findings worth keeping
| policy input | SR ||---|---|| centred with DEMONSTRATION statistics | 0.630 || centred with rollout-dominated statistics | 0.430 || per-dim z-scored | 0.010 |
Centring matters (the mean feature vector has norm 51.1 against a per-framedeviation of 9.0), WHICH frames the statistics come from matters (the rolloutcorpus is a noisier, half-failing distribution), and whitening is catastrophic(per-dim std spans 0.048 to 3.675, so it shrinks the informative directions up to34x relative to the median).
## The critic is the blocker, and it is upstream of the flow
Held-out within-task action win rate -- how often Q ranks the action actuallytaken above another action from the same task -- across every intervention tried:
| critic | best win rate ||---|---|| chunk 10, w_actcon 0.5 (the one deployed) | 0.568 || w_actcon 1.0, d_z 512 | 0.532 || w_actcon 2.0 | 0.533 || inverse dynamics 1.0 | 0.445 || inverse dynamics 5.0 | 0.534 || deployed critic + pessimism 2.0 (probe) | 0.570 |
All peak between step 1000 and 2000 and then decay below chance while reward AUCstays above 0.95. The state value is excellent and the action ranking is nearcoin-flip.
The cause is upstream of the occupancy model. This lane measured that over 5frames the executed action correlates with the proprio delta at |r| up to 0.98but with the visual-latent delta at only 0.49 (mean 0.10): a mean-pooledPaliGemma embedding barely resolves the motion a 10-frame chunk produces. Raisingthe action-contrastive weight asks the flow to use information the latent doesnot carry, which is why 2.0 was worse than 0.5.
### Every downstream use of that critic fails
| use | from | to ||---|---|---|| AWR, hard weight (IQL) | 0.470 | 0.380 || AWR, hard weight (RSM) round 1 | 0.470 | 0.400 || AWR, hard weight (RSM) round 2 | 0.470 | 0.290 || AWR, soft weight (IQL) | 0.630 | 0.490 || Q-filter, 16 candidates (RSM) | 0.630 | 0.510 |
The hard-weight collapse was a real bug and is fixed: with advantage std ~8 andbeta 3 the exponent saturates, so the "soft" weight became a hard filter on thesign of a 0.568-accurate critic. Standardising the advantage recovers most of theloss (IQL 0.380 -> 0.490) but does not turn a coin-flip critic into animprovement.
## Where RSM stands (2026-09-11)
Matched: full_demo cache, demo statistics, center scaling, concatenation flowhead, chunk 10, batch 1024, 120k steps, seed 0. C and D start from the SAMEdemonstration clone as A.
| arm | succ/n | SR | thr succ / all ||---|---|---|---|| **A: BC on demonstrations** | **63/100** | **0.630** | 1.183 / 0.788 || C: IQL + AWR (soft, pool = successes) | 49/100 | 0.490 | 0.839 / 0.615 || B: BC on successful rollouts | 48/100 | 0.480 | 0.807 / 0.596 || RSM Q-filter, 16 candidates, on A | 51/100 | 0.510 | - || D: RSM + AWR (soft, pessimism 2.0, pool = successes) | 41/100 | 0.410 | 0.802 / 0.513 |
**RSM does not yet beat the baselines.** Both critic arms move the policy DOWNfrom the 0.630 clone they start at, and RSM moves it further down than IQL.
Chunk 100 was tried because it is the only setting where the critic ranks actionswell (win 0.613 against 0.568 at chunk 10, confirming that over a 10-frame hop theaction barely moves the success probability). It does not rescue the result: BC atchunk 100 fits far worse (sampled action MSE 0.114 against 0.049) and scores0.00-0.20 per task over the first six, so the better critic sits on top of a muchweaker policy.
### What would have to change
The critic ranks actions at 0.57 and that ceiling survived every intervention:action-contrastive weight 0.5/1.0/2.0, latent width 512, inverse dynamics 1.0/5.0,particle pessimism, and chunk/hop length. Reward AUC stays above 0.95 throughout,so the state value is strong and only the ACTION channel is missing. The measuredcause is upstream: over 5 frames the executed action correlates with the propriodelta at |r| up to 0.98 but with the visual latent delta at only 0.49 (mean 0.10).Until the latent carries the action, no read-out on top of it can rank actions,and every consumer of that ranking -- AWR in two flavours, Q-filtering -- lowers agood policy instead of raising it.
## FINAL: all arms, fixed evaluator (2026-09-11)
10 tasks x 10 initial states, 520-step cap, chunk 10 executed 10. Every arm usesthe same cache, demonstration statistics, center scaling, concatenation flow head,batch 1024, 120k steps, seed 0. Both critic arms start from the SAME demonstrationclone as arm A, so the only difference is the improvement signal.
| arm | succ/n | SR | thr succ | thr all ||---|---|---|---|---|| **A: BC on demonstrations** | **63/100** | **0.630** | 1.132 | 0.874 || reference bcdemos, our harness | 53/100 | 0.530 | 0.946 | 0.691 || RSM Q-filter, 16 candidates | 51/100 | 0.510 | 0.951 | 0.668 || C: IQL + AWR (demo pool) | 50/100 | 0.500 | 0.963 | 0.658 || C: IQL + AWR (success pool) | 49/100 | 0.490 | 0.839 | 0.615 || B: BC on successful rollouts | 48/100 | 0.480 | 0.807 | 0.596 || D: RSM + AWR (demo pool) | 43/100 | 0.430 | 0.758 | 0.528 || D: RSM + AWR (success pool) | 41/100 | 0.410 | 0.802 | 0.513 |
**The RSM recipe does not beat BC-on-demonstrations, BC-on-successes, or IQLextraction on this dataset.** Behaviour cloning on the 500 demonstrations winsoutright, and it also beats the published reference through the same harness.
### The search that was run
Critic: action-contrastive weight 0.5 / 1.0 / 2.0; latent width 256 / 512;inverse dynamics 1.0 / 5.0; chunk and hop 10 / 100; particle pessimism 0 to 4.Extraction: AWR with hard and standardised weights, over the all / success /demonstration pools, with and without the importance-sampling correction, one andtwo rounds, plus deployment-time Q-filtering over 4 and 16 candidates.
### The single blocker
Held-out within-task action win rate never exceeds 0.57 at chunk 10 (0.613 atchunk 100), while reward AUC stays above 0.95. The state value is strong; theaction channel is missing, and it is missing upstream of the occupancy model: over5 frames the executed action correlates with the proprio delta at |r| up to 0.98but with the visual-latent delta at only 0.49 (mean 0.10). A mean-pooled PaliGemmaembedding does not resolve what a 10-frame chunk does. Every consumer of thatranking therefore lowers a good policy rather than raising it.
The chunk-100 result is the constructive part: lengthening the action window andthe hop is the one intervention that moved the win rate (0.568 -> 0.613), whichsays the horizon, not the read-out, is what starves the signal. Making thatusable needs a policy that is still accurate at a 100-frame chunk; ours loses moreto the longer chunk (sampled action MSE 0.114 vs 0.049) than the critic gains.
### The ceiling is the ACTION WINDOW, not the hop
Held-out within-task action win rate, chunk 10 held fixed while the hop varies:
| chunk | hop (beta_q) | best win ||---|---|---|| 10 | 0.90 (~10 frames) | 0.568 || 10 | 0.97 (~33 frames) | 0.558 || 10 | 0.99 (~100 frames) | 0.551 || 100 | 0.99 (~100 frames) | **0.613** |
Lengthening the hop does nothing; lengthening the ACTION WINDOW is what moves it.A 10-frame chunk simply does not determine much about the future on this task, sothe ranking ceiling at chunk 10 is a property of the data rather than a modellingfailure. And the policy trades the other way: a chunk-100 policy loses more to thelonger chunk (sampled action MSE 0.114 against 0.049) than the critic gains.
With this featurisation you can have an accurate policy or a discriminativecritic, not both. That is the finding, and it is what any future attempt on thiscorpus has to break.
## PARL with the RSM value, and the experiment that settles it
PARL: sample N=32 action chunks from a proposal policy, rank by the RSM Q, keepthe argmax, distill into a fresh head. The recipe's own precondition is that theproposal's samples must be DIVERSE, because ranking N copies of one action cannotimprove anything. Measured proposal action std against the data's 0.421:
| proposal | action std | ratio ||---|---|---|| BC on demos, 120k steps, best-MSE checkpoint | 0.029 | 0.070 || BC on demos, 20k steps | 0.053 | 0.126 || the same, sampling temperature 1.5 | 0.103 | 0.244 || the same, sampling temperature 2.5 | 0.222 | 0.527 |
Selecting a checkpoint by best held-out sampled reconstruction MSE picks the mostmean-collapsed one, so the earlier Q-filter run was ranking near-identicalcandidates. That is fixed above.
### The result
| proposal diversity | PARL SR ||---|---|| 0.070 (120k clone) | 0.350 || 0.126 | 0.440 || 0.244 | 0.230 || 0.527 | **0.000** |
Success falls monotonically as the critic is given more freedom to choose. Everyother factor is fixed: same critic, same N, same distillation, same evaluator.The only variable is how different the candidates are. If the value functioncarried signal, widening the candidate set would help; it destroys the policyinstead, so the ranking is not weak, it is pointed the wrong way. A collapsedproposal scores near BC simply because selection can do little harm when all 32candidates are the same action.
This is the cleanest isolation of the critic in this lane, and it agrees with theoffline probe: held-out within-task action win rate 0.568, barely above chance,while reward AUC stays above 0.95.
Chunk 30 closes the last alternative: BC 0.440, RSM + AWR 0.160, with a criticthat ranks at 0.597. Across all three action windows the same pattern holds.
| chunk | BC on demos | RSM extraction | critic win rate ||---|---|---|---|| 10 | 0.630 | 0.430 | 0.568 || 30 | 0.440 | 0.160 | 0.597 || 100 | 0.080 | 0.020 | 0.613 |
A better-ranking critic goes with a worse policy at every size, and the product isworse than plain behaviour cloning in all three.
### PARL grid: both knobs point the same way
| selection rule | T=1.5 (diversity 0.244) | T=2.5 (diversity 0.527) ||---|---|---|| Q minus 2 particle std | 0.230 | 0.000 || pure expected success | 0.130 | 0.010 |
Two independent controls, same conclusion. Giving the value more candidates tochoose among makes it worse, and removing the variance penalty -- so thatselection follows the raw value rather than staying near the mode -- makes itworse again. The penalty was masking the problem by keeping choices close to theproposal's mode, not by adding information.
The RSM value's preference over actions is anti-correlated with action quality onthis corpus. That is a stronger and more useful statement than "the critic isweak", and it is what the offline probe was too blunt to show: a 0.568 win rateagainst dataset alternatives is dominated by on-support versus off-support, whichsays nothing about ranking a policy's own candidates.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Is the label wrong, or did the replay diverge? These are different claims.
Replaying logged actions tests reproducibility; the corpus is documented as NOTbit-reproducible, so a replay failure does not by itself prove the label is wrong.
This does the direct test instead and needs no replay: load the episode's LOGGED FINALsim_state, restore the simulator to it, and evaluate LIBERO's own goal predicate.If the predicate is false in the very state the episode ended in, while is_success=1,the label is wrong -- no nondeterminism can explain it.
Per-conjunct results are also recorded, which measures how much of a compound task a"successful" episode actually completed."""import argparse, io, os, re, sys, base64import numpy as npsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
def src_parquet(ep_src): m = PAT.search(str(ep_src)) if not m: return None t, b, i, idx = m.groups() p = (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") return p if os.path.exists(p) else None
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True); ap.add_argument("--task", type=int, required=True) ap.add_argument("--out", required=True); ap.add_argument("--limit", type=int, default=0) ap.add_argument("--save-img", type=int, default=12, help="keep this many final frames of label errors") args = ap.parse_args()
import pyarrow.parquet as pq from libero.libero import benchmark, get_libero_path from libero.libero.envs.env_wrapper import ControlEnv from pathlib import Path
m = np.load(f"{args.cache}/meta.npz", allow_pickle=True) d, s, task = m["ep_demo"].astype(bool), m["ep_success"].astype(bool), m["ep_task"] todo = np.where((task == args.task) & s & ~d)[0] if args.limit: todo = todo[:args.limit]
bench = benchmark.get_benchmark_dict()["libero_10"]() t = bench.get_task(args.task) env = ControlEnv(bddl_file_name=str(Path(get_libero_path("bddl_files")) / t.problem_folder / t.bddl_file), has_renderer=False, has_offscreen_renderer=False, use_camera_obs=False) env.reset() goal = env.env.parsed_problem["goal_state"] print(f"[audit] task {args.task}: {len(todo)} logged successes, goal={goal}", flush=True)
rows, imgs = [], [] for n, e in enumerate(todo): p = src_parquet(m["ep_src"][e]) if p is None: rows.append((int(e), -1, -1, 0)); continue tb = pq.read_table(p, columns=["sim_state", "is_success", "image"]) last = tb.num_rows - 1 st = np.asarray(tb["sim_state"][last].as_py(), np.float64) env.env.sim.set_state_from_flattened(st) env.env.sim.forward() conj = [bool(env.env._eval_predicate(g)) for g in goal] ok = all(conj) rows.append((int(e), int(ok), int(sum(conj)), len(conj))) if not ok and len(imgs) < args.save_img: imgs.append((int(e), int(sum(conj)), len(conj), base64.b64encode(tb["image"][last].as_py()["bytes"]).decode())) if (n + 1) % 50 == 0: g = [r for r in rows if r[1] >= 0] print(f"[audit] {n+1}/{len(todo)} goal-holds-at-logged-end " f"{sum(r[1] for r in g)}/{len(g)}", flush=True) env.close() a = np.array([r for r in rows if r[1] >= 0]) np.savez_compressed(args.out, rows=np.array(rows), task=args.task, imgs=np.array([i[3] for i in imgs], dtype=object), img_ep=np.array([i[0] for i in imgs]), img_sat=np.array([[i[1], i[2]] for i in imgs])) if len(a): holds = int(a[:, 1].sum()); tot = len(a) print(f"[audit] task {args.task}: goal predicate TRUE at the logged final state " f"for {holds}/{tot} ({holds/tot:.3f}) of logged successes", flush=True) bad = a[a[:, 1] == 0] if len(bad): print(f"[audit] of the {len(bad)} label errors, conjuncts satisfied: " f"{np.bincount(bad[:, 2], minlength=int(a[0,3])+1).tolist()} " f"(index = #subgoals met of {int(a[0,3])})", flush=True)
if __name__ == "__main__": main()1234567891011121314151617#!/bin/bash#SBATCH --job-name=audit_goal#SBATCH --account=vision-pulkitag#SBATCH --cpus-per-task=4 --mem=32G#SBATCH --array=0-9#SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%a_%A.out#SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%a_%A.errset -uo pipefailB=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationS=/data/pulkitag/users/rli14/rlinf_recap_task_expansionexport LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standardexport MUJOCO_GL=osmesa PYTHONUNBUFFERED=1OUT=/data/pulkitag/users/rli14/rsm_libero_runs/goalaudit; mkdir -p $OUT$B/venvs/rlinf-libero-eval-venv/bin/python \ /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/audit_logged_goal.py \ --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ --task $SLURM_ARRAY_TASK_ID --out $OUT/task$SLURM_ARRAY_TASK_ID.npz123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Autoresearch driver: reads the local JSON mirror, advances stages, launches the nextcells via ibm_autoresearch.sh. Idempotent (state in a JSON file); run it repeatedly."""import json, os, subprocess, sys, globsys.argv = ["x"]; sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import ibm_table as TD = "/data/pulkitag/scratch/rli14/ibm_eval_json"; ST = "/data/pulkitag/scratch/rli14/autoresearch_state.json"IB = "/proj/dmfexp/zwhong/rsm_libero"; R = f"{IB}/runs/full_r256"st = json.load(open(ST)) if os.path.exists(ST) else {}def save(): json.dump(st, open(ST, "w"), indent=1)def run(*a): return subprocess.run(["./ibm_autoresearch.sh", *a], capture_output=True, text=True, timeout=1800).stdoutcells = T.load(D)V = {k[0]: v for k, v in cells.items() if k[1] == "DL" and k[4] == "V"}plain = V.get("plain")def vs_plain(arm): if arm not in V or plain is None: return None r = T.pair(V[arm], plain); return rprint(f"V cells: {len(V)} plain={plain['sr'] if plain else None}")for arm in sorted(V): 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 ""))# ---- stage 1 -> stage 2s1 = [f"RSMb{b}d{d}{pp}" for b in (90, 95, 98) for d in (1, 2, 3) for pp in ("", "p256")]if "stage2" not in st and all(a in V for a in s1) and plain: best = max(s1, key=lambda a: (V[a]["sr"], V[a]["thr"])) b, d = best[4:6], best[7]; pp = "256" if best.endswith("p256") else "16" # RSMb<bb>d<d>[p256] print(f"stage1 complete -> best {best}; launching stage2 at {pp} particles"); os.environ["QFPART"] = pp; print(run("stage2", b, d)) st["stage2"] = {"beta": b, "depth": d, "part": pp}; save()# ---- BC checkpoint selectionif "bcsel" not in st: 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 if "policy_s120000" in out: print("BCdemo_c finished -> launching bcsel"); print(run("bcsel")); st["bcsel"] = 1; save()# ---- critic checkpoint selection on V for each finished critic run, then confirm the arg-max on A/BCB = f"{R}/qsg_f/ckpt_best.pt"; HOP = f"{R}/HOPdemo_f/policy_r1.pt"b2, d2 = (st["stage2"]["beta"], st["stage2"]["depth"]) if "stage2" in st else ("95", "3")for crun in ("qsg_bce", "qind_bce", "qsoft_f", "qsg_b90", "qsg_wide"): key = f"critsel_{crun}" if key not in st: 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() if done and done != "0": print(f"{crun} finished ({done} periodic ckpts) -> critsel on V"); print(run("critsel", crun, b2, d2)) st[key] = {"n": int(done)}; save() elif "confirmed" not in st[key]: arms = sorted([a for a in V if a.startswith(f"RSMc{crun}S")], key=lambda a: -V[a]["sr"]) if len(arms) >= st[key]["n"] and arms: step = arms[0][len(f"RSMc{crun}S"):] print(f"{crun}: V arg-max checkpoint = step {step} (SR {V[arms[0]]['sr']:.3f}); confirming on A/B x 3 seeds") 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" print(run("stage3", f"RSMc{crun}", env, "DL", f"{R}/BCdemo_f/policy_last.pt")) st[key]["confirmed"] = step; save()# ---- stage 2 -> stage 3if "stage2" in st and "stage3" not in st: b, d = st["stage2"]["beta"], st["stage2"]["depth"] 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 "")] pc = sorted([a for a in V if a.startswith("plainC")], key=lambda a: -V[a]["sr"]) if all(a in V for a in s2) and (("bcsel" in st and pc and len(pc) >= 12) or plain): top = sorted(s2, key=lambda a: -(V[a]["sr"] + 0.1 * V[a]["thr"]))[:2] bc_ckpt = f"{R}/BCdemo_c/policy_s{pc[0][6:]}.pt" if pc else f"{R}/BCdemo_f/policy_last.pt" prop = "DC" if pc else "DL" print(f"stage2 complete -> confirming {top} on A/B x3 seeds against BC ckpt {bc_ckpt}") CB = f"{R}/qsg_f/ckpt_best.pt"; HOP = f"{R}/HOPdemo_f/policy_r1.pt" pp = st["stage2"].get("part", "256") def env_for(a): x = a[len(f"RSMb{b}d{d}"):].replace("p256", "") e = f"CRITIC={CB}, HOPPOL={HOP}, QFDEPTH={d}, QFBETA=0.{b}, QFGATE=0, QFCRN=1, QFPART={pp}, QFPES=0, QFILTER=8, SELECT=argmaxq" if x == "n32": e = e.replace("QFILTER=8", "QFILTER=32") if x == "n16": e = e.replace("QFILTER=8", "QFILTER=16") if x == "q90": e = e.replace("SELECT=argmaxq", "SELECT=quantile, SELQ=0.9") if x == "q90n32": e = e.replace("SELECT=argmaxq", "SELECT=quantile, SELQ=0.9").replace("QFILTER=8", "QFILTER=32") if x == "near4": e = e.replace("SELECT=argmaxq", "SELECT=qnear, QNEARK=4") if x == "fold": e += ", QFMODE=fold" if x == "pes1": e = e.replace("QFPES=0", "QFPES=1") if x == "nocrn": e = e.replace("QFCRN=1", "QFCRN=0") if x == "cL": e = e.replace(CB, f"{R}/qsg_f/ckpt.pt") return e for a in top: print(run("stage3", a, env_for(a), prop, bc_ckpt)) print(run("stage3", "plain", "QFILTER=0", prop, bc_ckpt)) print(run("stage3", "medoid8", "SELECT=medoid, QFILTER=8, QFDEPTH=1, QFBETA=0.98, QFPES=0, QFGATE=0", prop, bc_ckpt)) st["stage3"] = {"arms": top, "bc_ckpt": bc_ckpt}; save()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""Policy improvement by advantage-weighted regression on the IS-corrected Q,and the evaluation <-> improvement loop.
A(z,A) = Q^pi(z,A) - V(z), V(z) = mean over M chunks drawn from pi itself loss = -E[ w * log pi(A_data | z) ], w = clip(exp(beta*A), 0, w_max)
Why this can carry signal where the smolvla run's could not: that critic was fiton demonstrations only, so Q(demo action) ~= Q(actor's own action) and the meanabsolute advantage was 0.019 -- no gradient. Here half the corpus is failure, sothe advantage has real spread, and the weights are additionally corrected towardpi by the endpoint ratio rather than left at the behaviour policy's value.
The loop is deliberately short (2-3 rounds). Each round re-fits the ratio nets,because the target policy has moved and a stale ratio silently evaluates thewrong policy -- the notes flag exactly this."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, jsonfrom pathlib import Pathimport numpy as npimport torch
from model import BCHead, FlowPolicyfrom data import LiberoRSMDatafrom is_ope import ( policy_features, load_critic, train_bc, train_ratio, train_endpoint_ratio, q_recursive, make_policy, policy_nll)from train_rsm import auc
def awr_step(d, enc, pol, *, rew, flow, rms, wend, args, device, steps, M=4, pfeat=None, d_policy=None, cont_pol=None): """One improvement round. Returns a NEW policy; `pol` is left untouched.
`awr_pool` controls which episodes the regression draws from. Standard AWR uses ALL data and relies on the advantage to downweight bad actions. Measured consequence when the advantage is weak: pi_0 was cloned on SUCCESSES, one AWR round over all data collapsed its success-vs-failure separation from 0.0170 to 0.00046, and the loss on FAILED chunks improved from 0.1876 to 0.1713 -- i.e. it walked the policy back toward cloning the full half-failure corpus. That is the offline echo of this lane's own bcall=0.108 vs bcdemos=0.584. `awr_pool=succ` restricts the pool so AWR can only sharpen within the slice pi_0 was fit on, which isolates dilution from genuine improvement.""" pf = enc if pfeat is None else pfeat # q_recursive rolls hops through the occupancy model and must re-draw a # continuation action at each hop CONDITIONED ON THE PREDICTED LATENT z'. # Once the extracted policy reads raw 4104-d observations it cannot be # queried there -- there is no observation for a latent the flow imagined. # `cont_pol` is a small BC policy living in the critic's latent space used # only inside the recursion; the policy AWR actually improves is `new`. roll = cont_pol if cont_pol is not None else pol new = make_policy(args, d, device, d_z=d_policy) new.load_state_dict(pol.state_dict()) opt = torch.optim.AdamW(new.parameters(), lr=1e-4, weight_decay=0.01) rng = np.random.default_rng(args.seed + 11) stats = [] _ap = getattr(args, "awr_pool", "all") for step in range(1, steps + 1): b = d.sample_frames(args.batch, rng, "train", device) if _ap != "all": keep = (b["succ"] > 0.5) if _ap == "succ" else (b["demo"] > 0.5) if keep.sum() < 8: continue b = {k: (v[keep.cpu().numpy()] if isinstance(v, np.ndarray) else (v[keep] if torch.is_tensor(v) else v)) for k, v in b.items()} with torch.no_grad(): z = enc(b["x"]) # critic latent -> advantage zp = pf(b["x"]) # policy features -> action head q_data, _ = q_recursive(z, b["a"], b["task"], rew=rew, flow=flow, rms=rms, pol=roll, wend=wend, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=args.use_is, pessimism=args.q_pessimism) # V(z) = Monte-Carlo baseline over the policy's own chunks v = torch.zeros_like(q_data) for _ in range(M): a_pi = new.sample(zp, b["task"]) qi, _ = q_recursive(z, a_pi, b["task"], rew=rew, flow=flow, rms=rms, pol=roll, wend=wend, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=args.use_is, pessimism=args.q_pessimism) v += qi v /= M adv = q_data - v # Standardise the advantage before exponentiating. Measured on this # corpus the raw advantage has std ~8, so at beta=3 the exponent is # ~24 per standard deviation: every positive sample saturates the # clip and every negative one underflows to zero. The "soft" weight # degenerates into a hard sign filter that throws away half the data # and hands the decision entirely to the critic's sign -- whose # held-out action win rate is only 0.568. That is why AWR moved the # IQL arm from 0.470 down to 0.380. Standardising makes beta mean # what it is supposed to mean: weights span exp(+-beta) per sigma. if args.adv_norm == "std": adv = (adv - adv.mean()) / adv.std().clamp_min(1e-6) w = (args.awr_beta * adv).exp().clamp(0, args.w_max) w = w / w.mean().clamp_min(1e-6) # AWR on a flow policy weights the PER-SAMPLE flow-matching loss, since # a flow head has no tractable log-density. loss = (w * policy_nll(new, zp, b["task"], b["a"], reduce=False)).mean() opt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_(new.parameters(), 1.0); opt.step() if step % 500 == 0: rec = {"step": step, "loss": float(loss), "mean_abs_adv": float(adv.abs().mean()), "adv_std": float(adv.std()), "w_max_batch": float(w.max())} stats.append(rec) print(f"[awr] {step} loss={rec['loss']:.3f} |adv|={rec['mean_abs_adv']:.4f} " f"adv_std={rec['adv_std']:.4f} w_max={rec['w_max_batch']:.2f}", flush=True) new.eval() return new, stats
@torch.no_grad()def offline_score(d, enc, pol, rng, device, n=4096, pfeat=None): """Offline proxies, reported together and never individually as a win: bc_nll_succ : negative log-likelihood of SUCCESSFUL logged chunks act_gap : how much more likely a success chunk is than a failure chunk Neither is closed-loop success; they are screens, not the result.""" ok = np.array([e for e in d.val_eps if d.ep_success[e]], dtype=np.int64) bad = np.array([e for e in d.val_eps if not d.ep_success[e]], dtype=np.int64) def nll(pool): # A demonstrations-only cache has no failures at all, so this pool is # empty; report nan rather than indexing with an empty float array. if len(pool) == 0: return float("nan") w = d.ep_len[pool].astype(np.float64); w /= w.sum() e = rng.choice(pool, size=n, p=w) lo, hi = d.ep_from[e], d.ep_to[e] t = lo + (rng.random(n) * (hi - lo)).astype(np.int64) x = torch.from_numpy(d._feat(t)).to(device) a = torch.from_numpy(d._chunk_at(t, e)).to(device) tk = torch.from_numpy(d.ep_task[e]).long().to(device) return float(policy_nll(pol, (enc if pfeat is None else pfeat)(x), tk, a)) s, f = nll(ok), nll(bad) return {"bc_nll_success": s, "bc_nll_failure": f, "act_gap": f - s}
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--norm-pool", default="all", choices=["all", "demos"], help="frames the feature statistics come from. demos is worth +0.15 closed-loop over rollout-dominated statistics.")
ap.add_argument("--q-pessimism", type=float, default=2.0, help="subtract this many particle standard deviations from Q. " "Probed on the deployed critic, the held-out within-task " "action win rate goes 0.549 (0.0) -> 0.570 (2.0).")
ap.add_argument("--adv-norm", default="std", choices=["std", "none"], help="standardise the advantage inside the AWR weight. " "Without it beta is uninterpretable and the weight " "collapses to a hard sign filter.")
ap.add_argument("--init-pool", default="succ", choices=["succ", "demos", "demos_succ", "all"], help="episodes the pi_0 clone is fit on. Both critic arms must " "use the SAME value or the comparison measures the initialisation rather than the critic.")
ap.add_argument("--lr", type=float, default=3e-4)
ap.add_argument("--feat-scale", default="zscore", choices=["zscore", "center"], help="how the POLICY sees the observation. zscore matches the " "lane BC recipe that reaches 0.584; center keeps relative " "dim importance. Ranked on held-out sampled action MSE, " "never on the CFM loss.")
ap.add_argument("--critic", required=True) ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"], help="what the POLICY reads. raw = the full 4104-d observation " "(what a BC baseline sees); latent = the critic's " "reward-predictive bottleneck, which discards action " "detail and produced the 0%% closed-loop cliff. The " "ADVANTAGE always comes from the critic latent either way.")
ap.add_argument("--out", required=True) ap.add_argument("--rounds", type=int, default=2) ap.add_argument("--batch", type=int, default=256) ap.add_argument("--beta-q", type=float, default=0.98) ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--depth", type=int, default=2) ap.add_argument("--particles", type=int, default=8) ap.add_argument("--awr-beta", type=float, default=1.0) ap.add_argument("--w-max", type=float, default=20.0) ap.add_argument("--awr-steps", type=int, default=4000) ap.add_argument("--bc-steps", type=int, default=8000) ap.add_argument("--ratio-steps", type=int, default=4000) ap.add_argument("--wend-steps", type=int, default=4000) ap.add_argument("--use-is", type=int, default=1) ap.add_argument("--chunk", type=int, default=10, help="MUST match the critic's training chunk; the action\n dim is chunk*7 and a mismatch silently breaks loading") ap.add_argument("--ratio-chunk", type=int, default=0, help="action length the IS ratio scores; 0 = same as --chunk. " "Set to the BEHAVIOUR POLICY decision period (10 for pi0.5). " "The occupancy may condition on a much longer window; the " "ratio is a product over DECISIONS and must not.") ap.add_argument("--success-gamma", type=float, default=0.98, help="discount for reward-mode=soft: the label is " "success_gamma ** (frames until success)") ap.add_argument("--reward-mode", default="dense", choices=["dense","terminal","soft"], help="dense = P(task succeeds|z), every frame of a success is a " "positive (~50%%). terminal = last k frames only (~0.5%%), which " "leaves Q near-constant in the action.") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--policy-family", default="concat", choices=["concat", "flow", "gauss"]) ap.add_argument("--awr-pool", default="all", choices=["all", "succ", "demos"], help="which episodes AWR regresses on; 'succ' isolates dilution") ap.add_argument("--ratio-smooth", type=float, default=0.0, help="Gaussian kernel width applied to BOTH action classes before " "the ratio classifier; buys overlap at the cost of a blurred ratio") args = ap.parse_args() args.use_is = bool(args.use_is)
# Seed torch too, not just numpy: the policy head init and the # flow-matching noise are torch RNG. Without this two arms meant to # differ in ONE flag start from different policies -- observed as # pi_0 separation gaps of 0.0170 (IS on) vs 0.0089 (IS off). torch.manual_seed(args.seed) dev = "cuda" if torch.cuda.is_available() else "cpu" out = Path(args.out); out.mkdir(parents=True, exist_ok=True) d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode=args.reward_mode, success_gamma=getattr(args, 'success_gamma', 0.98), norm_pool=args.norm_pool) enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) args.d_z = cfg["d_z"] pfeat, d_pol = policy_features(args, enc, d, cfg, dev) print(f"[loop] policy reads {args.policy_features} ({d_pol}-d); " f"advantage reads critic latent ({cfg['d_z']}-d)", flush=True) rng = np.random.default_rng(args.seed + 23)
pol = train_bc(d, enc, args, dev, only_success=args.init_pool, steps=args.bc_steps, pfeat=pfeat, d_policy=d_pol, resume_path=str(Path(args.out) / 'bc_resume.pt')) # Continuation policy for the recursion only (critic-latent space). Cheap: # it never has to be a good controller, only a plausible next-action model # so the imagined hops stay on the behaviour manifold. cont_pol = (pol if args.policy_features != "raw" else train_bc(d, enc, args, dev, only_success=True, steps=max(args.bc_steps // 6, 2000), pfeat=enc, d_policy=cfg["d_z"])) log = {"config": vars(args), "rounds": []} log["pi_0"] = offline_score(d, enc, pol, rng, dev, pfeat=pfeat) print(f"[loop] pi_0 {log['pi_0']}", flush=True)
for r in range(1, args.rounds + 1): if args.use_is: # Re-fit every round: the target policy has moved, and a stale ratio # silently evaluates the wrong policy. print(f"=== round {r}: re-fit ratio for the CURRENT policy ===", flush=True) ratio = train_ratio(d, enc, cont_pol, args, dev, steps=args.ratio_steps) wend = train_endpoint_ratio(d, enc, ratio, args, dev, steps=args.wend_steps) else: # q_recursive ignores wend when use_is is False, so fitting it is # pure waste in the ablation arm. print(f"=== round {r}: IS off, skipping ratio fit ===", flush=True) wend = None pol, stats = awr_step(d, enc, pol, rew=rew, flow=flow, rms=rms, wend=wend, args=args, device=dev, steps=args.awr_steps, pfeat=pfeat, d_policy=d_pol, cont_pol=cont_pol) sc = offline_score(d, enc, pol, rng, dev, pfeat=pfeat) log["rounds"].append({"round": r, "awr": stats, "score": sc}) print(f"[loop] round {r} {sc}", flush=True) torch.save({"pol": pol.state_dict(), "round": r, "config": vars(args)}, out / f"policy_r{r}.pt") (out / "loop.json").write_text(json.dumps(log, indent=2)) print(json.dumps(log["rounds"][-1]["score"], indent=2), flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""Behaviour-cloning arms: the bars an RSM recipe has to clear.
Two pools, one script: --pool demos -> A_bc_demos, cloning the 500 human demonstrations. This is the headline baseline: the lane's own bcdemos bar is 0.584. --pool succ -> B_bc_succ, cloning the SUCCESSFUL rollouts of the behaviour policy. This is behaviour-policy extraction with no critic at all, which is what "RSM adds value" has to beat.
No critic is loaded when the policy reads raw features, so these arms areindependent of the RSM run and can train in parallel with it. The policy class,chunk, optimiser and seed are identical to the AWR arms so the only thing thatdiffers across the four arms is where the improvement signal comes from."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, jsonfrom pathlib import Pathimport numpy as npimport torch
from data import LiberoRSMDatafrom is_ope import train_bc, policy_featuresfrom awr import offline_score
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--norm-pool", default="all", choices=["all", "demos"], help="frames the feature statistics come from. demos is worth +0.15 closed-loop over rollout-dominated statistics.")
ap.add_argument("--lr", type=float, default=3e-4)
ap.add_argument("--feat-scale", default="zscore", choices=["zscore", "center"], help="how the POLICY sees the observation. zscore matches the " "lane BC recipe that reaches 0.584; center keeps relative " "dim importance. Ranked on held-out sampled action MSE, " "never on the CFM loss.")
ap.add_argument("--out", required=True) ap.add_argument("--pool", required=True, choices=["demos", "succ", "rollsucc", "rollsucc_mix", "demos_succ", "all"], help="rollsucc = successful ROLLOUTS with demos excluded; " "succ silently includes all 500 demos.") ap.add_argument("--critic", default="", help="only needed when --policy-features latent") ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"]) ap.add_argument("--policy-family", default="concat", choices=["concat", "flow", "gauss"]) ap.add_argument("--chunk", type=int, default=10) ap.add_argument("--pol-width", type=int, default=1024, help="policy MLP width (1024 -> 7.7M params; 3072x8 -> ~90M)") ap.add_argument("--pol-depth", type=int, default=4) ap.add_argument("--demo-weight", type=float, default=1.0, help="sampling weight multiplier for demonstration episodes in a mixed pool") ap.add_argument("--save-every", type=int, default=0, help="save policy_s<step>.pt every N steps (checkpoint selection on validation inits)") ap.add_argument("--bc-steps", type=int, default=30000) ap.add_argument("--batch", type=int, default=1024) ap.add_argument("--in-ram", type=int, default=0) ap.add_argument("--success-gamma", type=float, default=0.98, help="discount for reward-mode=soft: the label is " "success_gamma ** (frames until success)") ap.add_argument("--reward-mode", default="dense", choices=["dense", "terminal", "soft"]) ap.add_argument("--demos-per-task", type=int, default=5, help="pool=rollsucc_mix only: demonstrations added per task on top " "of the rollout successes. 0 reduces to pool=rollsucc.") ap.add_argument("--success-mask", default="", help="npz with keep[] from merge_verify.py. Drops logged successes whose replay did not reproduce.") ap.add_argument("--eps-per-task", type=int, default=0, help="cap distinct initial conditions per task (0 = all). Each " "episode is an independent BDDL draw, so this is a direct " "coverage-density knob at FIXED data quality.") ap.add_argument("--qfilter-frac", type=float, default=0.0, help="clone only the top fraction of each oversampled batch " "by critic advantage (the port's qfilter_frac=0.25). " "Requires --critic. A third way to use the critic: data " "selection, not action selection or gradient weighting.") ap.add_argument("--beta-q", type=float, default=0.98) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", ""), help="W&B entity; '' (default) = no W&B. rsm_rise sets RSM_WANDB_ENTITY via wandb_env.sh.") ap.add_argument("--wandb-project", default=_os.environ.get("RSM_WANDB_PROJECT", "rsm_rise")) ap.add_argument("--wandb-name", default="", help="run name (default: basename of --out)") ap.add_argument("--wandb-mode", default="online", choices=["online", "offline", "disabled"]) args = ap.parse_args()
# ---- W&B (same pattern as train_rsm.py: off unless RSM_WANDB_ENTITY is set; run id from --out) ---- if args.wandb_entity and args.wandb_mode != "disabled": try: import wandb, hashlib import is_ope as _isope _rid = hashlib.md5(str(Path(args.out).resolve()).encode()).hexdigest()[:16] _isope.WANDB_RUN = wandb.init(entity=args.wandb_entity, project=args.wandb_project, name=args.wandb_name or Path(args.out).name, id=_rid, resume="allow", mode=args.wandb_mode, config=vars(args), dir=str(Path(args.out))) print(f"[bc_arm] wandb: {_isope.WANDB_RUN.url}", flush=True) except Exception as e: print(f"[bc_arm] wandb disabled: {e}", flush=True)
torch.manual_seed(args.seed) dev = "cuda" if torch.cuda.is_available() else "cpu" d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode=args.reward_mode, success_gamma=getattr(args, 'success_gamma', 0.98), norm_pool=args.norm_pool, success_mask=getattr(args, 'success_mask', '') or '')
enc, cfg = None, {"d_z": 0} if args.policy_features == "latent": if not args.critic: raise SystemExit("--policy-features latent needs --critic") from is_ope import load_critic enc, _r, _f, _rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) args.d_z = cfg["d_z"] pfeat, d_pol = policy_features(args, enc, d, cfg, dev) print(f"[bc_arm] pool={args.pool} eps={d.n_ep} chunk={d.chunk} " f"policy reads {args.policy_features} ({d_pol}-d)", flush=True)
Path(args.out).mkdir(parents=True, exist_ok=True) pool = {"demos": "demos", "succ": True, "rollsucc": "rollsucc", "rollsucc_mix": "rollsucc_mix", "demos_succ": "demos_succ", "all": False}[args.pool] pol = train_bc(d, enc, args, dev, only_success=pool, steps=args.bc_steps, pfeat=pfeat, d_policy=d_pol, resume_path=str(Path(args.out) / 'bc_resume.pt'))
# Save FIRST: a defect in the offline proxies must never discard an hour of # training that already produced a usable policy. out = Path(args.out); out.mkdir(parents=True, exist_ok=True) torch.save({"pol": pol.state_dict(), "round": 1, "config": vars(args), "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")}, out / "policy_r1.pt") rng = np.random.default_rng(args.seed + 23) sc = offline_score(d, enc, pol, rng, dev, pfeat=pfeat) sc["sampled_action_mse"] = getattr(pol, "best_sampled_mse", float("nan")) print(f"[bc_arm] {args.pool} {sc}", flush=True) (out / "loop.json").write_text(json.dumps( {"config": vars(args), "pi_0": sc, "rounds": []}, indent=2)) import is_ope as _isope if _isope.WANDB_RUN is not None: try: _isope.WANDB_RUN.log({f"final/{k}": v for k, v in sc.items() if isinstance(v, (int, float))}) _isope.WANDB_RUN.finish() except Exception as e: print(f"[bc_arm] wandb finish failed: {e}", flush=True) print("[bc_arm] DONE", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Temperature calibration of a DWM checkpoint's dense reward head on HELD-OUT frames (orchestrator, 13:20 UTC).
Fits a scalar T minimising BCE(sigmoid(logit / T), dense label) over the val episodes' frames (EMA head on realframes, z-scored tokens/proprio exactly as in training) and writes <ckpt dir>/calib.json: {T, ckpt, step, n_val, bce_before, bce_after, ece_before, ece_after, frac_p_gt_0.99_before/after, label_rate, train: {same numbers on a train-frame sample}}.DWMCritic then uses q = mean_i sigmoid(logit_i / T) (load_critic_dwm reads calib.json). T >> 1 = overconfident head.
python calib_dwm.py --cache cache/<task> --ckpt runs/<task>/rsm/DWM/ckpt_best.pt [--max-frames 20000]"""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, json, timefrom pathlib import Pathimport numpy as npimport torchimport torch.nn.functional as F
from dwm_model import TokenRSMDatafrom dwm_readout import load_critic_dwmfrom train_rsm import auc
def ece(p, y, n_bins=15): p = np.asarray(p, np.float64); y = np.asarray(y, np.float64) bins = np.linspace(0, 1, n_bins + 1); e = 0.0 for lo, hi in zip(bins[:-1], bins[1:]): m = (p > lo) & (p <= hi) if lo > 0 else (p >= lo) & (p <= hi) if m.any(): e += m.mean() * abs(p[m].mean() - y[m].mean()) return float(e)
def fit_T(logit, y, iters=200): """1-D BCE minimisation over log T (Newton-free: golden-section on [1/16, 64]).""" lo, hi = np.log(1 / 16), np.log(64.0) f = lambda t: float(F.binary_cross_entropy_with_logits(logit / np.exp(t), y)) r = (np.sqrt(5) - 1) / 2 a, b = lo, hi; c = b - r * (b - a); d = a + r * (b - a); fc, fd = f(c), f(d) for _ in range(iters): if fc < fd: b, d, fd = d, c, fc; c = b - r * (b - a); fc = f(c) else: a, c, fc = c, d, fd; d = a + r * (b - a); fd = f(d) if b - a < 1e-5: break return float(np.exp((a + b) / 2))
def stats(logit, y, T): p = torch.sigmoid(logit / T).cpu().numpy(); yn = y.cpu().numpy() return {"bce": float(F.binary_cross_entropy_with_logits(logit / T, y)), "ece": ece(p, yn), "frac_p_gt_0.99": float((p > 0.99).mean()), "frac_p_gt_0.9": float((p > 0.9).mean()), "mean_p": float(p.mean()), "auc": auc(p, yn), "mean_p_on_label0": float(p[yn < 0.5].mean()) if (yn < 0.5).any() else float("nan"), "mean_p_on_label1": float(p[yn > 0.5].mean()) if (yn > 0.5).any() else float("nan")}
@torch.no_grad()def logits_on(crit, d, idx, dev, bs=1024): out = [] for i in range(0, len(idx), bs): sl = idx[i:i + bs] tok = torch.from_numpy(d._tok(sl)).to(dev); pr = torch.from_numpy(d._pr(sl)).to(dev) tz, pz = crit.norm.tok(tok), crit.norm.pr(pr) with crit.autocast(): out.append(crit.rew(tz, pz).float()) return torch.cat(out)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True); ap.add_argument("--ckpt", required=True) ap.add_argument("--reward-mode", default="dense"); ap.add_argument("--seed", type=int, default=0) ap.add_argument("--max-frames", type=int, default=20000); ap.add_argument("--out", default="") a = ap.parse_args() dev = "cuda" if torch.cuda.is_available() else "cpu" d = TokenRSMData(a.cache, chunk=8, seed=a.seed, reward_mode=a.reward_mode) crit = load_critic_dwm(a.ckpt, dev, calib=None) rng = np.random.default_rng(a.seed) val_idx = np.concatenate([np.arange(d.ep_from[e], d.ep_to[e]) for e in d.val_eps]) tr_idx = np.concatenate([np.arange(d.ep_from[e], d.ep_to[e]) for e in d.train_eps]) if len(val_idx) > a.max_frames: val_idx = np.sort(rng.choice(val_idx, a.max_frames, replace=False)) tr_idx = np.sort(rng.choice(tr_idx, min(a.max_frames, len(tr_idx)), replace=False)) t0 = time.time() lv = logits_on(crit, d, val_idx, dev); yv = torch.from_numpy(d.r[val_idx]).to(dev) lt = logits_on(crit, d, tr_idx, dev); yt = torch.from_numpy(d.r[tr_idx]).to(dev) T = fit_T(lv, yv) rec = {"T": T, "ckpt": str(a.ckpt), "step": crit.step, "label": a.reward_mode, "n_val": int(len(val_idx)), "n_train": int(len(tr_idx)), "label_rate_val": float(yv.mean()), "label_rate_train": float(yt.mean()), "val_before": stats(lv, yv, 1.0), "val_after": stats(lv, yv, T), "train_before": stats(lt, yt, 1.0), "train_after": stats(lt, yt, T), "T_fit_on_train_for_reference": fit_T(lt, yt), "seconds": time.time() - t0} for k in ("bce", "ece", "frac_p_gt_0.99"): rec[f"{k}_before"] = rec["val_before"][k]; rec[f"{k}_after"] = rec["val_after"][k] out = Path(a.out) if a.out else Path(a.ckpt).parent / "calib.json" out.write_text(json.dumps(rec, indent=1)) print(f"[calib] T={T:.3f} val bce {rec['bce_before']:.4f}->{rec['bce_after']:.4f} ece {rec['ece_before']:.4f}->" 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} " f"(val auc {rec['val_before']['auc']:.4f}; train T_ref {rec['T_fit_on_train_for_reference']:.3f}) -> {out}", flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132#!/bin/bash#SBATCH --job-name=capfeat#SBATCH --account=vision-pulkitag#SBATCH --qos=tig-main#SBATCH --partition=tig-cpu# EXACTLY label_subgoals.sbatch's resources. 8 cpus / 40G was CANCELLED by uid 0# three seconds in, with no output file ever created -- indistinguishable from a# crash. groenig nodes are 16 cpu / 64298 MB, so --mem=64G is also rejected outright# ("Memory specification can not be satisfied"). Do not widen these without testing.#SBATCH --cpus-per-task=4 --mem=32G#SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.out#SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.errset -uo pipefailB=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationS=/data/pulkitag/users/rli14/rlinf_recap_task_expansionexport REPO_PATH=$B/external/rlinf PYTHONPATH="$B/external/rlinf:${PYTHONPATH:-}"export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard# CPU rendering: only the FIRST observation of each episode is needed, so there is# no rollout and no GPU. osmesa is the same backend verify_successes.py used.export MUJOCO_GL=osmesa PYOPENGL_PLATFORM=osmesaexport TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "")export HUGGINGFACE_HUB_TOKEN=$HF_TOKENexport FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')"export CUDA_VISIBLE_DEVICES=""G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero$B/venvs/rlinf-libero-eval-venv/bin/python $G/capture_init_feats.py \ --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ --norm-pool demos --tasks "${TASKS:-0,1,2,3,4,6,7,8,9}" --n-init "${NINIT:-5}" \ --fresh "${FRESH:-0}" --out "${OUT:?set OUT}"echo "[cap] rc=$? $(date -u +%T)"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""Capture the evaluator's t=0 feature vector without rolling out.
The question this answers: are the features the closed-loop evaluator actuallyfeeds the policy in the DEMO region of the cache or the ROLLOUT region? It decideswhether a critic trained on a 90%-rollout corpus is read on-support at eval time.
Only the first observation of each episode is needed, so no policy and no GPU arerequired -- reset, one zero step, encode, done. Uses the SAME featurization path aseval_closed_loop.py (to224 quantisation, axis-angle proprio, cache normalisation);any deviation would make the comparison meaningless."""from __future__ import annotationsimport argparse, importlib.util, sys, osfrom pathlib import Pathimport numpy as npimport torch
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from eval_closed_loop import to224, _eef_ori, BUILDER # identical transforms
_spec = importlib.util.spec_from_file_location("ogpo_cap", BUILDER)ogpo = importlib.util.module_from_spec(_spec)sys.modules["ogpo_cap"] = ogpo_spec.loader.exec_module(ogpo)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True, help="cache whose feat stats the policy used") ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) ap.add_argument("--tasks", default="0,1,2,3,4,6,7,8,9") ap.add_argument("--n-init", type=int, default=5) ap.add_argument("--fresh", type=int, default=0) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", required=True) args = ap.parse_args()
dev = "cuda" if torch.cuda.is_available() else "cpu" print(f"[cap] device {dev}", flush=True) tower = ogpo.build_paligemma(dev) from libero.libero import benchmark, get_libero_path from libero.libero.envs import OffScreenRenderEnv bench = benchmark.get_benchmark_dict()["libero_10"]()
sname = "feat_stats.npz" if args.norm_pool == "all" else f"feat_stats_{args.norm_pool}.npz" st = np.load(str(Path(args.cache) / sname)) nmu = torch.tensor(st["mu"], dtype=torch.float32, device=dev) nsd = torch.tensor(st["sd"], dtype=torch.float32, device=dev) print(f"[cap] normalisation {sname} dim={int(st['dim'])}", flush=True)
tasks, feats = [], [] for tid in [int(t) for t in args.tasks.split(",")]: task = bench.get_task(tid) ids = ogpo.tokenize_prompt(task.language) inits = bench.get_task_init_states(tid) env = OffScreenRenderEnv( bddl_file_name=str(Path(get_libero_path("bddl_files")) / task.problem_folder / task.bddl_file), camera_heights=128, camera_widths=128) for k in range(args.n_init): np.random.seed(args.seed * 100003 + tid * 1009 + k) if hasattr(env, "seed"): env.seed(args.seed * 100003 + tid * 1009 + k) env.reset() if not args.fresh: env.set_init_state(inits[k % len(inits)]) obs, _, _, _ = env.step(np.zeros(7)) cams = [] for key in ("agentview_image", "robot0_eye_in_hand_image"): cams.append(to224(obs[key][::-1, ::-1])[None]) z = np.concatenate( [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0] prop = np.concatenate([ obs["robot0_eef_pos"], _eef_ori(obs), obs["robot0_gripper_qpos"], ]).astype(np.float32) x = torch.tensor(np.concatenate([z, prop])[None], dtype=torch.float32, device=dev) x = (x - nmu) / nsd tasks.append(tid); feats.append(np.asarray(x[0].cpu(), np.float32)) print(f"[cap] task {tid} init {k}: |x|={float(x.norm()):.2f}", flush=True) env.close() np.savez_compressed(args.out, task=np.array(tasks), x=np.stack(feats), norm_pool=args.norm_pool, fresh=args.fresh) print(f"[cap] wrote {len(tasks)} features -> {args.out}", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Does the Q arg-max over N near-copy candidates track the critic or the Monte-Carlonoise? Score the same N candidates twice with fresh seeds, with independent draws andwith common random numbers (crn), and report arg-max agreement and the ratio ofbetween-candidate Q spread to between-seed Q noise. CPU/GPU, no env.usage: crn_diag.py --critic ckpt --policy proposer.pt --hop hop.pt [--depth 3] [--n 8] [--states 200]"""import argparse, numpy as np, torchfrom data import LiberoRSMDatafrom is_ope import load_critic, q_recursive, make_policyfrom eval_closed_loop import load_policy, _resolve_cache
ap = argparse.ArgumentParser()ap.add_argument("--critic", required=True); ap.add_argument("--policy", required=True)ap.add_argument("--hop", default=""); ap.add_argument("--depth", type=int, default=3)ap.add_argument("--n", type=int, default=8); ap.add_argument("--states", type=int, default=200)ap.add_argument("--particles", type=int, default=16); ap.add_argument("--beta", type=float, default=0.98)a = ap.parse_args()dev = "cuda" if torch.cuda.is_available() else "cpu"pcfg = torch.load(a.policy, map_location="cpu", weights_only=False)["config"]d = LiberoRSMData(_resolve_cache(pcfg["cache"]), chunk=pcfg.get("chunk", 10), seed=0, in_ram=False, reward_mode="dense", norm_pool=pcfg.get("norm_pool", "all"))pfeat, pol, chunk, ccfg, pmode, d_lat, _ = load_policy(a.critic, a.policy, d.n_task, dev)q_enc, q_rew, q_flow, q_rms, q_cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d)hop = Noneif a.depth >= 2: hk = torch.load(a.hop, map_location=dev, weights_only=False) hop = make_policy(hk["config"], d, dev, d_z=q_cfg["d_z"]); hop.load_state_dict(hk["pol"]); hop.eval()rng = np.random.default_rng(0)# demo frames from the pool the proposer was trained oneps = np.where(d.ep_demo)[0]; rows = []tasks = []for e in rng.choice(eps, size=a.states, replace=True): 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]))agree = {0: [], 1: []}; ratio = {0: [], 1: []}; agree_x = []with torch.no_grad(): for i, ti in zip(rows, tasks): x = torch.as_tensor(d._feat(i)[None], device=dev).float(); tt = torch.tensor([ti], device=dev) torch.manual_seed(1234 + i) cand = pol.sample(pfeat(x).expand(a.n, -1), tt.expand(a.n)) z = q_enc(x).expand(a.n, -1) qs = {} for crn in (0, 1): out = [] for seed in (1, 2): torch.manual_seed(seed) q, _ = q_recursive(z, cand, tt.expand(a.n), rew=q_rew, flow=q_flow, rms=q_rms, pol=hop, wend=None, beta=a.beta, gamma=0.99, depth=a.depth, n_particles=a.particles, use_is=False, crn=bool(crn)) out.append(q.cpu().numpy()) q1, q2 = out; qs[crn] = (q1, q2) agree[crn].append(float(q1.argmax() == q2.argmax())) spread = 0.5 * (q1.std() + q2.std()); noise = np.abs(q1 - q2).mean() / np.sqrt(2) ratio[crn].append(spread / max(noise, 1e-9)) agree_x.append(float(qs[0][0].argmax() == qs[1][0].argmax()))for crn in (0, 1): print(f"crn={crn}: argmax agreement across seeds {np.mean(agree[crn]):.3f} " f"median (between-candidate spread / between-seed noise) {np.median(ratio[crn]):.2f}")print(f"chance agreement = {1/a.n:.3f}; independent-vs-crn argmax agreement {np.mean(agree_x):.3f}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587"""Batch sampling over the packed LIBERO-10 rollout cache."""from __future__ import annotationsfrom pathlib import Pathimport json as _json # was only imported inside the cam_res loop below, so the encoder # tag lookup (which runs first) always hit NameError and kept the # legacy default; importing it here makes PACK.json's encoder tag loadimport numpy as npimport torch
def truncated_geometric_future(rows, ep_ends, discounts, uniforms): """Ported verbatim from gen_q ogbench_genq/rsm.py (via the CLM fast-critic port).
Draws k ~ Geom(1-discount) truncated to the episode end, so the sampled future is always a REAL logged frame -- the Monte-Carlo occupancy target with no bootstrap anywhere. """ length = (ep_ends - rows) log_d = np.log(discounts) finite_mass = np.maximum(1.0 - np.exp(length * log_d), 1e-12) offset = np.ceil(np.log1p(-uniforms * finite_mass) / log_d).astype(np.int64) - 1 offset = np.clip(offset, 0, length - 1) return rows + offset
class LiberoRSMData: def __init__(self, root, chunk: int = 10, k_success: int = 10, val_frac: float = 0.1, seed: int = 0, in_ram: bool = True, success_mask: str = "", subgoal_dir: str = "", reward_mode: str = "dense", success_gamma: float = 0.98, reward_npy: str = "", weight_npy: str = "", normalize: bool = True, norm_pool: str = "all", stratify_success: bool = False, action_augment: float = 0.0, augment_mode: str = "contrastive", augment_table: str = "", augment_neighbors: int = 15, augment_frac_cap: float = 0.0): root = Path(root) self.root = root m = np.load(root / "meta.npz", allow_pickle=True) self.z = np.load(root / "z.f16.npy", mmap_mode="r") self.act = np.load(root / "act.f32.npy", mmap_mode="r") pp = root / "proprio.f32.npy" self.proprio = np.load(pp, mmap_mode="r") if pp.exists() else None # Measured on this corpus: over 5 frames the executed action correlates # with the PROPRIO delta at max |r| 0.98, but with the visual-latent delta # at only 0.49 (mean 0.10). A mean-pooled PaliGemma embedding barely # resolves the motion a 10-step chunk produces, which is why the occupancy # could rank states (0.66-0.69 AUC) but never actions (~chance pooled). # Concatenating proprio puts the action-sensitive channel INTO the latent # the successor has to predict. self.use_proprio = self.proprio is not None if in_ram: # training draws ~512 RANDOM rows per step; over NFS that is 512 # separate 8 kB reads and caps throughput at a few it/s. The cache is # small enough to hold, so pull it in once. gb = self.z.nbytes / 1e9 print(f"[data] loading {gb:.1f} GB of latents into RAM", flush=True) self.z = np.ascontiguousarray(self.z) self.act = np.ascontiguousarray(self.act) if self.proprio is not None: self.proprio = np.ascontiguousarray(self.proprio) self.ep_from = m["ep_from"]; self.ep_to = m["ep_to"]; self.ep_len = m["ep_len"] self.ep_task = m["ep_task"]; self.ep_success = m["ep_success"] # ADMISSIBILITY (see CLAUDE.md): a logged success whose actions do not # reproduce in the eval environment is not a success here. Applied before any # reward is built, so the critic never sees a progress curve toward an event # that will not occur in the environment it is scored in. if success_mask: _keep = np.load(success_mask)["keep"].astype(bool) _n0 = int(self.ep_success.sum()) self.ep_success = self.ep_success.astype(bool) & _keep print(f"[data] admissibility mask: {_n0} -> {int(self.ep_success.sum())} " f"successes ({_n0-int(self.ep_success.sum())} dropped as " f"non-reproducing)", flush=True) self.ep_demo = m["ep_demo"] if "ep_demo" in m else np.zeros(len(self.ep_task), bool) # Declared render resolution of the latents (RENDER.json, else PACK.json). Stored # into every checkpoint config so the evaluator can refuse a mismatch (i251). self.cam_res = "UNKNOWN" self.encoder = "pi05_base_pytorch" # legacy caches predate the tag for _f in ("PACK.json", "RENDER.json"): try: _e = _json.load(open(f"{root}/{_f}")).get("encoder") if _e: self.encoder = _e; break except Exception: pass for _f in ("RENDER.json", "PACK.json"): try: _v = _json.load(open(f"{root}/{_f}")).get("cam_res") if _v is not None: self.cam_res = _v; break except Exception: pass self.tasks = [str(t) for t in m["tasks"]] self.dim = int(m["dim"]); self.adim = int(m["adim"]) self.chunk = chunk; self.k_success = k_success self.n_task = len(self.tasks) self.n_ep = len(self.ep_len)
# episode-level split: adjacent frames cannot leak across the boundary rng = np.random.default_rng(seed) n_val = max(1, int(val_frac * self.n_ep)) if stratify_success: # STRATIFY ON ep_success (gen_q#261). An unstratified 10% split of the real cooking # corpus put 2 of the 50 rewarded episodes in val. Under a sparse reward label that is # 80 positive val frames, so a 256-anchor val eval draws well under one positive and the # printed `val auc` is noise rather than evidence (measured: 0.9960 sampled vs 0.9983 # over the exact full split). Holding out the SAME FRACTION of rewarded and unrewarded # episodes makes a held-out reward metric estimable at all. Off by default so every # existing run's split is bit-identical. _s = np.asarray(self.ep_success, bool) _parts = [] for _grp in (np.nonzero(_s)[0], np.nonzero(~_s)[0]): if len(_grp) == 0: continue _pg = _grp[rng.permutation(len(_grp))] _k = max(1, int(round(val_frac * len(_grp)))) if len(_grp) > 1 else 0 _parts.append(_pg[:_k]) self.val_eps = np.sort(np.concatenate(_parts)) if _parts else np.array([], np.int64) self.train_eps = np.sort(np.setdiff1d(np.arange(self.n_ep), self.val_eps)) print(f"[data] success-stratified split: {len(self.val_eps)} val " f"({int(_s[self.val_eps].sum())} rewarded) / {len(self.train_eps)} train " f"({int(_s[self.train_eps].sum())} rewarded)", flush=True) else: perm = rng.permutation(self.n_ep) self.val_eps = np.sort(perm[:n_val]) self.train_eps = np.sort(perm[n_val:])
# Feature normalisation (see _feat for why this matters). self.norm_mu = self.norm_sd = None self.z_clip = 0.0 # set from feat_stats.npz (rsm_rise caches store z_clip=10) self.norm_pool = norm_pool if normalize: self._fit_norm()
# ---- RISE-style COUNTERFACTUAL ACTION AUGMENTATION (rsm_rise AUG_SUCC, gen_q#279) ------ # # WHY. This model only ever sees (s, a_logged, future) triples, so its value OFF the logged # action at s is unconstrained. Measured consequence (status/real/RANK_CTRL.md): anchored # inside a failure episode at the S2 junction it ranks the goal-bound chunk at the 23rd # percentile, below its own permuted control. RISE's augmentation # (rise_robomimic/robomimic/utils/dataset.py:build_state_augmentation_data) is built to # supply exactly the missing pair: for state i it takes a neighbour j from a DIFFERENT # trajectory within `distance_threshold` in STATE space and emits # obs = i's obs | actions = j's action | rewards = j's reward | next_obs = i's OWN next_obs. # # TWO READINGS, both implemented, selected by `augment_mode`: # "invariant" the literal transcription: the neighbour's action is asserted to lead to # the ANCHOR's own occupancy. This trains INVARIANCE to the action over the # neighbourhood. Safe only if the neighbourhood is strictly smaller than the # action gap the value has to resolve -- measured by # scripts/real/aug_feasibility.py, which reports the straddle fraction. # "contrastive" the faithful lift of RISE's INTENT to an occupancy model: the counterfactual # action carries the NEIGHBOUR's own future, so the read-out # Qbar(s_anchor, a_neighbour) = E_{f ~ m(.|s_i,a_j)} r(f) reads the # neighbour's route. This is the pair whose absence explains the failure above. # # WHY `contrastive` CANNOT BE "anchor's future + neighbour's reward label" HERE. The reward # head in this architecture is a function of the STATE ALONE (model.py: rew(z, task)); the # action enters only through the occupancy. Asserting the anchor's own future for the # counterfactual action therefore makes Qbar(s_i, a_j) == Qbar(s_i, a_i) identically, and no # relabelling of r can change it -- while overriding r at an unchanged x_now would be pure # label noise on the one head that generalises. RISE escapes this because its contrastiveness # lives in the r term of a one-step Q(s,a) <- r + gamma V(s'), which a state-only reward plus an # action-conditioned occupancy cannot express while also asserting s' = s'_anchor. # In BOTH modes the reward-head target r_now stays the ANCHOR's own label, for that reason. # # The RISE knobs carry over verbatim: `augment_neighbors` = num_neighbors (the cap is applied # to the NEAREST different-episode frames FIRST, exactly as RISE does), `action_augment` = # distance_threshold, different-trajectory-only and skip-self are baked into the table # (scripts/real/build_aug_knn.py), which is built over the TRAIN episodes only. # # MIXING IS PROPORTIONAL, NOT ALTERNATING. RISE's `epoch % 2 == 0` scheme hands the augmented # pool 50% of all gradient steps at ANY pool size (on one sim task a 14-row pool was replayed # 457x per epoch). Here the per-row probability is n_aug_pairs / (n_aug_pairs + n_train_frames), # so a starved pool contributes in proportion to its size and `aug_frac` reports the realised # number every batch. self.aug = None self.aug_mode = augment_mode self.aug_thr = float(action_augment) self.aug_k = int(augment_neighbors) self.aug_p = 0.0 self.aug_cap = 0.0 if self.aug_thr > 0: if augment_mode not in ("contrastive", "invariant"): raise ValueError(f"--augment-mode must be contrastive|invariant, got {augment_mode}") tbl_path = augment_table or str(root / "aug_knn_feat.npz") tbl = np.load(tbl_path, allow_pickle=True) nbr_row = tbl["nbr_row"][:, : self.aug_k] nbr_dist = tbl["nbr_dist"][:, : self.aug_k] anc_row = tbl["rows"] # the table must have been built on THIS split, or an augmented pair reaches into the # held-out episodes through the action channel t_train = set(int(x) for x in tbl["train_eps"]) if "train_eps" in tbl.files else None if t_train is not None and t_train != set(int(x) for x in self.train_eps): raise RuntimeError( f"{tbl_path} was built on a DIFFERENT train split " f"({len(t_train)} eps) than this run ({len(self.train_eps)} eps); " f"rebuild it with matching --seed/--val-frac/--stratify-success") keep = nbr_dist <= self.aug_thr ai, aj = np.nonzero(keep) self.aug_anchor = anc_row[ai].astype(np.int64) self.aug_nbr = nbr_row[ai, aj].astype(np.int64) self.aug_dist = nbr_dist[ai, aj].astype(np.float32) n_pairs = len(self.aug_anchor) n_frames_tr = int(sum(int(self.ep_to[e]) - int(self.ep_from[e]) for e in self.train_eps)) self.aug = n_pairs > 0 self.aug_p = n_pairs / max(n_pairs + n_frames_tr, 1) # AUGMENTED-FRACTION CAP (AUG_SUCC run 5). Proportional mixing is the right default -- # RISE's `epoch % 2` alternation hands the augmented pool 50% of all gradient steps at ANY # pool size, which on one sim task replayed a 14-row pool 457x per epoch. But at the other # end it bites: on this corpus the k=15 pool is 15x the logged corpus, so proportional # mixing put 93% of gradient steps on counterfactual rows, the logged pair (s_i, a_i) was # seen on 7% of steps, and the 30k `contrastive` gate number came with an INVERTED # own-chunk preference and a +30% minmse -- i.e. plausibly a chunk prior rather than # goal-direction. `aug_frac`, not threshold, was the explanatory variable of that ladder. # This cap is the one change that separates the two: it fixes the augmented share at a # stated value (RISE's own scheme is 0.5) while leaving the pool, the pairing and the mode # untouched. 0 = off = pure proportional, so every prior run reproduces bit-for-bit. self.aug_cap = float(augment_frac_cap) if self.aug_cap > 0: self.aug_p = min(self.aug_p, self.aug_cap) # global row -> episode index, needed to read the neighbour's episode bounds self.row_ep = np.zeros(int(self.ep_to[-1]), np.int32) for _e in range(self.n_ep): self.row_ep[int(self.ep_from[_e]):int(self.ep_to[_e])] = _e self._aug_rng = np.random.default_rng(seed + 777) _cov = len(np.unique(self.aug_anchor)) / max(n_frames_tr, 1) print(f"[data] action augmentation: metric={str(tbl['metric'])} " f"mode={self.aug_mode} thr={self.aug_thr} k={self.aug_k} -> {n_pairs} pairs " f"over {n_frames_tr} train frames ({_cov:.3%} of anchors get >=1), " f"proportional mix p={self.aug_p:.4f}" + (f" (CAPPED at {self.aug_cap:.3f})" if self.aug_cap > 0 else ""), flush=True) if n_pairs == 0: print("[data] STARVED: the threshold admits NO pairs; training is unchanged", flush=True)
# Per-frame reward label. # # "terminal": 1 on the last k frames of successful episodes. SPARSE -- # positives are ~0.5% of frames, so nearly every sampled future reads ~0, # Q is near-constant in the action, and there is nothing to rank. This is # the likely reason action ranking stayed near chance. # # "dense": 1 on EVERY frame of a successful episode, i.e. P(episode # succeeds | z). Dense and well-posed, but it is an OUTCOME predictor and # carries almost no action information: a supervised Q(z,a) beats a # state-only V(z) by AUC 0.9550 vs 0.9539 (+0.0012). Whether an episode # succeeds is a property of the state, not of the next 10 frames. # # "soft" (RECOMMENDED): gamma_s ** (frames until this episode's success), # and 0 for episodes that never succeed. Both binary labels above are # FLAT in the sense that matters -- neither varies with PROGRESS, so # moving one chunk closer to the goal does not change the target, and an # action therefore cannot move the value. The soft label is monotone in # time-to-success, so it does. This is the fix the OCBench port # identifies for exactly this symptom: its binary `indicator` target # leaves the readout ~0 on almost every state (q_mean 0.02-0.07, "so the # Q is flat") while the soft target raises q_mean to ~0.43 and "makes the # readout vary with progress". self.r = np.zeros(int(self.ep_to[-1]), dtype=np.float32) # PER-FRAME REWARD-LOSS WEIGHT (gen_q #271 scheme C). A float32 [n_frames] array of # non-negative sample weights for the reward BCE ONLY; 1.0 everywhere when unset, so the # loss is bit-identical to the unweighted path. Scheme C puts w_neg on the frames whose # reached_state_id is a failure terminal (S5/S6) to make them hard negatives. self.w = None if weight_npy: _wv = np.load(weight_npy).astype(np.float32).ravel() assert len(_wv) == len(self.r), (len(_wv), len(self.r)) assert (_wv >= 0).all(), "negative reward-loss weight" self.w = _wv print(f"[data] reward-loss weights {weight_npy}: mean w={self.w.mean():.4f}, " f"{int((self.w != 1.0).sum())} reweighted frames of {len(self.w)}", flush=True) if reward_npy: # EXTERNAL PER-FRAME REWARD (rsm_rise #261 reward-head study). A float32 array of # exactly n_frames entries replaces every rule above, so a label defined outside this # file (e.g. the goal-transition label from the dataset's own per-frame stage # annotations, scripts/real/make_goal_reward.py) is trained with a bit-identical # pipeline to the provenance label. Nothing else changes. _rv = np.load(reward_npy).astype(np.float32).ravel() assert len(_rv) == len(self.r), (len(_rv), len(self.r)) self.r[:] = _rv print(f"[data] external reward {reward_npy}: mean r={self.r.mean():.6f}, " f"{int((self.r > 0).sum())} positive frames of {len(self.r)}", flush=True) return if reward_mode in ("subgoal", "subgoal_ind"): # r(s) = satisfied BDDL conjuncts / K. A genuine function of the state: # identical configurations get identical targets, and every frame of every # episode is labelled -- including failures, which under the soft label # contributed only zeros (50.5% of the corpus, no gradient at all). import glob as _g n_lab = 0 for _f in sorted(_g.glob(f"{subgoal_dir}/task*.npz")): _z = np.load(_f, allow_pickle=True) _K = int(_z["K"]) for _e, _v in zip(_z["ep"], _z["vals"]): _a, _b = int(self.ep_from[_e]), int(self.ep_to[_e]) _v = np.asarray(_v, np.float32) _v[_v < 0] = 0.0 # unresolvable -> no credit _val = (_v >= _K).astype(np.float32) if reward_mode == "subgoal_ind" \ else _v / max(_K, 1) self.r[_a:_a + min(len(_val), _b - _a)] = _val[:_b - _a] n_lab += 1 # demonstrations complete the task by construction for _i in np.where(self.ep_demo)[0]: self.r[int(self.ep_from[_i]):int(self.ep_to[_i])] = 1.0 print(f"[data] {reward_mode} reward: {n_lab} rollouts labelled from " f"{subgoal_dir}, mean r={self.r.mean():.4f}", flush=True) return for i in range(self.n_ep): if not self.ep_success[i]: continue lo, hi = int(self.ep_from[i]), int(self.ep_to[i]) if reward_mode == "dense": self.r[lo:hi] = 1.0 elif reward_mode == "soft": # discounted time-to-success, measured from the last frame n = hi - lo self.r[lo:hi] = (success_gamma ** np.arange(n - 1, -1, -1, dtype=np.float64) ).astype(np.float32) else: self.r[max(lo, hi - k_success):hi] = 1.0
def _feat(self, idx): """Observation every head sees: visual latent, optionally with proprio, z-scored per dimension.
Normalisation is not cosmetic here. Measured on this corpus, the mean feature vector has norm 51.1 while the per-frame deviation from it has norm 9.0 -- 85% of the input magnitude is a constant offset carrying no information, and the per-dim |mean|/std ratio is 3.14 median / 8.0 at p90. Fed raw, the informative variation is a small perturbation riding on a large common mode, which is exactly the conditioning an MLP handles worst. Proprio is worse still: its per-dim std spans 0.014 to 1.372, so the gripper channel is invisible next to the wrist angle.
Stats are computed once and cached in the cache directory so that training and the closed-loop evaluator apply the IDENTICAL transform; a policy evaluated under different statistics is off-distribution and indistinguishable from a bad policy.""" z = np.asarray(self.z[idx], np.float32) if self.proprio is not None: z = np.concatenate([z, np.asarray(self.proprio[idx], np.float32)], -1) if self.norm_mu is None: return z z = (z - self.norm_mu) / self.norm_sd # rsm_rise STATE DEFINITION: x = clip((feat - mu) / max(sd, sd_floor), -z_clip, z_clip). # A GeM channel whose patch tokens are almost always negative collapses to the 1e-6 # clamp on nearly every frame (sd ~1e-3) and then takes |x| = 30-70 on the few frames # where it is not; the flow is queried far off-support on those rows and the val # min-MSE read 2e5 (mug M, step 5000). z_clip comes from feat_stats.npz (0 = off). if self.z_clip: z = np.clip(z, -self.z_clip, self.z_clip, out=z) return z
def _fit_norm(self, stride=97): """Per-dim mean/std over a strided pass, cached next to the data.
`norm_pool` selects WHICH frames the statistics come from, and it matters a great deal. Measured: behaviour cloning on demonstrations scores 0.580 closed-loop when centred with demonstration statistics and 0.430 with statistics dominated by the 4500 rollout episodes -- same policy, same data, same budget. The rollout corpus is a different distribution (a noisy pi0.5 with SDE noise 0.5, half of it failures), so its mean is the wrong origin for a policy that acts like a demonstrator. """ tag = "" if self.norm_pool == "all" else f"_{self.norm_pool}" f = self.root / f"feat_stats{tag}.npz" if f.exists(): c = np.load(f) if int(c["dim"]) == self.feat_dim: self.norm_mu, self.norm_sd = c["mu"], c["sd"] self.z_clip = float(c["z_clip"]) if "z_clip" in c.files else 0.0 print(f"[data] feature normalisation loaded from {f.name}" f" (sd min {float(self.norm_sd.min()):.1e}, z_clip {self.z_clip})", flush=True) return if self.norm_pool == "demos": keep = np.zeros(len(self.z), bool) for e in np.where(self.ep_demo)[0]: keep[self.ep_from[e]:self.ep_to[e]] = True idx = np.where(keep)[0][::max(1, stride // 8)] else: idx = np.arange(0, len(self.z), stride) x = np.asarray(self.z[idx], np.float32) if self.proprio is not None: x = np.concatenate([x, np.asarray(self.proprio[idx], np.float32)], -1) mu = x.mean(0) sd = np.maximum(x.std(0), 1e-3) # floor: a dead dim must not be amplified self.norm_mu, self.norm_sd = mu.astype(np.float32), sd.astype(np.float32) try: np.savez(f, mu=self.norm_mu, sd=self.norm_sd, dim=self.feat_dim, n=len(idx)) print(f"[data] feature normalisation fitted on {len(idx)} frames " f"-> {f.name}", flush=True) except OSError as e: # read-only cache dir: still normalise in-process print(f"[data] normalisation fitted but not cached ({e})", flush=True)
@property def feat_dim(self): return self.dim + (0 if self.proprio is None else self.proprio.shape[1])
def _chunk_at(self, idx, ep_i, chunk_len=None): """Flattened next-`chunk_len` executed actions, padded by repeating the last.
`chunk_len` defaults to the occupancy conditioning window, but the IS ratio must use the BEHAVIOUR POLICY'S DECISION granularity instead. The notes define W as a product over interior DECISIONS; pi0.5 re-decided every 10 frames. Scoring 100-frame windows makes the two policies perfectly separable (classifier acc 1.000 at 700 dims vs 0.934 at 70), which destroys the ratio the correction needs. """ cl = self.chunk if chunk_len is None else chunk_len idx = np.asarray(idx, np.int64); ep_i = np.asarray(ep_i, np.int64) if isinstance(self.act, np.ndarray) and not isinstance(self.act, np.memmap): # in-RAM fast path (same result as the loop below): frames past the episode # end are clamped to its last frame, which IS "pad by repeating the last # action". At batch 4096 the Python loop was the step-time bottleneck. fr = idx[:, None] + np.arange(cl)[None, :] fr = np.minimum(fr, self.ep_to[ep_i][:, None] - 1) return np.asarray(self.act[fr], np.float32).reshape(len(idx), cl * self.adim) out = np.empty((len(idx), cl * self.adim), np.float32) for j, (t, e) in enumerate(zip(idx, ep_i)): hi = int(self.ep_to[e]) take = min(cl, hi - t) a = np.asarray(self.act[t:t + take], np.float32) if take < cl: a = np.concatenate([a, np.repeat(a[-1:], cl - take, 0)], 0) out[j] = a.reshape(-1) return out
def sample(self, batch: int, rng, beta_lo: float, beta_hi: float, split: str = "train", device="cuda", beta_trunc_eps: float = 0.02, with_next: bool = False, augment: bool = True): # `augment=False` forces the LOGGED sampler even when --action-augment is on. The # minmse / staymse / NN-L1 diagnostics are the training gate this stream has to report # against the un-augmented R_M cell, and under `contrastive` an augmented row's x_fut comes # from the NEIGHBOUR's trajectory -- so letting augmented rows into those evaluations would # silently change what the gate measures instead of measuring the same thing on a new model. eps_pool = self.train_eps if split == "train" else self.val_eps w = self.ep_len[eps_pool].astype(np.float64); w /= w.sum() e = rng.choice(eps_pool, size=batch, p=w) lo = self.ep_from[e]; hi = self.ep_to[e] t = lo + (rng.random(batch) * (hi - lo)).astype(np.int64) # BETA MEANS ONE THING (gen_q#262). k ~ Geom(1-beta) is truncated at the episode end, and # E[k | k<L] depends on L -- at beta=0.995 with 150 frames remaining, 47% of the geometric # falls past the end and the realised mean offset is 65 instead of 199. Drawing beta before # looking at L therefore trains the model on "beta=0.995" paired with horizons anywhere from # ~23 to ~180 frames, blurring the conditioning exactly where the horizon is longest. # # Cap beta per anchor so the truncated tail is a CONSTANT eps for every sample: # beta_cap**L == eps => beta_cap = eps**(1/L) # Anchors with a long remaining horizon (a full episode from its initial condition) get the # whole band; short-remaining anchors get a correspondingly narrower one, because a # long-horizon target genuinely does not exist there. L = np.maximum(hi - t, 1).astype(np.float64) beta_cap = np.power(beta_trunc_eps, 1.0 / L) beta_hi_eff = np.clip(beta_cap, beta_lo, beta_hi) beta = beta_lo + rng.random(batch) * (beta_hi_eff - beta_lo) fut = truncated_geometric_future(t, hi, beta, rng.random(batch))
# ---- counterfactual action augmentation (see the block in __init__) ------------------- # Nothing here touches `rng`: with augmentation off the draws above ARE the whole sampler and # every existing run reproduces bit-for-bit. `t_act` is the row the ACTION chunk comes from # and is identical to `t` on every non-augmented row. t_act, e_act = t, e aug_mask = np.zeros(batch, bool) if self.aug and augment and split == "train": if with_next: raise NotImplementedError( "--action-augment with --occupancy-target td is not implemented: the TD " "right-hand side needs s_{t+1} and a_{t+1} for the COUNTERFACTUAL action, which " "the logged corpus does not contain. Use the MC occupancy target.") ar = self._aug_rng n_aug = int(ar.binomial(batch, self.aug_p)) if n_aug > 0: t_act = t.copy(); e_act = e.copy() pos = ar.choice(batch, size=min(n_aug, batch), replace=False) pi = ar.integers(len(self.aug_anchor), size=len(pos)) i_row = self.aug_anchor[pi] # the ANCHOR state (x_now) j_row = self.aug_nbr[pi] # the NEIGHBOUR: its action is the counterfactual # "invariant" asserts the anchor's OWN occupancy for the counterfactual action; # "contrastive" gives the counterfactual action the NEIGHBOUR's own future. src = i_row if self.aug_mode == "invariant" else j_row e_src = self.row_ep[src].astype(np.int64) hi_s = self.ep_to[e_src] L_s = np.maximum(hi_s - src, 1).astype(np.float64) b_cap = np.power(beta_trunc_eps, 1.0 / L_s) # the SAME beta band and the SAME b_hi = np.clip(b_cap, beta_lo, beta_hi) # truncation cap as the logged rows b_new = beta_lo + ar.random(len(pos)) * (b_hi - beta_lo) fut_new = truncated_geometric_future(src, hi_s, b_new, ar.random(len(pos))) # x_now, r_now, task, succ, demo all stay the ANCHOR's (the reward head is # state-only, so relabelling r at an unchanged x_now would be label noise) e[pos] = self.row_ep[i_row] t[pos] = i_row beta[pos] = b_new fut[pos] = fut_new t_act[pos] = j_row e_act[pos] = self.row_ep[j_row] aug_mask[pos] = True
x_now = torch.from_numpy(self._feat(t)).to(device) x_fut = torch.from_numpy(self._feat(fut)).to(device) a_now = torch.from_numpy(self._chunk_at(t_act, e_act)).to(device) out = { "x_now": x_now, "x_fut": x_fut, "a_now": a_now, "task": torch.from_numpy(self.ep_task[e]).long().to(device), "beta": torch.from_numpy(beta).float().to(device), "r_now": torch.from_numpy(self.r[t]).to(device), "r_fut": torch.from_numpy(self.r[fut]).to(device), "succ": torch.from_numpy(self.ep_success[e].astype(np.float32)).to(device), "demo": torch.from_numpy(self.ep_demo[e].astype(np.float32)).to(device), "t_idx": t, "ep": e, "fut_idx": fut, } # BUGFIX 2026-09-23 (pack 1881632 crashed here): `aug_frac` is a SCALAR, and nnl1_eval slices # every value of the batch dict by a row index. Emit the two bookkeeping keys ONLY on a batch # that actually went through the augmented path, so the diagnostic samplers (augment=False) and # every run with the flag off see EXACTLY the pre-change key set. Both readers in train_rsm.py # already use b.get(..., 0.0). if self.aug and augment and split == "train": out["aug_mask"] = aug_mask out["aug_frac"] = float(aug_mask.mean()) if self.w is not None: out["w_now"] = torch.from_numpy(self.w[t]).to(device) if with_next: # TD-FLOW (gen_q#268). The Bellman right-hand side of the occupancy identity # m_beta(. | s,a) = (1-beta) P(. | s,a) + beta E_{s'}[ m_beta(. | s', pi(s')) ] # needs the ONE-STEP successor s' and the action the behaviour policy takes there. # This lane fits the occupancy of the DATASET policy (train_rsm.py has no actor), so # a' is the logged chunk at t+1 -- exactly the analogue of a' = pi(s') for the policy # the Monte-Carlo path already integrates along. # Clamped to hi-1, i.e. the terminal frame is its own successor; the mixture coin is # drawn per row in train_rsm.py, so a terminal anchor that takes the bootstrap branch # bootstraps from itself rather than from a frame of the next episode. # NOTHING here draws from `rng`: with with_next=False (the default) this block does not # run at all, and with it True the MC draws above are bit-for-bit unchanged. nxt = np.minimum(t + 1, hi - 1) out["x_next"] = torch.from_numpy(self._feat(nxt)).to(device) out["a_next"] = torch.from_numpy(self._chunk_at(nxt, e)).to(device) out["r_next"] = torch.from_numpy(self.r[nxt]).to(device) out["next_idx"] = nxt return out
def goal_pool(self): """Terminal latents of SUCCESSFUL episodes, per task -- the goal set the two-tower likelihood scores against. Built once; index by task id.""" if getattr(self, "_gpool", None) is None: pool = {} for i in range(self.n_ep): if not self.ep_success[i]: continue hi = int(self.ep_to[i]) pool.setdefault(int(self.ep_task[i]), []).extend( range(max(int(self.ep_from[i]), hi - self.k_success), hi)) self._gpool = {k: np.array(v, np.int64) for k, v in pool.items()} return self._gpool
def sample_goals(self, task_ids, rng, device="cuda"): """One goal latent per row, drawn from that row's task's terminal states.""" gp = self.goal_pool() idx = np.empty(len(task_ids), np.int64) for j, ti in enumerate(np.asarray(task_ids)): c = gp.get(int(ti)) idx[j] = rng.choice(c) if c is not None and len(c) else 0 return torch.from_numpy(self._feat(idx)).to(device)
def sample_frames(self, batch: int, rng, split="train", device="cuda"): """(x, action chunk, task, reward, success) with no future -- for the reward head, the ratio classifier and behavior cloning.""" eps_pool = self.train_eps if split == "train" else self.val_eps w = self.ep_len[eps_pool].astype(np.float64); w /= w.sum() e = rng.choice(eps_pool, size=batch, p=w) lo = self.ep_from[e]; hi = self.ep_to[e] t = lo + (rng.random(batch) * (hi - lo)).astype(np.int64) return { "to_end": torch.from_numpy((hi - t).astype(np.float32)).to(device), "x": torch.from_numpy(self._feat(t)).to(device), "a": torch.from_numpy(self._chunk_at(t, e)).to(device), "task": torch.from_numpy(self.ep_task[e]).long().to(device), "r": torch.from_numpy(self.r[t]).to(device), "succ": torch.from_numpy(self.ep_success[e].astype(np.float32)).to(device), "demo": torch.from_numpy(self.ep_demo[e].astype(np.float32)).to(device), "t_idx": t, "ep": e, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228"""Diffusion Forcing as a VALUE ESTIMATOR -- the eval-harness read-out (gen_q#274 / #282, DF_VALUE).
WHAT THIS IS------------The third column of the world-model family. All three are the same experiment with ONE thingchanged -- how the horizon is produced:
DINO-WM autoregressive latent rollout, chunk after chunk (dinowm_readout.py) LeWM autoregressive latent rollout (lewm_readout.py) DF ONE joint multi-step generation of the whole horizon, per-token noise levels (here)
so this module is deliberately the same shape as the other two: a `*Critic` class with the `q(...)`signature `rsm_scorer` calls, plus a `load_critic_df` loader. The scoring MATH is not reimplementedhere -- it is `df_value.value_of_candidates`, the same function the offline spread gate runs, so aneval cell and the gate cannot disagree about what "DF's value of a candidate" means.
THE READ-OUT (D1-D4, status/real/DF_VALUE.md; the docstring of df_value.py is the full statement) D1 the candidate action chunk is INPAINTED into the action channel of plan token 1 and re-imposed after every scheduling step; guidance_fn is None, ALWAYS. There is no guidance objective in this route -- that is the planner route, and it is a different stream's. D2 past the 8-frame chunk the action channel is LEFT FREE (model-sampled): the value means "this chunk, then the behaviour distribution the model was trained on", which is the same semantics as RSM's successor measure under the behaviour policy. free_tail=False (zero action, i.e. "this chunk then nothing") is the named ablation, exposed as `free_tail`. D3 M Monte-Carlo draws, the analogue of RSM's particle count P. See CRN below. D4 two aggregations of the predicted reward channel: terminal r_hat at H (mode="mpc") and the normalised discounted sum (mode="mpc_disc"). They map onto the two MPC modes the DINO-WM and LeWM columns already publish, so the arm grammar is byte-identical across the three.
INPUT SPACE. The pooled 1545-d DINOv2 state, z-scored with the task's feat_stats -- literally thesame vector `rsm_scorer.PooledDinoState.forward` returns and the same map `df_data.obs_rows` applies(`x = clip((feat - mu)/sd)`). So DF reads the scorer's DEFAULT state field `x`; unlike DINO-WM itneeds no patch tokens and unlike LeWM it needs no pixels, and `state_from_obs` needs no new branch.The model's SECOND normalisation (the bundle-level z-score over [obs | act | reward]) is appliedinside df_value via `model.norm`, from the checkpoint's own mean/std.
COMMON RANDOM NUMBERS. `rsm_scorer` flattens (B envs x N candidates) into rows and a backend isnever told N, so drawing noise per row would give every candidate its own noise and make the argmaxpartly a noise draw. This module therefore calls df_value with `crn_rows=True`: ONE noise draw perMonte-Carlo index, shared by every row of the call. `crn_seed` from the planner selects it, so acell is reproducible and two candidates differ only by their actions.
WHAT IS NOT MATCHED, STATED PLAINLY-----------------------------------1. DF's value is NOT a probability. DINO-WM and LeWM push their reward logit through a sigmoid and return c_k in [0,1]; DF's reward channel is a REGRESSION onto the provenance label, unnormalised and unbounded. It is clamped to [0,1] here ONLY because the planner's argmax and the table's health numbers assume that range; `q_raw` carries the unclamped value. No temperature calibration exists for it, so `temperature` is accepted and ignored, and `return_logit` returns the raw value, NOT a logit. Any read-out that needs a real logit (prob_log, conformal_lcb) is refused rather than faked.2. The two aggregations are one rollout used twice, but the scorer asks for one mode per cell, so a (mpc, mpc_disc) pair of cells rolls the model twice. That is 2x the compute for a pair of numbers that could share it; it is accepted here because sharing would mean caching across calls inside a backend the harness may re-instantiate, and a wrong cache is worse than a slow cell.3. The continuation past chunk 1 is the model's own sampled action channel (D2), which is NEITHER DINO-WM's hop head NOR LeWM's zero-order hold. The three columns therefore differ in the continuation as well as the rollout mechanism; the caption must say so."""from __future__ import annotations
import jsonimport osimport sysfrom pathlib import Path
import numpy as npimport torch
_DF_DIR = "/proj/dmfexp/zwhong/rsm_rise/code/df_rise"if _DF_DIR not in sys.path: sys.path.insert(0, _DF_DIR)
# The RISE eval env ($ROOT/env, py3.10) does not ship rotary_embedding_torch, and upstream's# models/diffusion.py -> models/unet3d.py:6 imports it unconditionally (unet3d is NOT used by our# 1-D transformer bundle; the import is merely on the module path). code/df_rise/_deps holds the# real 0.9.1 package, vendored by the planner stream (see _deps/PROVENANCE.txt) and put on sys.path# there only inside eval.py's `if RR_DF_CKPT:` block -- a branch this value-estimator route never# takes. Do the same here, guarded, so no shared environment is mutated and a process that already# has the package (venv_df, where the trainer and the offline gate run) is untouched.# Measured: without this, LSF 1893591 died at df_readout.py:87 with ModuleNotFoundError.try: # pragma: no cover - env-dependent import rotary_embedding_torch as _ret # noqa: F401except ModuleNotFoundError: _DF_DEPS = os.path.join(_DF_DIR, "_deps") if os.path.isdir(_DF_DEPS) and _DF_DEPS not in sys.path: sys.path.append(_DF_DEPS)
from df_data import OBS_DIM, ACT_DIM # noqa: E402from df_core import DFRise # noqa: E402from df_value import value_of_candidates, default_gamma # noqa: E402
class DFCritic: """The interface robomimic's RSMScorer expects of a backend core (see rsm_scorer.DWMBackend)."""
def __init__(self, ck, device, free_tail=True): meta = ck["meta"] self.device = torch.device(device) # TF32 ON by default, and it is a MEASUREMENT, not a guess. LSF 1894069 ran threading df_A # H=50 M=8 over 128 shared anchors at S=50 in both precisions and dumped the raw 128x128 # value matrices (status/real/dfval/vals_*_cost_s50_{fp32,tf32}.npz). Against the fp32 # reference TF32 agrees on top-1 -- which is all the planner's argmax consumes -- for # 99.2 % of anchors on the discounted read-out and 96.9 % on terminal, with per-anchor rank # correlation 1.000 / 0.995, while cutting the cell 1.45x (119.4s -> 81.3s / 128 anchors). # Contrast the DDIM knob, measured in the SAME job and REJECTED: S=25 already drops terminal # top-1 to 0.594 and S=10 to 0.367, so sampling_timesteps stays at its trained-config 50. # RR_DF_TF32=0 restores full fp32 for a bit-comparable re-read. self._tf32 = os.environ.get("RR_DF_TF32", "1") not in ("0", "false", "False") torch.backends.cuda.matmul.allow_tf32 = self._tf32 torch.backends.cudnn.allow_tf32 = self._tf32 self.frame_stack = int(meta["frame_stack"]) self.n_tokens = int(meta["n_tokens"]) self.model = DFRise(frame_stack=self.frame_stack, n_tokens=self.n_tokens, mean=ck["mean"], std=ck["std"], cfg=ck["cfg"]).to(self.device) self.model.load_state_dict(ck["model"]) self.model.eval() for p in self.model.parameters(): p.requires_grad_(False) # The candidate chunk IS one plan token: frame_stack == the project's 8-frame action chunk. self.chunk = self.frame_stack self.adim = ACT_DIM self.d_act = self.chunk * ACT_DIM self.d_z = OBS_DIM # One DF hop = one plan token = frame_stack frames, so K = ceil(H / hop_frames) plan tokens. # Read by rsm_scorer to turn the cell's H (in frames) into a depth; constant in beta, as on # DINO-WM and LeWM, because a latent world model has no beta. self.hop_frames = float(self.frame_stack) self.step = int(ck.get("step", -1)) self.free_tail = bool(free_tail) self.temperature = 1.0 self.calib = None self.q_action_winrate = None # The training window, kept so a cell can declare when H extrapolates past it. self.train_frames = self.frame_stack * self.n_tokens self.last_diag = None
# ------------------------------------------------------------------------------------------ def _prep(self, inp, a_chunk): x = inp[0] if isinstance(inp, (tuple, list)) else inp x = torch.as_tensor(x).to(self.device).float() assert x.ndim == 2 and x.shape[1] == self.d_z, \ f"DF scores from the pooled {self.d_z}-d state, got {tuple(x.shape)}" a = torch.as_tensor(a_chunk).to(self.device).float().view(x.shape[0], -1) assert a.shape[1] == self.d_act, f"a_chunk must be [B,{self.d_act}], got {tuple(a.shape)}" return x, a.view(x.shape[0], 1, self.chunk, self.adim)
@torch.no_grad() def q(self, inp, a_chunk, beta=None, n_particles=1, crn_seed=None, depth=1, mode="mpc", proprio=None, hop_policy=None, gamma=0.99, flow_steps=8, micro=256, return_hops=False, return_logit=False, temperature=None, return_lcb=None, rescore_top=0, n_particles_rescore=0): """Q per row. `depth` = plan tokens (K), so the horizon rolled is K * frame_stack frames.
`n_particles` is DF's M (D3) -- unlike DINO-WM this model IS stochastic, so the particle axis is real here and is not forced to 1. `beta`, `flow_steps`, `hop_policy` and `proprio` are accepted because the shared planner passes them to every backend, and are inert: DF has no hazard, no ODE, no hop head and reads no proprio channel of its own (proprio is already inside the pooled state).""" if mode not in ("mpc", "mpc_disc"): raise ValueError( f"mode {mode!r}: the DF value route publishes the two MPC read-outs only -- 'mpc' " f"(terminal r_hat at H) and 'mpc_disc' (normalised discounted sum along the " f"rollout). 'd1' and 'fold' are hazard read-outs of a SUCCESSOR model; DF has no " f"per-hop hazard to fold, and faking one would not be the same estimator.") if return_lcb is not None: raise ValueError("plan_score=conformal_lcb needs a calibrated particle quantile; DF's " "reward channel is an uncalibrated regression, so a quantile of it is " "not a lower confidence bound on anything") x, a = self._prep(inp, a_chunk) K = max(int(depth), 1) H = int(K * self.frame_stack) M = max(int(n_particles), 1) seed = 0 if crn_seed is None else int(crn_seed) out = value_of_candidates( self.model, x, a, H=H, M=M, # D4: the cell's own gamma, so the discounted sum uses the SAME discount the cell's H # was derived from (H = 1/(1-gamma)) instead of df_value's default 1 - 1/H. gamma=float(gamma) if mode == "mpc_disc" else None, free_tail=self.free_tail, device=self.device, seed=seed, crn_rows=True, assert_clamp=True) v = (out["terminal"] if mode == "mpc" else out["disc"])[:, 0] sd = (out["terminal_std"] if mode == "mpc" else out["disc_std"])[:, 0] self.last_diag = dict(out["diag"], mode=mode, H=H, K=K, M=M, mean_std_across_M=float(sd.mean().item()), std_across_rows=float(v.std().item())) q_raw = torch.nan_to_num(v, nan=0.0) q = q_raw.clamp(0.0, 1.0) # see "WHAT IS NOT MATCHED" 1 in the module docstring out_v = (q, q_raw) if return_logit else q if return_hops: # DF generates the horizon JOINTLY -- there is no per-hop sequence of independent # decisions to report, which is the whole point of the column. Returning the terminal # value K times would look like a hop trace and would be a lie about the mechanism. raise ValueError("return_hops has no meaning for DF: the horizon is generated jointly, " "not hop by hop") return out_v
def hop_sample(self, x, eps): raise RuntimeError("DF has no hop head: the continuation past the candidate chunk is the " "model's OWN sampled action channel (D2), not a policy over states")
def describe(self): return {"backend": "df", "frame_stack": self.frame_stack, "n_tokens": self.n_tokens, "hop_frames": self.hop_frames, "chunk": self.chunk, "d_act": self.d_act, "step": self.step, "free_tail": self.free_tail, "tf32": self._tf32, "train_frames": self.train_frames, "deterministic": False, "readout": "predicted reward channel of a jointly generated multi-step bundle", "guidance": "none (guidance_fn=None)"}
def load_critic_df(path, device="cuda", calib="auto", free_tail=None) -> DFCritic: """`path` is a train_df.py checkpoint (ckpt_s<step>.pt: keys cfg/mean/meta/model/std/step).
`free_tail` defaults to D2 (True) and can be forced to False by the env var RR_DF_FREE_TAIL=0 so the "this chunk then nothing" ablation can be run WITHOUT a new cell grammar -- the scorer has no flag for it and inventing one would change every other column's argument surface.""" ck = torch.load(str(path), map_location="cpu", weights_only=False) if "meta" not in ck or "model" not in ck: raise RuntimeError(f"{path} is not a train_df.py checkpoint (keys {sorted(ck.keys())})") if free_tail is None: free_tail = os.environ.get("RR_DF_FREE_TAIL", "1") not in ("0", "false", "False") crit = DFCritic(ck, device, free_tail=free_tail) # Accepted and IGNORED, loudly: DF's value is a regression, not a logit, so a temperature is not # defined for it. Silently reading calib.json would make the column look calibrated. if calib not in (None, "auto", "none") or (Path(path).parent / "calib.json").exists(): print(f"[df_readout] temperature calibration does not apply to DF's regression read-out; " f"T=1 (calib={calib!r})", flush=True) return crit123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""DINO-WM read-out: the same best-of-N scorer interface as dwm_readout, with DINO-WM's dynamics.
gen_q#268. The single-actor flagship asks one question -- "same RISE actor, same 128 candidates,same provenance reward, only the value estimator changes" -- so a world-model comparator is onlyworth running if it differs from RSM/DWM in the MODEL and in nothing else. That is why this moduleis 60 lines instead of 600: `DINOWMCritic` SUBCLASSES `dwm_readout.DWMCritic` and overrides exactlytwo methods, the transition and the hop length. The fold algebra, the hop-policy chaining, thereward head, the token normaliser, the temperature calibration and the two-stage rescore are thesame code objects the DWM column runs.
WHAT DINO-WM IS HERE--------------------stable-worldmodel's PreJEPA recipe: frozen DINOv2 ViT-S/14 patch features + a causal transformerthat predicts the next frame's features from the current ones and the action, trained by latent MSE.Our caches already hold exactly those features (cache/<task>/tokens/tok.f16.npy is[N, 514, 384] = 2 cameras x (CLS + 256 patches) from dinov2_vits14 at 224 px), and dwm_model.DWM isalready "the DINO-WM predictor" -- stream C built it as the velocity network of a token-space flow.So DINO-WM is that predictor trained with train_rsm_dwm.py --dynamics latent_mse, and scored here.
TRANSITION. Deterministic: s' = f_theta(s, a), one action chunk ahead. The predictor is queriedat the one fixed point of its flow-time/noise inputs that training used (x_k = 0, k = 0, beta = 0),so the "future" half of its token sequence is a learned query attending to the current frame's patchtokens under the action embedding. There is no ODE and no noise IN THE TRANSITION.
PARTICLES (gen_q#288, corrected 2026-09-25). A deterministic transition does NOT make the ESTIMATORdeterministic. Past the candidate chunk the continuation action comes from the stochastic Gaussianhop head -- the same object RSM chains with -- so at depth > 1 the M particles are M different actionsequences and Q is the mean over them, with common random numbers across candidates (`_q_once` drawseps per particle and tiles it over the rows). This module used to force n_particles = 1 at EVERYdepth, so all 855 published DINO-WM MPC cells requested 16 particles and measured one roll-out. Onlydepth == 1 is truly deterministic and keeps the force. Search cost therefore scales with M and theflagship discloses it; the effective count is in the cell's `planner.scorer.effective_particles` andin the arm key, so a repaired cell cannot pool with an old one.
HOP LENGTH. One DINO-WM hop is `hop_frames` frames (the action chunk the model was trained on, 8 =0.4 s at 20 Hz), whereas an RSM/DWM hop spans 1/(1-beta) frames. The two scorers are thereforematched on the NUMBER of hops, L in {1,2,4,8}, not on beta -- a latent-dynamics model has no beta --and the fold's per-hop discount uses gamma ** hop_frames. L is the only knob this scorer has, whichis why its arm label in verdict_table is "L<depth> N<n>" with no beta in it.
DEVIATIONS FROM THE PAPER, DECLARED-----------------------------------1. History length 1, not 3. Forced by the protocol, not chosen: rsm_planner.plan_get_action hands a scorer the SINGLE current frame (`obs_t = {k: v[:, -1] ...}`), so a history-3 world model cannot be evaluated on the same observation every other scorer sees.2. Two cameras (514 tokens) rather than one, because that is what the RISE observation is and what every other scorer in the table reads.3. Actions enter as the flattened 8-step chunk the RISE actor emits, not per-frame, for the same reason: it is the candidate the planner ranks.4. The reward probe is the checkpoint's own head on the provenance/membership label -- the same label and the same head class RSM's membership read-out uses."""from __future__ import annotations
import jsonfrom pathlib import Path
import torch
# (no direct model construction here: DWMCritic.__init__ builds the predictor and the reward head)from dwm_readout import DWMCritic
class DINOWMCritic(DWMCritic): """DWMCritic with DINO-WM's deterministic latent dynamics instead of the occupancy flow."""
def __init__(self, ck, device, use_ema=True): super().__init__(ck, device, use_ema=use_ema) # frames per hop: the action chunk the model was trained to step over. self.hop_frames = float(ck.get("hop_frames", self.config.get("chunk", 8))) self.dynamics = str(self.config.get("dynamics", "latent_mse"))
def _step(self, tzr, pzr, ar, bq, B, n, g, flow_steps, micro): """s' = f_theta(s, a): one deterministic chunk step, in normalised token space.
Mirrors the training call in train_rsm_dwm._latent_mse_terms exactly -- same zero flow-time, same zero noise input, same zero beta, same residual reparameterisation -- so the model is queried at scoring time at the one point it was fitted at. `micro` still bounds the rows per forward, because N=128 candidates x 514 tokens is the same memory problem the flow path has. """ outs_t, outs_p = [], [] m = max(int(micro), 1) for i in range(0, tzr.shape[0], m): t_i, p_i, a_i = tzr[i:i + m], pzr[i:i + m], ar[i:i + m] zt = torch.zeros_like(t_i) zp = torch.zeros_like(p_i) kz = torch.zeros(t_i.shape[0], device=t_i.device) bz = torch.zeros(t_i.shape[0], device=t_i.device) with self.autocast(): v_tok, v_pr = self.flow(t_i, p_i, a_i, bz, zt, zp, kz) nt = t_i.float() + self.rms_tok * v_tok.float() npr = (p_i.float() + self.rms_pr * v_pr.float()) if v_pr.shape[1] else p_i.float() outs_t.append(nt) outs_p.append(npr) return torch.cat(outs_t, 0), torch.cat(outs_p, 0)
def _hop_frames(self, beta): return self.hop_frames
def n_eff_particles(self, n_particles, depth, mode): """The number of DISTINCT roll-outs a (n_particles, depth, mode) cell actually averages.
Exposed so the eval cell's `planner.scorer` block can record the EFFECTIVE count rather than the requested one, the same self-verifying trick the temperature field already uses: two cells pool in verdict_table's arm key exactly when the estimator they ran was the same, whatever the grid asked for. Before gen_q#288 this class silently collapsed every count to 1, so 855 published DINO-WM cells REQUESTED 16 and MEASURED 1; without this field a re-run at a working M=16 would pool with them. """ d = 1 if mode == "d1" else int(depth or 1) return 1 if d <= 1 else int(n_particles or 1)
def q(self, *a, **kw): """gen_q#288 -- M STOCHASTIC ROLL-OUTS, not one. n_particles is forced to 1 only at depth 1.
The TRANSITION here is deterministic (`_step` above), which is why this override used to force n_particles = 1 unconditionally. That was wrong for every depth > 1 cell, and every published DINO-WM MPC cell is one: past the candidate chunk the continuation comes from the STOCHASTIC Gaussian hop head (`_q_once`'s hop_policy branch draws its own eps per particle), so particles at depth > 1 are genuinely different chains and averaging them is the estimator, exactly as it is for RSM and DWM. Owner, 2026-09-25: "should definitely be M different chains for DINOWM and LeWM with stochastic continuations just like RSM."
At depth == 1 there is no continuation to sample and the roll IS deterministic, so 16 identical roll-outs would burn 16x the compute and report the same number -- that case keeps the force. `mode="d1"` pins depth to 1 inside the parent, so it is resolved here the same way. """ if len(a) > 3: # n_particles/depth/mode passed POSITIONALLY would be invisible to the kw rewrite below and # `kw["n_particles"] = 1` would then be a duplicate argument, so say so instead of guessing. raise TypeError( "dinowm_readout.DINOWMCritic.q takes (x_tokens, a_chunk, beta) positionally; pass " "n_particles / depth / mode by keyword (rsm_scorer.DWMBackend.q already does) -- the " "particle count is rewritten here (gen_q#288) and cannot be read out of *args") mode = kw.get("mode", "d1") depth = kw.get("depth", 1) if self.n_eff_particles(kw.get("n_particles", 16), depth, mode) == 1: if kw.get("n_particles", 1) != 1: kw["n_particles"] = 1 if kw.get("n_particles_rescore"): kw["n_particles_rescore"] = 1 return super().q(*a, **kw)
def load_critic_dwm(path, device="cuda", use_ema=True, calib="auto") -> DINOWMCritic: """Same name and signature as dwm_readout.load_critic_dwm, so this module is a drop-in for the scorer's DWM backend (which imports `load_critic_dwm` from `rsm_dwm_module`).""" ck = torch.load(str(path), map_location="cpu", weights_only=False) m = str(ck.get("model", "dwm")) dyn = dict(ck.get("config", {})).get("dynamics") if m != "dinowm" or dyn != "latent_mse": raise RuntimeError( f"{path} is model={m!r} dynamics={dyn!r}; dinowm_readout needs a checkpoint trained with " f"train_rsm_dwm.py --dynamics latent_mse. A flow DWM must be loaded by " f"dwm_readout.load_critic_dwm -- reading it here would treat a velocity field as a " f"next-state predictor.") crit = DINOWMCritic(ck, device, use_ema=use_ema) if isinstance(calib, (int, float)) and not isinstance(calib, bool): crit.temperature = float(calib) elif calib == "auto": cj = Path(path).parent / "calib.json" if cj.exists(): try: crit.calib = json.loads(cj.read_text()) crit.temperature = float(crit.calib["T"]) except Exception as e: print(f"[dinowm_readout] calib.json unreadable ({e}); T=1", flush=True) return crit123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562"""DWM: the DINO-WM predictor architecture, trained as a beta-discounted SUCCESSOR model.
DINO-WM (gaoyuezhou/dino_wm, conf/predictor/vit.yaml): a ViT (depth 6, 16 heads x 64,MLP 2048, dropout 0.1) over frozen DINOv2 ViT-S/14 patch tokens (384-d) with the action andproprio embeddings CONCATENATED to every token, trained by MSE to the next frame's tokens.
Ours keeps the ViT and changes the target and the objective (LAUNCH_MATRIX rev. 4, "DWM"):
* sequence = 514 "now" tokens (agentview CLS + 256 patches, wrist CLS + 256 patches) + 514 NOISY FUTURE tokens x_k = (1-k) y + k eps, full attention, learned position embedding shared by the two halves + a 2-way TYPE embedding; * y = (x_{t+K} - x_t) / rho, the residual of the z-scored tokens, rho = running per-(token, channel) RMS of the residual (OccFlow's per-dim normalisation); * K ~ Geom(1 - beta), beta ~ U[lo, hi], truncated at the episode end (data.py sampler); * conditioning, concatenated to EVERY token as DINO-WM does: action chunk (8x7=56 -> 16), proprio (9 -> 8), Fourier(log(-log beta)) (-> 8), flow time k sinusoid (8): 384+40 = 424; * output = the flow velocity v = y - eps read at the future positions (LayerNorm+Linear); * reward head R: mean-pooled tokens per camera (2x384) ++ proprio -> MLP 512x2 -> logit.
One documented addition: a 515th "proprio" token per frame (9-d proprio embedded to 384, andits own 9-d residual on the future side, read out by a 424->9 head). The MLP cells model thepooled 1545-d state, which INCLUDES proprio, and the Stage-2 hop policy consumes the pooledstate of the sampled future, so the DWM successor has to predict proprio too. Cost: 2 tokensout of 1030.
No learned encoder: DINO is frozen and its tokens are the state (Stage 1 "no learned encoderin either case")."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import jsonfrom pathlib import Pathimport numpy as npimport torchimport torch.utils.checkpointimport torch.nn as nnimport torch.nn.functional as F
from model import beta_fourier, time_embedfrom data import truncated_geometric_future
# token layout of cache/<task>/tokens/tok.f16.npy [N, 514, 384]N_PATCH = 256D_TOK = 384TOK_LAYOUT = {"agent_cls": 0, "agent_patch": (1, 1 + N_PATCH), "wrist_cls": 1 + N_PATCH, "wrist_patch": (2 + N_PATCH, 2 + 2 * N_PATCH)}N_TOK = 2 + 2 * N_PATCH # 514# Stage-1 state normalisation rule (orchestrator, 2026-09-18; B_stage1.md "STATE DEFINITION (final)"):# x = clip((feat - mu) / max(sd, SD_FLOOR), -Z_CLIP, Z_CLIP) -- same floor/clip for pooled and token space# and the residual RMS rho is floored at RHO_FLOOR; the normalised residual y is clipped to +-Y_CLIP so a dead# channel (sd at the floor, delta up to 2*Z_CLIP) can never blow up the flow target.SD_FLOOR = 0.01Z_CLIP = 10.0RHO_FLOOR = 0.01Y_CLIP = 10.0STATS_VERSION = 2
# --------------------------------------------------------------------------- ## pooled 1545-d state from tokens (RISE's DinoV2Core(concatenate=True) ++ proprio)# --------------------------------------------------------------------------- #def gem_pool(patches: torch.Tensor, p: float = 4.0, eps: float = 1e-6) -> torch.Tensor: """GeM over the patch axis exactly as robomimic/models/obs_core.py DinoV2Core does: clamp(min=1e-6) -> mean over the 16x16 grid of x^4 -> ^(1/4). patches [..., 256, 384].""" return patches.clamp(min=eps).pow(p).mean(-2).pow(1.0 / p)
def pool_tokens(tokens: torch.Tensor, proprio: torch.Tensor | None = None) -> torch.Tensor: """[B, 514, 384] RAW DINO tokens (+ [B, 9] proprio) -> [B, 1536 (+9)] pooled state = [agent CLS ‖ GeM(agent patches) ‖ wrist CLS ‖ GeM(wrist patches)] ‖ proprio, i.e. what cache/<task>/z.f16.npy ‖ proprio.f32.npy holds (un-normalised).""" t = tokens.float() a0, (a1, a2) = TOK_LAYOUT["agent_cls"], TOK_LAYOUT["agent_patch"] w0, (w1, w2) = TOK_LAYOUT["wrist_cls"], TOK_LAYOUT["wrist_patch"] parts = [t[:, a0], gem_pool(t[:, a1:a2]), t[:, w0], gem_pool(t[:, w1:w2])] if proprio is not None: parts.append(proprio.float()) return torch.cat(parts, -1)
# --------------------------------------------------------------------------- ## data: the pooled pack's meta/actions/proprio/labels + the token memmap# --------------------------------------------------------------------------- #class TokenRSMData: """Same episode split, reward label and future sampler as data.LiberoRSMData, but the state is the [514, 384] token frame from <cache>/tokens/tok.f16.npy (memmap; the page cache is shared by the 8 DDP ranks on a node). Frame order = the pooled pack's."""
def __init__(self, root, chunk: int = 8, val_frac: float = 0.1, seed: int = 0, reward_mode: str = "dense", success_gamma: float = 0.98, in_ram: bool = False, tokens_file: str = "", goal_file: str = "", tok_rows: str = ""): root = Path(root) self.root = root m = np.load(root / "meta.npz", allow_pickle=True) self.ep_from = m["ep_from"].astype(np.int64); self.ep_to = m["ep_to"].astype(np.int64) self.ep_len = m["ep_len"].astype(np.int64) self.ep_task = m["ep_task"].astype(np.int64); self.ep_success = m["ep_success"].astype(bool) self.ep_demo = m["ep_demo"] if "ep_demo" in m else np.zeros(len(self.ep_task), bool) self.tasks = [str(t) for t in m["tasks"]] self.n_task = len(self.tasks); self.n_ep = len(self.ep_len) self.adim = int(m["adim"]); self.chunk = chunk self.act = np.load(root / "act.f32.npy", mmap_mode="r") pp = root / "proprio.f32.npy" self.proprio = np.load(pp, mmap_mode="r") if pp.exists() else None tf = Path(tokens_file) if tokens_file else root / "tokens" / "tok.f16.npy" self.tok_path = tf self.tok = np.load(tf, mmap_mode="r") assert self.tok.ndim == 3 and self.tok.shape[1:] == (N_TOK, D_TOK), \ f"token cache {tf} has shape {self.tok.shape}, expected [N, {N_TOK}, {D_TOK}]" # ROW MAP (gen_q#268). A cache that is a ROW SLICE of a parent -- cache/square_sub_20100 is # exactly that of cache/square_expert_suboptimal (SLICE.json, # scripts/build_sq20100_cache_slice.py), and its PACK.json records that tokens were not # sliced -- can read the PARENT's token file through an index array instead of getting a # 15.6 GB copy of it. /proj/dmfexp runs at 99% full, so the copy is not an option. # tok_rows[i] is the parent-file row of THIS cache's frame i; it must have one entry per # frame of the pooled pack, and the pooled pack's own frame count is what everything else # (act, proprio, meta, the reward label) is indexed by. self.tok_rows = None if tok_rows: self.tok_rows = np.load(tok_rows).astype(np.int64) assert len(self.tok_rows) == int(self.ep_to[-1]), \ f"row map {tok_rows} has {len(self.tok_rows)} entries, pooled pack has {int(self.ep_to[-1])} frames" assert int(self.tok_rows.max()) < self.tok.shape[0], \ f"row map indexes frame {int(self.tok_rows.max())} of a {self.tok.shape[0]}-frame token file" print(f"[data] token row map {tok_rows}: {len(self.tok_rows)} frames read out of " f"{self.tok.shape[0]} in {tf}", flush=True) else: assert self.tok.shape[0] == int(self.ep_to[-1]), \ f"token frames {self.tok.shape[0]} != pooled pack frames {int(self.ep_to[-1])}" self.tok_info = {} tj = tf.parent / "TOKENS.json" if tj.exists(): try: self.tok_info = json.loads(tj.read_text()) except Exception: pass self.act = np.ascontiguousarray(self.act) if self.proprio is not None: self.proprio = np.ascontiguousarray(self.proprio) if in_ram: gb = self.tok.nbytes / 1e9 print(f"[data] loading {gb:.1f} GB of tokens into RAM", flush=True) self.tok = np.ascontiguousarray(self.tok) if self.tok_rows is not None and in_ram: # keep only the rows this cache uses, and renumber the map onto them self.tok = np.ascontiguousarray(self.tok[np.sort(np.unique(self.tok_rows))]) _u = np.sort(np.unique(np.load(tok_rows).astype(np.int64))) self.tok_rows = np.searchsorted(_u, np.load(tok_rows).astype(np.int64)) self.n_pr = 0 if self.proprio is None else int(self.proprio.shape[1])
# episode-level split, IDENTICAL to LiberoRSMData(seed=seed) so the val set matches # the MLP cells rng = np.random.default_rng(seed) perm = rng.permutation(self.n_ep) n_val = max(1, int(val_frac * self.n_ep)) self.val_eps = np.sort(perm[:n_val]); self.train_eps = np.sort(perm[n_val:])
# per-frame reward label (LiberoRSMData: dense = every frame of a success; soft = # gamma ** frames-to-end on successes) self.r = np.zeros(int(self.ep_to[-1]), dtype=np.float32) if reward_mode == "goal": # GOAL-STATE label: env.is_success() at the replayed frame (scripts/goal_label_replay.py), not the # outcome. The dense label fires on every frame of a successful episode and makes the read-out saturate. gf = Path(goal_file) if goal_file else root / "goal.npz" g = np.load(gf, allow_pickle=True)["goal"] assert len(g) == len(self.r), f"{gf}: {len(g)} frames vs cache {len(self.r)}" self.r[:] = g.astype(np.float32) print(f"[data] goal label from {gf}: {self.r.mean():.4f} of frames", flush=True) for i in range(self.n_ep): if reward_mode == "goal" or not self.ep_success[i]: continue lo, hi = int(self.ep_from[i]), int(self.ep_to[i]) if reward_mode == "dense": self.r[lo:hi] = 1.0 elif reward_mode == "soft": n = hi - lo self.r[lo:hi] = (success_gamma ** np.arange(n - 1, -1, -1, dtype=np.float64) ).astype(np.float32) else: raise ValueError(f"reward_mode {reward_mode} not supported for DWM") self.stats = self._fit_stats()
# ---- normalisation statistics (per token position x channel; per proprio dim) ---- def _fit_stats(self, stride: int = 97): # With a row map the token file belongs to the PARENT task, so its tok_stats.npz describes # the parent's frame distribution, not ours. Fit and cache our own, in our own cache dir. f = (self.root / "tokens" / "tok_stats.npz") if self.tok_rows is not None \ else self.tok_path.parent / "tok_stats.npz" f.parent.mkdir(parents=True, exist_ok=True) n = int(self.ep_to[-1]) if f.exists(): try: c = np.load(f) if c["mu"].shape == (N_TOK, D_TOK) and int(c["version"]) == STATS_VERSION \ and float(c["sd_floor"]) == SD_FLOOR and float(c["z_clip"]) == Z_CLIP: print(f"[data] token normalisation loaded from {f} (sd floor {SD_FLOOR}, clip {Z_CLIP})", flush=True) return {k: c[k] for k in ("mu", "sd", "pr_mu", "pr_sd")} print(f"[data] token stats {f} are an older version; refitting", flush=True) except Exception as e: # a half-written file from a concurrent job: refit print(f"[data] token stats unreadable ({e}); refitting", flush=True) idx = np.arange(0, n, max(1, min(stride, max(n // 64, 1)))) x = np.asarray(self.tok[self._rows(idx)], np.float32) mu = x.mean(0); sd_raw = x.std(0); sd = np.maximum(sd_raw, SD_FLOOR) if self.proprio is not None: p = np.asarray(self.proprio[idx], np.float32) pr_mu, pr_sd = p.mean(0), np.maximum(p.std(0), SD_FLOOR) else: pr_mu = np.zeros(0, np.float32); pr_sd = np.ones(0, np.float32) st = {"mu": mu.astype(np.float32), "sd": sd.astype(np.float32), "pr_mu": pr_mu.astype(np.float32), "pr_sd": pr_sd.astype(np.float32)} n_floor = int((sd_raw < SD_FLOOR).sum()) try: tmp = f.with_name(f"tok_stats.{_os.getpid()}.tmp.npz") np.savez(tmp, n=len(idx), version=STATS_VERSION, sd_floor=SD_FLOOR, z_clip=Z_CLIP, rho_floor=RHO_FLOOR, y_clip=Y_CLIP, sd_raw=sd_raw.astype(np.float32), **st) _os.replace(tmp, f) # atomic: concurrent jobs (f.parent / "TOK_STATS.json").write_text(json.dumps({ "file": "tok_stats.npz", "version": STATS_VERSION, "n_frames": int(len(idx)), "stride": int(idx[1] - idx[0]) if len(idx) > 1 else 1, "rule": "x = clip((tok - mu) / max(sd, sd_floor), -z_clip, z_clip), per (token position, channel); " "proprio: per dim, same floor/clip", "sd_floor": SD_FLOOR, "z_clip": Z_CLIP, "residual": "y = clip((x_fut - x_now) / max(rho, rho_floor), -y_clip, y_clip), rho = running " "per-(token, channel) RMS of the residual", "rho_floor": RHO_FLOOR, "y_clip": Y_CLIP, "n_token_channels_at_sd_floor": n_floor, "sd_raw_min": float(sd_raw.min()), "sd_raw_p01": float(np.percentile(sd_raw, 1)), "abs_z_max_on_fit_frames": float(np.abs((x - mu) / sd).max())}, indent=1)) print(f"[data] token normalisation fitted on {len(idx)} frames -> {f} " f"({n_floor} token-channels at the sd floor {SD_FLOOR}; z clipped to +-{Z_CLIP})", flush=True) except OSError as e: print(f"[data] token normalisation fitted but not cached ({e})", flush=True) return st
def _chunk_at(self, idx, ep_i, chunk_len=None): cl = self.chunk if chunk_len is None else chunk_len out = np.empty((len(idx), cl * self.adim), np.float32) for j, (t, e) in enumerate(zip(idx, ep_i)): hi = int(self.ep_to[e]); take = min(cl, hi - t) a = np.asarray(self.act[t:t + take], np.float32) if take < cl: a = np.concatenate([a, np.repeat(a[-1:], cl - take, 0)], 0) out[j] = a.reshape(-1) return out
def _rows(self, idx): """cache frame indices -> rows of the token file (identity unless a row map is in use).""" return idx if self.tok_rows is None else self.tok_rows[idx]
def _tok(self, idx): """RAW fp16 tokens for a set of rows (gathered in sorted order for locality).""" idx = self._rows(np.asarray(idx, np.int64)) order = np.argsort(idx, kind="stable") g = np.asarray(self.tok[idx[order]]) out = np.empty_like(g); out[order] = g return out
def _pr(self, idx): if self.proprio is None: return np.zeros((len(idx), 0), np.float32) return np.asarray(self.proprio[idx], np.float32)
def draw(self, batch, rng, beta_lo, beta_hi, split="train"): """Index-level draw (no I/O): the (t, K, beta) tuple per row.""" eps_pool = self.train_eps if split == "train" else self.val_eps w = self.ep_len[eps_pool].astype(np.float64); w /= w.sum() e = rng.choice(eps_pool, size=batch, p=w) lo = self.ep_from[e]; hi = self.ep_to[e] t = lo + (rng.random(batch) * (hi - lo)).astype(np.int64) beta = rng.uniform(beta_lo, beta_hi, size=batch) fut = truncated_geometric_future(t, hi, beta, rng.random(batch)) return e, t, fut, beta
def gather(self, e, t, fut, beta, with_fut=True): """CPU tensors for a draw. Tokens stay fp16 (normalised on the device).""" out = {"tok_now": torch.from_numpy(self._tok(t)), "pr_now": torch.from_numpy(self._pr(t)), "a_now": torch.from_numpy(self._chunk_at(t, e)), "task": torch.from_numpy(self.ep_task[e]).long(), "beta": torch.from_numpy(np.asarray(beta)).float(), "r_now": torch.from_numpy(self.r[t]), "succ": torch.from_numpy(self.ep_success[e].astype(np.float32)), "to_end": torch.from_numpy((self.ep_to[e] - t).astype(np.float32)), "t_idx": t, "ep": e, "fut_idx": fut} if with_fut: out["tok_fut"] = torch.from_numpy(self._tok(fut)) out["pr_fut"] = torch.from_numpy(self._pr(fut)) out["r_fut"] = torch.from_numpy(self.r[fut]) return out
def sample(self, batch, rng, beta_lo, beta_hi, split="train", device="cpu"): e, t, fut, beta = self.draw(batch, rng, beta_lo, beta_hi, split) b = self.gather(e, t, fut, beta) return {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v) for k, v in b.items()}
def sample_frames(self, batch, rng, split="train", device="cpu"): e, t, _, _ = self.draw(batch, rng, 0.5, 0.5, split) b = self.gather(e, t, t, np.zeros(batch), with_fut=False) b["x"] = b.pop("tok_now"); b["a"] = b.pop("a_now"); b["r"] = b.pop("r_now") return {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v) for k, v in b.items()}
class Normalizer(nn.Module): """z-scoring of raw tokens / proprio, stored in the checkpoint as buffers."""
def __init__(self, stats): super().__init__() self.register_buffer("mu", torch.as_tensor(stats["mu"], dtype=torch.float32)) self.register_buffer("sd", torch.as_tensor(stats["sd"], dtype=torch.float32)) self.register_buffer("pr_mu", torch.as_tensor(stats["pr_mu"], dtype=torch.float32)) self.register_buffer("pr_sd", torch.as_tensor(stats["pr_sd"], dtype=torch.float32))
def tok(self, x): # raw -> z-scored, sd floored (in the stats) and clipped return ((x.float() - self.mu) / self.sd.clamp_min(SD_FLOOR)).clamp(-Z_CLIP, Z_CLIP)
def tok_inv(self, z): # z-scored -> raw return z.float() * self.sd.clamp_min(SD_FLOOR) + self.mu
def pr(self, p): return ((p.float() - self.pr_mu) / self.pr_sd.clamp_min(SD_FLOOR)).clamp(-Z_CLIP, Z_CLIP)
def pr_inv(self, z): return z.float() * self.pr_sd.clamp_min(SD_FLOOR) + self.pr_mu
# --------------------------------------------------------------------------- ## the DINO-WM ViT (vit-pytorch style: PreNorm, Attention, FeedForward, dropout)# --------------------------------------------------------------------------- #class Attention(nn.Module): def __init__(self, dim, heads=16, dim_head=64, dropout=0.0): super().__init__() inner = heads * dim_head self.heads, self.dim_head, self.dropout = heads, dim_head, dropout self.norm = nn.LayerNorm(dim) self.to_qkv = nn.Linear(dim, inner * 3, bias=False) self.to_out = nn.Sequential(nn.Linear(inner, dim), nn.Dropout(dropout))
def forward(self, x): B, N, _ = x.shape q, k, v = self.to_qkv(self.norm(x)).chunk(3, -1) q, k, v = (t.view(B, N, self.heads, self.dim_head).transpose(1, 2) for t in (q, k, v)) o = F.scaled_dot_product_attention(q, k, v, dropout_p=self.dropout if self.training else 0.0) return self.to_out(o.transpose(1, 2).reshape(B, N, -1))
class FeedForward(nn.Module): def __init__(self, dim, hidden, dropout=0.0): super().__init__() self.net = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, hidden), nn.GELU(), nn.Dropout(dropout), nn.Linear(hidden, dim), nn.Dropout(dropout))
def forward(self, x): return self.net(x)
class Transformer(nn.Module): def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout=0.0, grad_ckpt=False): super().__init__() self.layers = nn.ModuleList([nn.ModuleList([Attention(dim, heads, dim_head, dropout), FeedForward(dim, mlp_dim, dropout)]) for _ in range(depth)]) self.norm = nn.LayerNorm(dim) self.grad_ckpt = grad_ckpt
@staticmethod def _block(attn, ff, x): x = x + attn(x) return x + ff(x)
def forward(self, x): for attn, ff in self.layers: if self.grad_ckpt and self.training and torch.is_grad_enabled(): x = torch.utils.checkpoint.checkpoint(self._block, attn, ff, x, use_reentrant=False) else: x = self._block(attn, ff, x) return self.norm(x)
class DWM(nn.Module): """Successor flow in token space with the DINO-WM predictor as the velocity network."""
def __init__(self, n_tok=N_TOK, d_tok=D_TOK, n_pr=9, d_act=56, depth=6, heads=16, dim_head=64, mlp_dim=2048, dropout=0.1, d_act_emb=16, d_pr_emb=8, d_beta_emb=8, d_time_emb=8, n_fourier=6, emb_dropout=0.1, grad_ckpt=False, tok_drop=0.0): super().__init__() self.tok_drop = tok_drop # training-time dropout of WHOLE "now" tokens (regulariser probe) self.n_tok, self.d_tok, self.n_pr, self.d_act = n_tok, d_tok, n_pr, d_act self.d_cond = d_act_emb + d_pr_emb + d_beta_emb + d_time_emb self.dim = d_tok + self.d_cond # 424 self.d_time_emb = d_time_emb; self.n_fourier = n_fourier self.act_emb = nn.Linear(d_act, d_act_emb) self.pr_emb = nn.Linear(max(n_pr, 1), d_pr_emb) self.beta_emb = nn.Linear(2 * n_fourier + 1, d_beta_emb) # the extra proprio token (now: embedded proprio; future: embedded noisy residual) self.pr_tok_now = nn.Linear(max(n_pr, 1), d_tok) self.pr_tok_fut = nn.Linear(max(n_pr, 1), d_tok) self.n_seq = n_tok + 1 self.pos = nn.Parameter(torch.randn(1, self.n_seq, self.dim) * 0.02) self.type_emb = nn.Parameter(torch.randn(2, 1, self.dim) * 0.02) self.drop = nn.Dropout(emb_dropout) self.transformer = Transformer(self.dim, depth, heads, dim_head, mlp_dim, dropout, grad_ckpt) self.head_tok = nn.Linear(self.dim, d_tok) self.head_pr = nn.Linear(self.dim, max(n_pr, 1))
def _cond(self, a, pr, beta, k): c = torch.cat([self.act_emb(a), self.pr_emb(pr if self.n_pr else torch.zeros_like(a[:, :1])), self.beta_emb(beta_fourier(beta.float(), self.n_fourier)), time_embed(k.float(), self.d_time_emb)], -1) return c
def forward(self, tok_now, pr_now, a, beta, xk_tok, xk_pr, k): """tok_now [B,514,384] z-scored; pr_now [B,9] z-scored; a [B,56]; beta [B]; xk_tok [B,514,384] noisy residual; xk_pr [B,9]; k [B] flow time (1 = noise). -> (v_tok [B,514,384], v_pr [B,9])""" B = tok_now.shape[0] pr_in = pr_now if self.n_pr else torch.zeros(B, 1, device=tok_now.device) xk_pr_in = xk_pr if self.n_pr else torch.zeros(B, 1, device=tok_now.device) if self.tok_drop > 0 and self.training: keep = (torch.rand(B, tok_now.shape[1], 1, device=tok_now.device) >= self.tok_drop).to(tok_now.dtype) tok_now = tok_now * keep # dropped token -> 0 = the mean token (z-scored space) now = torch.cat([tok_now, self.pr_tok_now(pr_in)[:, None]], 1) # [B,515,384] fut = torch.cat([xk_tok, self.pr_tok_fut(xk_pr_in)[:, None]], 1) # [B,515,384] c = self._cond(a, pr_in, beta, k)[:, None].expand(-1, self.n_seq, -1) # [B,515,40] now = torch.cat([now, c], -1) + self.pos + self.type_emb[0] fut = torch.cat([fut, c], -1) + self.pos + self.type_emb[1] h = self.transformer(self.drop(torch.cat([now, fut], 1))) # [B,1030,424] hf = h[:, self.n_seq:] v_tok = self.head_tok(hf[:, :self.n_tok]) v_pr = self.head_pr(hf[:, self.n_tok]) return v_tok, (v_pr if self.n_pr else v_pr[:, :0])
class DWMReward(nn.Module): """R(x): mean-pooled tokens per camera (2 x 384) ++ proprio -> MLP 512 x 2 -> logit."""
def __init__(self, n_tok=N_TOK, d_tok=D_TOK, n_pr=9, width=512): super().__init__() self.n_tok, self.n_pr = n_tok, n_pr self.net = nn.Sequential(nn.Linear(2 * d_tok + n_pr, width), nn.SiLU(), nn.Linear(width, width), nn.SiLU(), nn.Linear(width, 1))
@staticmethod def pool(tok): h = tok.shape[1] // 2 return torch.cat([tok[:, :h].mean(1), tok[:, h:].mean(1)], -1)
def forward(self, tok, pr): x = self.pool(tok.float()) if self.n_pr: x = torch.cat([x, pr.float()], -1) return self.net(x).squeeze(-1)
# --------------------------------------------------------------------------- ## sampling# --------------------------------------------------------------------------- #@torch.no_grad()def sample_future_dwm(model, tok_now, pr_now, a, beta, rms_tok, rms_pr, n_steps=8, n=1, x0=None, micro=512, autocast=None, y_clip=Y_CLIP): """Euler ODE sample of the token residual, returned as ABSOLUTE z-scored tokens/proprio. x0: optional (noise_tok [rows,514,384], noise_pr [rows,9]) for common random numbers. autocast: zero-arg callable returning a context manager (default: bf16 on cuda). y_clip: the integrated residual is clamped to +-y_clip (rho units) after every Euler step -- the training target lives in that box, so anything outside it is a diverged velocity, not a successor (stream B measured the MLP flow's velocity growing 170 -> 8500 over 8 steps on held-out episodes; this bounds the damage at read-out). 0 = off. Returns (tok_fut_z [B*n,514,384], pr_fut_z [B*n,9]).""" B = tok_now.shape[0] if n > 1: tok_now = tok_now.repeat_interleave(n, 0); pr_now = pr_now.repeat_interleave(n, 0) a = a.repeat_interleave(n, 0); beta = beta.repeat_interleave(n, 0) R = tok_now.shape[0] dev = tok_now.device if x0 is None: xt = torch.randn(R, model.n_tok, model.d_tok, device=dev) xp = torch.randn(R, model.n_pr, device=dev) else: xt, xp = x0[0].clone(), x0[1].clone() if autocast is None: autocast = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) if dev.type == "cuda" \ else (lambda: torch.autocast("cpu", enabled=False)) for s in range(n_steps): kk = 1.0 - s / n_steps for i in range(0, R, micro): sl = slice(i, i + micro) k = torch.full((xt[sl].shape[0],), kk, device=dev) with autocast(): vt, vp = model(tok_now[sl], pr_now[sl], a[sl], beta[sl], xt[sl], xp[sl], k) xt[sl] = (xt[sl] + vt.float() / n_steps).clamp(-y_clip, y_clip) if y_clip else xt[sl] + vt.float() / n_steps xp[sl] = (xp[sl] + vp.float() / n_steps).clamp(-y_clip, y_clip) if y_clip else xp[sl] + vp.float() / n_steps return tok_now + xt * rms_tok, pr_now + xp * rms_pr
# --------------------------------------------------------------------------- ## synthetic cache with the real layout (tests, and development before stream B's dump)# --------------------------------------------------------------------------- #def make_synthetic_cache(root, n_ep=6, ep_len=(30, 50), seed=0, success_rate=0.5, n_pr=9, adim=7): """Writes meta.npz, act.f32.npy, proprio.f32.npy, z.f16.npy (pooled, via the reference GeM), tokens/tok.f16.npy [N,514,384], tokens/TOKENS.json. Tokens drift smoothly along the episode so a successor has something to learn.""" root = Path(root); (root / "tokens").mkdir(parents=True, exist_ok=True) rng = np.random.default_rng(seed) lens = rng.integers(ep_len[0], ep_len[1] + 1, size=n_ep).astype(np.int64) ep_to = np.cumsum(lens); ep_from = ep_to - lens; N = int(ep_to[-1]) tok = np.lib.format.open_memmap(root / "tokens" / "tok.f16.npy", mode="w+", dtype=np.float16, shape=(N, N_TOK, D_TOK)) act = np.zeros((N, adim), np.float32); pr = np.zeros((N, n_pr), np.float32) base = rng.normal(0, 1, size=(N_TOK, D_TOK)).astype(np.float32) base[1:1 + N_PATCH] = np.abs(base[1:1 + N_PATCH]) + 0.5 # patches mostly positive (GeM) base[2 + N_PATCH:] = np.abs(base[2 + N_PATCH:]) + 0.5 succ = rng.random(n_ep) < success_rate for i in range(n_ep): s, e = int(ep_from[i]), int(ep_to[i]); T = e - s a = np.tanh(rng.normal(0, 0.7, size=(T, adim))).astype(np.float32) a = np.cumsum(a, 0) / np.sqrt(np.arange(1, T + 1))[:, None] # correlated in time act[s:e] = np.clip(a, -1, 1) drift = rng.normal(0, 0.3, size=(D_TOK,)).astype(np.float32) for t in range(T): frac = t / max(T - 1, 1) x = base + frac * drift[None] + 0.05 * rng.normal(size=(N_TOK, D_TOK)).astype(np.float32) x += 0.2 * np.cumsum(act[s:s + t + 1], 0)[-1].sum() * (base > 0) * 0.01 tok[s + t] = x.astype(np.float16) pr[s + t] = np.concatenate([np.cumsum(act[s:s + t + 1, :3], 0)[-1] * 0.05, np.array([1, 0, 0, 0], np.float32), np.array([0.04 - 0.03 * frac, -0.04 + 0.03 * frac])])[:n_pr] tok.flush() # pooled pack with the reference formula (torch avg_pool2d, as obs_core.py) z = np.zeros((N, 4 * D_TOK), np.float16) for i in range(0, N, 64): t = torch.from_numpy(np.asarray(tok[i:i + 64], np.float32)) parts = [] for c0, (p0, p1) in ((TOK_LAYOUT["agent_cls"], TOK_LAYOUT["agent_patch"]), (TOK_LAYOUT["wrist_cls"], TOK_LAYOUT["wrist_patch"])): p = t[:, p0:p1].reshape(t.shape[0], 16, 16, -1).clamp(min=1e-6).permute(0, 3, 1, 2) g = F.avg_pool2d(p.pow(4), (16, 16)).pow(1 / 4).reshape(t.shape[0], -1) parts += [t[:, c0], g] z[i:i + 64] = torch.cat(parts, -1).numpy().astype(np.float16) np.save(root / "z.f16.npy", z) np.save(root / "act.f32.npy", act); np.save(root / "proprio.f32.npy", pr) np.savez(root / "meta.npz", ep_from=ep_from, ep_to=ep_to, ep_len=lens, ep_task=np.zeros(n_ep, np.int64), ep_success=succ, ep_demo=np.zeros(n_ep, bool), tasks=np.array(["synthetic"]), dim=4 * D_TOK, adim=adim, stride=1, n_frames=N) # goal-state label: the last 30 % of frames of every successful episode (env-success-by-replay stand-in) goal = np.zeros(N, np.uint8); first = np.full(n_ep, -1, np.int64) for i in range(n_ep): if succ[i]: s, e = int(ep_from[i]), int(ep_to[i]); first[i] = s + int(0.7 * (e - s)); goal[first[i]:e] = 1 first[i] -= s np.savez(root / "goal.npz", goal=goal, first_success=first, label="synthetic") (root / "tokens" / "TOKENS.json").write_text(json.dumps({ "file": "tok.f16.npy", "shape": [N, N_TOK, D_TOK], "dtype": "float16", "layout": "[agentview CLS, 256 agentview patches, wrist CLS, 256 wrist patches]", "encoder": "synthetic", "synthetic": True}, indent=1)) (root / "PACK.json").write_text(json.dumps({"encoder": "synthetic", "cam_res": 84, "frames": N, "episodes": n_ep, "sd_floor": SD_FLOOR, "z_clip": Z_CLIP}, indent=1)) return root123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""Stage-3 read-out of a DWM checkpoint: Q̄_β(x, A) = E_{x' ~ d_β(.|x, A)}[σ(R(x'))].
from dwm_readout import load_critic_dwm crit = load_critic_dwm("runs/<task>/rsm/DWM/ckpt_best.pt", device) q = crit.q(x_tokens, a_chunk, beta, n_particles=16, crn_seed=0, depth=1, mode="d1", proprio=proprio) # -> [B] in [0, 1]
Inputs are RAW: x_tokens [B, 514, 384] DINOv2 ViT-S/14 tokens at 224 input, in the cache order[agentview CLS, 256 agentview patches, wrist CLS, 256 wrist patches] (fp16/fp32 both fine);proprio [B, 9] = robot0_eef_pos(3) ‖ robot0_eef_quat(4) ‖ robot0_gripper_qpos(2), un-normalised;a_chunk [B, 56] = the next 8 actions flattened (7-d OSC_POSE, in [-1, 1]); beta a float.
mode="d1" one hop from the query chunk, mean over particles of σ(R(x')).mode="fold" is_ope.q_fold's product fold over `depth` hops: hop 1 from the query chunk, hop k+1 from `hop_policy` evaluated on the POOLED 1545-d state of hop k (pool_tokens: [CLS ‖ GeM(patches)] per camera ‖ proprio, RAW units, the same vector cache/<task>/z.f16.npy ‖ proprio.f32.npy holds). Q = c_L; Q = c_k + (1 - c_k) γ^h Q (h = 1/(1-β)), mean over particles. hop_policy(pooled_raw [R, 1545], eps [R, d_act]) -> a_chunk [R, 56]; the caller applies its own feature normalisation (feat_stats.npz) inside that callable. Optional attribute hop_policy.d_act (default 56) sizes the CRN noise eps.
PRIMARY read-out for planning (orchestrator 13:05): the dense expert-membership head with LOGIT averaging, q, q_logit = crit.q(x_tokens, a_chunk, beta, ..., return_logit=True) # rank candidates by q_logitq_logit = mean over particles of R(x'_i) (no sigmoid), which does not saturate/tie at 1.0 the way q does.Temperature: calib_dwm.py fits T on held-out frames -> runs/<task>/rsm/DWM/calib.json; load_critic_dwm reads it(crit.temperature) and q = mean_i sigmoid(logit_i / T); q(..., temperature=T) overrides.Two-stage screening: q(..., n_particles=4, rescore_top=16, n_particles_rescore=64) scores all candidates with 4particles, rescores the top-16 by q_logit with 64 particles, returns full-length arrays.
reward="goal_clf", reward_path="runs/<task>/goal_clf/clf.pt" (PRIVILEGED ABLATION: env success via statereplay, which RISE's baselines never see): the read-out reward is the standalone GOAL-STATEclassifier (train_goal_clf.py; env-success-by-replay label) on the pooled 1545-d state of every sampled futureinstead of the checkpoint's own head; return_logit=True also returns q_logit (mean logit over particles).
Common random numbers: crn_seed seeds a torch.Generator; every particle i draws ONE noisetensor shared by all B rows (candidates), so Q differences between candidates at the samestate are paired (same convention as is_ope.q_fold(crn=True)). Euler ODE with `flow_steps`(8) steps in token space; the EMA weights are used."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))from pathlib import Pathimport numpy as npimport torch
from dwm_model import (DWM, DWMReward, Normalizer, pool_tokens, sample_future_dwm, N_TOK, D_TOK)
class DWMCritic: def __init__(self, ck, device, use_ema=True): a = ck["arch"] self.device = torch.device(device) self.n_pr, self.d_act = int(a["n_pr"]), int(a["d_act"]) self.flow = DWM(a["n_tok"], a["d_tok"], a["n_pr"], a["d_act"], depth=a["depth"], heads=a["heads"], dim_head=a["dim_head"], mlp_dim=a["mlp_dim"], dropout=a["dropout"], emb_dropout=a["dropout"]).to(self.device) self.rew = DWMReward(a["n_tok"], a["d_tok"], a["n_pr"]).to(self.device) self.flow.load_state_dict(ck["flow_ema" if use_ema else "flow"]) self.rew.load_state_dict(ck["rew_ema" if use_ema else "rew"]) self.norm = Normalizer({k: v.numpy() if torch.is_tensor(v) else v for k, v in ck["norm"].items()}).to(self.device) self.rms_tok = ck["rms_tok"].to(self.device); self.rms_pr = ck["rms_pr"].to(self.device) self.config = dict(ck["config"]); self.step = int(ck.get("step", -1)) self.temperature = 1.0; self.calib = None self.q_action_winrate = ck.get("q_action_winrate", float("nan")) for m in (self.flow, self.rew): m.eval() for p in m.parameters(): p.requires_grad_(False) self.autocast = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) if self.device.type == "cuda" \ else (lambda: torch.autocast("cpu", enabled=False))
# ---- helpers ---- def _prep(self, x_tokens, proprio, a_chunk): x = torch.as_tensor(x_tokens).to(self.device) 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)}" B = x.shape[0] if self.n_pr: assert proprio is not None, "this checkpoint models proprio: pass proprio=[B, 9]" p = torch.as_tensor(proprio).to(self.device).float().view(B, self.n_pr) else: p = torch.zeros(B, 0, device=self.device) a = torch.as_tensor(a_chunk).to(self.device).float().view(B, -1) assert a.shape[1] == self.d_act, f"a_chunk must be [B,{self.d_act}] (chunk x adim flattened)" return self.norm.tok(x), self.norm.pr(p), a
@torch.no_grad() def reward(self, x_tokens, proprio=None, reward="head", reward_path=None): """σ(R(x)) on RAW tokens/proprio -> [B]; reward='goal_clf' uses the goal classifier.""" tz, pz, _ = self._prep(x_tokens, proprio, torch.zeros(len(x_tokens), self.d_act)) if reward == "goal_clf": if reward_path is not None and getattr(self, "goal_clf", {}).get("path") != str(reward_path): self.load_goal_clf(reward_path) return torch.sigmoid(self.goal_logit(tz, pz)) with self.autocast(): return torch.sigmoid(self.rew(tz, pz).float())
@torch.no_grad() def sample_future(self, x_tokens, a_chunk, beta, proprio=None, n=1, crn_seed=None, flow_steps=8, micro=512): """Raw-unit successor samples: (tokens [B*n,514,384], proprio [B*n,9]).""" tz, pz, a = self._prep(x_tokens, proprio, a_chunk) B = tz.shape[0] bq = torch.full((B,), float(beta), device=self.device) x0 = self._crn_noise(B, n, crn_seed) if crn_seed is not None else None xt, xp = sample_future_dwm(self.flow, tz, pz, a, bq, self.rms_tok, self.rms_pr, flow_steps, n=n, x0=x0, micro=micro, autocast=self.autocast) return self.norm.tok_inv(xt), self.norm.pr_inv(xp)
# ---- goal-state classifier read-out (orchestrator 2026-09-18: R must be a goal classifier) ---- def load_goal_clf(self, path): """train_goal_clf.py checkpoint: MLP on the pooled z-scored state; cached on the critic.""" ck = torch.load(str(path), map_location="cpu", weights_only=False) c = ck["config"] from train_goal_clf import build_net net = build_net(c["d_in"], c["width"], c["depth"]).to(self.device) net.load_state_dict(ck["net"]); net.eval() for p in net.parameters(): p.requires_grad_(False) nm = ck["norm"] self.goal_clf = {"net": net, "mu": nm["mu"].to(self.device), "sd": nm["sd"].to(self.device), "z_clip": float(nm["z_clip"]), "sd_floor": float(nm.get("sd_floor", 0.01)), "path": str(path), "config": c} return self.goal_clf
def goal_logit(self, tz, pz): """logit of 'goal state' for z-scored token/proprio tensors (sampled futures or real frames).""" g = self.goal_clf pooled = pool_tokens(self.norm.tok_inv(tz), self.norm.pr_inv(pz) if self.n_pr else None) # raw 1545 x = (pooled - g["mu"]) / g["sd"].clamp_min(g["sd_floor"]) if g["z_clip"]: x = x.clamp(-g["z_clip"], g["z_clip"]) return g["net"](x).squeeze(-1).float()
def _gen(self, seed): g = torch.Generator(device=self.device); g.manual_seed(int(seed)); return g
def _crn_noise(self, B, n, seed, gen=None): """[n, ...] noise per particle, tiled over the B rows (rows are repeat_interleave'd by particle, so particle i of row b sits at b*n + i -> tile with .repeat(B, ...)).""" g = gen if gen is not None else self._gen(seed) nt = torch.randn(n, N_TOK, D_TOK, device=self.device, generator=g).repeat(B, 1, 1) npr = torch.randn(n, self.n_pr, device=self.device, generator=g).repeat(B, 1) return nt, npr
@torch.no_grad() def q(self, x_tokens, a_chunk, beta, n_particles=16, crn_seed=0, depth=1, mode="d1", proprio=None, hop_policy=None, gamma=0.99, flow_steps=8, micro=512, return_hops=False, reward="head", reward_path=None, return_logit=False, temperature=None, rescore_top=0, n_particles_rescore=0): """Q̄ estimate per row. See the module docstring. reward="head": the checkpoint's own reward head R (trained on the run's --reward-mode label). reward="goal_clf": the standalone goal-state classifier (train_goal_clf.py; PRIVILEGED ablation) on the POOLED state of each sampled future; reward_path = its clf.pt (loaded once and cached). temperature: q = mean_i sigmoid(logit_i / T). None -> self.temperature (calib.json next to the checkpoint, fitted by calib_dwm.py on held-out frames; 1.0 if absent). q_logit is the RAW mean logit (ranking is T-free). rescore_top=K, n_particles_rescore=M: two-stage screening -- score every candidate with n_particles, keep the top-K by q_logit, rescore those with M particles (CRN seed family crn_seed -> crn_seed*7919+1) and write the rescored values back; non-rescored rows keep their stage-1 values. Full-length outputs. return_logit=True -> (q, q_logit); return_hops=True -> (out, [c_k [B, n]]) of the stage-1 pass.""" if reward == "goal_clf": if reward_path is not None and getattr(self, "goal_clf", {}).get("path") != str(reward_path): self.load_goal_clf(reward_path) assert getattr(self, "goal_clf", None), "reward='goal_clf' needs reward_path=<clf.pt> once" elif reward != "head": raise ValueError(f"reward {reward!r}: use 'head' or 'goal_clf'") if mode == "d1": depth = 1 elif mode not in ("fold", "mpc", "mpc_disc"): # gen_q#273: "mpc" / "mpc_disc" are the MPC read-outs -- the SAME open-loop roll-out the fold # performs, combined differently (terminal latent / discounted sum) instead of through the # beta-hazard fold. Additive: "d1" and "fold" take byte-identical code paths. raise ValueError(f"mode {mode!r}: use 'd1', 'fold', 'mpc' or 'mpc_disc'") if depth > 1 and hop_policy is None: raise ValueError("depth > 1 needs hop_policy(pooled_raw [R,1545], eps [R,d_act]) -> a_chunk") T = float(self.temperature if temperature is None else temperature) tz, pz, a = self._prep(x_tokens, proprio, a_chunk) q, ql, cs = self._q_once(tz, pz, a, beta, int(n_particles), self._gen(crn_seed), depth, mode, hop_policy, gamma, flow_steps, micro, reward, T) if rescore_top and n_particles_rescore and rescore_top < tz.shape[0]: top = torch.topk(ql, int(rescore_top)).indices q2, ql2, _ = self._q_once(tz[top], pz[top], a[top], beta, int(n_particles_rescore), self._gen(int(crn_seed) * 7919 + 1), depth, mode, hop_policy, gamma, flow_steps, micro, reward, T) q = q.clone(); ql = ql.clone(); q[top] = q2; ql[top] = ql2 out = (q, ql) if return_logit else q if return_hops: return out, cs return out
# ---- the two things a different dynamics model has to change (gen_q#268) ------------------- # Factored out so DINO-WM (dinowm_readout.DINOWMCritic) can subclass this class and override # ONLY the transition and the hop length, exactly as TDFlowAgent subclasses RSMAgent to override # only the occupancy target. Everything else -- the fold algebra, the hop-policy chaining, the # reward head, the normaliser, the temperature, the two-stage rescore -- is then literally the # same code, which is what makes the two columns of a matched-proposer table comparable. def _step(self, tzr, pzr, ar, bq, B, n, g, flow_steps, micro): """One hop: a DRAW from the beta-discounted successor, by Euler-integrating the flow.""" x0 = self._crn_noise(B, n, None, gen=g) return sample_future_dwm(self.flow, tzr, pzr, ar, bq, self.rms_tok, self.rms_pr, flow_steps, n=1, x0=x0, micro=micro, autocast=self.autocast)
def _hop_frames(self, beta): """Frames one hop spans, for the fold's per-hop discount gamma ** h.""" return 1.0 / (1.0 - float(beta))
def _q_once(self, tz, pz, a, beta, n, g, depth, mode, hop_policy, gamma, flow_steps, micro, reward, T): B = tz.shape[0] tzr = tz.repeat_interleave(n, 0); pzr = pz.repeat_interleave(n, 0); ar = a.repeat_interleave(n, 0) bq = torch.full((B * n,), float(beta), device=self.device) cs = [] for k in range(depth): tzr, pzr = self._step(tzr, pzr, ar, bq, B, n, g, flow_steps, micro) with self.autocast(): lg = self.goal_logit(tzr, pzr) if reward == "goal_clf" else self.rew(tzr, pzr).float() cs.append(torch.sigmoid(lg / T)) if k == depth - 1: break pooled = pool_tokens(self.norm.tok_inv(tzr), self.norm.pr_inv(pzr) if self.n_pr else None) d_act = int(getattr(hop_policy, "d_act", self.d_act)) eps = torch.randn(n, d_act, device=self.device, generator=g).repeat(B, 1) ar = torch.as_tensor(hop_policy(pooled, eps)).to(self.device).float().view(B * n, -1) assert ar.shape[1] == self.d_act, "hop_policy must return [R, chunk*adim] chunks" if mode == "d1": q = cs[0] elif mode in ("mpc", "mpc_disc"): # gen_q#273 -- MPC READ-OUTS. `cs[k]` is the reward head on the latent the model predicts # after k+1 chunks of open-loop rolling, so the roll-out itself is unchanged; only the way the # per-step rewards are combined differs from the fold above. # mpc : the TERMINAL latent only -- score(s_K), K = depth chunks = the H frames the # discount defines. This is what a world-model MPC objective is. # mpc_disc : the discounted sum over the same roll-out with the SAME gamma that defines H, # normalised by sum_k gamma**(h k) so it stays a probability in [0, 1] and is # comparable ACROSS horizons (an unnormalised sum grows with K and would rank # longer horizons higher for arithmetic reasons alone). h = self._hop_frames(beta) if mode == "mpc": q = cs[-1] else: w = [float(gamma) ** (h * k) for k in range(len(cs))] tot = float(sum(w)) q = sum(wk * c for wk, c in zip(w, cs)) / tot else: h = self._hop_frames(beta) q = torch.zeros_like(cs[-1]) for c in reversed(cs): q = c + (1.0 - c) * (gamma ** h) * q q = torch.nan_to_num(q, nan=0.0).clamp(0.0, 1.0).view(B, n).mean(1) q_logit = torch.nan_to_num(lg, nan=0.0).view(B, n).mean(1) return q, q_logit, [c.view(B, n) for c in cs]
def load_critic_dwm(path, device="cuda", use_ema=True, calib="auto") -> DWMCritic: """calib: "auto" reads <dir of path>/calib.json (calib_dwm.py) and sets crit.temperature = T if present; a float sets T directly; None/False leaves T = 1.0.""" ck = torch.load(str(path), map_location="cpu", weights_only=False) _m = str(ck.get("model", "dwm")) if _m != "dwm": raise RuntimeError( f"{path} is a '{_m}' checkpoint (config dynamics=" f"{dict(ck.get('config', {})).get('dynamics')!r}), not a flow DWM. Load it with the " f"read-out for that model (dinowm_readout.load_critic_dwm) -- Euler-integrating a " f"network that was never trained as a velocity field would report a number that is " f"neither method.") crit = DWMCritic(ck, device, use_ema=use_ema) if isinstance(calib, (int, float)) and not isinstance(calib, bool): crit.temperature = float(calib) elif calib == "auto": cj = Path(path).parent / "calib.json" if cj.exists(): try: import json crit.calib = json.loads(cj.read_text()); crit.temperature = float(crit.calib["T"]) except Exception as e: print(f"[dwm_readout] calib.json unreadable ({e}); T=1", flush=True) return crit
# --------------------------------------------------------------------------- #@torch.no_grad()def verify_pooling(cache_dir, n=512, seed=0, tokens_file=""): """pool_tokens(tokens, proprio) vs the pooled pack z.f16.npy ‖ proprio.f32.npy on n random frames. Returns dict(max_abs, max_rel, fp16_ok). fp16_ok: every |diff| <= 2 fp16 ulps of the stored value (the pack is fp16-rounded; the pooling itself is fp32).""" cache_dir = Path(cache_dir) z = np.load(cache_dir / "z.f16.npy", mmap_mode="r") pr = np.load(cache_dir / "proprio.f32.npy", mmap_mode="r") if (cache_dir / "proprio.f32.npy").exists() else None tf = Path(tokens_file) if tokens_file else cache_dir / "tokens" / "tok.f16.npy" tok = np.load(tf, mmap_mode="r") assert tok.shape[0] == z.shape[0], f"tokens {tok.shape[0]} frames vs pooled {z.shape[0]}" rng = np.random.default_rng(seed) idx = np.sort(rng.choice(tok.shape[0], size=min(n, tok.shape[0]), replace=False)) t = torch.from_numpy(np.asarray(tok[idx], np.float32)) p = torch.from_numpy(np.asarray(pr[idx], np.float32)) if pr is not None else None got = pool_tokens(t, p).numpy() ref = np.asarray(z[idx], np.float32) if p is not None: ref = np.concatenate([ref, p.numpy()], -1) assert got.shape == ref.shape, f"pooled dim {got.shape[1]} vs pack {ref.shape[1]}" diff = np.abs(got - ref) ulp = np.abs(np.asarray(ref, np.float16)).astype(np.float32) * 2 ** -10 + 1e-6 ok = bool((diff <= 2 * ulp + 1e-4).all()) return {"n": int(len(idx)), "dim": int(got.shape[1]), "max_abs": float(diff.max()), "max_rel": float((diff / (np.abs(ref) + 1e-3)).max()), "fp16_ok": ok, "frac_within_2ulp": float((diff <= 2 * ulp + 1e-4).mean())}
if __name__ == "__main__": import argparse, json ap = argparse.ArgumentParser(description="verify pool_tokens against the pooled pack") ap.add_argument("--cache", required=True); ap.add_argument("--n", type=int, default=512) ap.add_argument("--tokens", default="") a = ap.parse_args() print(json.dumps(verify_pooling(a.cache, a.n, tokens_file=a.tokens), indent=1))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Cost of one planning step with the DWM read-out at N=128 candidates (orchestrator, 13:20 UTC).
One real held-out state (tokens + proprio) and 128 candidate 8-step chunks; times (CUDA-synchronised, median of--reps) for flat n_particles in {4, 16, 64} and for the two-stage screen (4 -> top-16 x 64), in d1 mode, plus theagreement between the rankings. Candidates: `--chunks hop` loads stream B's hop head (runs/<task>/hop/flow) if itsloader is importable, else (default `logged`) 128 logged chunks from 128 random frames of the val split -- the timingdoes not depend on which chunks are used. Writes <out>/readout_timing.json."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, json, timefrom pathlib import Pathimport numpy as npimport torch
from dwm_model import TokenRSMDatafrom dwm_readout import load_critic_dwm
def timed(fn, reps, dev): fn() # warm-up (compile/caches) ts = [] for _ in range(reps): if dev.type == "cuda": torch.cuda.synchronize() t0 = time.time(); out = fn() if dev.type == "cuda": torch.cuda.synchronize() ts.append(time.time() - t0) return float(np.median(ts)), out
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True); ap.add_argument("--ckpt", required=True) ap.add_argument("--n-cand", type=int, default=128); ap.add_argument("--reps", type=int, default=3) ap.add_argument("--beta", type=float, default=0.95); ap.add_argument("--micro", type=int, default=512) ap.add_argument("--seed", type=int, default=0); ap.add_argument("--out", default="") a = ap.parse_args() dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") d = TokenRSMData(a.cache, chunk=8, seed=a.seed) crit = load_critic_dwm(a.ckpt, dev) rng = np.random.default_rng(a.seed) fb = d.sample_frames(1, rng, "val"); cb = d.sample_frames(a.n_cand, rng, "val") N = a.n_cand x = torch.as_tensor(fb["x"]).expand(N, -1, -1).contiguous(); pr = torch.as_tensor(fb["pr_now"]).expand(N, -1).contiguous() a_c = cb["a"] res = {"n_cand": N, "beta": a.beta, "device": torch.cuda.get_device_name(0) if dev.type == "cuda" else "cpu", "ckpt": a.ckpt, "step": crit.step, "temperature": crit.temperature, "micro": a.micro, "reps": a.reps} outs = {} for n in (4, 16, 64): t, (q, ql) = timed(lambda: crit.q(x, a_c, a.beta, n_particles=n, crn_seed=0, proprio=pr, micro=a.micro, return_logit=True), a.reps, dev) outs[n] = ql.cpu().numpy() res[f"flat_{n}_particles_s"] = t res[f"flat_{n}_q_mean"] = float(q.mean()); res[f"flat_{n}_q_max"] = float(q.max()) res[f"flat_{n}_frac_q_gt_0.99"] = float((q > 0.99).float().mean()) print(f"[timing] flat n={n}: {t:.3f} s for {N} candidates ({N*n*8} ViT forwards); q mean {float(q.mean()):.3f} " f"max {float(q.max()):.3f} frac>0.99 {float((q > 0.99).float().mean()):.3f}", flush=True) t, (q2, ql2) = timed(lambda: crit.q(x, a_c, a.beta, n_particles=4, rescore_top=16, n_particles_rescore=64, crn_seed=0, proprio=pr, micro=a.micro, return_logit=True), a.reps, dev) res["two_stage_4_top16_64_s"] = t top64 = set(np.argsort(-outs[64])[:16].tolist()); top2 = set(np.argsort(-ql2.cpu().numpy())[:16].tolist()) top4 = set(np.argsort(-outs[4])[:16].tolist()) res["top16_overlap_two_stage_vs_flat64"] = len(top64 & top2) / 16 res["top16_overlap_flat4_vs_flat64"] = len(top64 & top4) / 16 res["argmax_agree_two_stage_vs_flat64"] = bool(int(np.argmax(outs[64])) == int(torch.argmax(ql2))) res["spearman_flat4_vs_flat64"] = float(np.corrcoef(np.argsort(np.argsort(outs[4])), np.argsort(np.argsort(outs[64])))[0, 1]) 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} " f"(flat-4 alone {res['top16_overlap_flat4_vs_flat64']:.2f}); spearman flat4/flat64 {res['spearman_flat4_vs_flat64']:.3f}", flush=True) out = Path(a.out) if a.out else Path(a.ckpt).parent / "readout_timing.json" out.write_text(json.dumps(res, indent=1)); print(f"[timing] -> {out}", flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Encode RLinf LeRobot parquet rollouts straight from their RECORDED frames into theper-episode npz the cache packer consumes (z fp16 [T,4096], proprio [T,8], actions [T,7],success, prompt, task_index) -- no re-rendering, no EGL.
The recorded frames ARE the evaluation environment's frames (the collector renders atcam_res 256 and RLinf stores them upright, i.e. already in the evaluator's servingorientation), and the parquet `state` equals the evaluator's proprio exactly (checked:max |state - proprio| = 0 on the existing corpus). The encoder is whatever OGPO_PI05_BASEpoints at, so this is how a LIBERO-finetuned pi0.5 (lerobot/pi05_libero_base) becomes thefeature encoder for a new cache; the tag is recorded in every episode.
usage: OGPO_PI05_BASE=<ckpt dir> encode_parquet.py --root <collect root> --out <corpus dir> [--shard i --num-shards n] [--task-file lib10_tasks.txt]Layout in: <root>/task{t}_block{b}/rank_*/id_{i}/data/chunk-*/episode_{k:06d}.parquetLayout out: <out>/<taskname>/ep_t{t}_b{b}_i{i}_{k:06d}.npz (same as the existing corpus)"""from __future__ import annotationsimport argparse, io, os, re, sys, glob, timefrom pathlib import Pathimport numpy as npsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from eval_closed_loop import BUILDER, ogpo, to224 # the evaluator's own encoder path
PAT = re.compile(r"task(\d+)_block(\d+)/rank_(\d+)/id_(\d+)/data/chunk-(\d+)/episode_(\d+)\.parquet$")
def main(): ap = argparse.ArgumentParser() ap.add_argument("--root", required=True); ap.add_argument("--out", required=True) ap.add_argument("--shard", type=int, default=0); ap.add_argument("--num-shards", type=int, default=1) ap.add_argument("--batch", type=int, default=64) ap.add_argument("--task-file", default=os.environ.get("RSM_TASKS_FILE", "")) a = ap.parse_args() import torch, pyarrow.parquet as pq from PIL import Image from libero.libero import benchmark dev = "cuda" if torch.cuda.is_available() else "cpu" enc_tag = os.path.basename(os.path.normpath(os.environ.get("OGPO_PI05_BASE", "pi05_base_pytorch"))) canon = [n.strip() for n in Path(a.task_file).read_text().replace("\n", ",").split(",") if n.strip()] bench = benchmark.get_benchmark_dict()["libero_10"]() lang = {bench.get_task(i).name: bench.get_task(i).language for i in range(bench.n_tasks)} files = sorted(glob.glob(f"{a.root}/task*_block*/rank_*/id_*/data/chunk-*/episode_*.parquet")) files = [f for k, f in enumerate(files) if k % a.num_shards == a.shard] print(f"[enc] encoder={enc_tag} shard {a.shard}/{a.num_shards}: {len(files)} episodes", flush=True) model = ogpo.build_paligemma(dev) ids_cache = {} n_done = n_skip = 0; t0 = time.time() for k, f in enumerate(files): m = PAT.search(f) if not m: continue 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))) tname = canon[t] op = Path(a.out) / tname / f"ep_t{t}_b{b}_i{i}_{ep:06d}.npz" if op.exists(): n_skip += 1; continue tb = pq.read_table(f, columns=["state", "actions", "is_success", "image", "wrist_image"]) st = np.asarray(tb.column("state").to_pylist(), np.float32) ac = np.asarray(tb.column("actions").to_pylist(), np.float32) succ = bool(np.asarray(tb.column("is_success").to_pylist()).any()) frames = {} for cam in ("image", "wrist_image"): col = tb.column(cam).to_pylist() frames[cam] = np.stack([to224(np.asarray(Image.open(io.BytesIO(x["bytes"])).convert("RGB"))) for x in col]) if t not in ids_cache: ids_cache[t] = ogpo.tokenize_prompt(lang[tname]) za = ogpo.encode_frames(model, frames["image"], ids_cache[t], dev, a.batch) zw = ogpo.encode_frames(model, frames["wrist_image"], ids_cache[t], dev, a.batch) z = np.concatenate([za, zw], 1).astype(np.float16) op.parent.mkdir(parents=True, exist_ok=True) tmp = str(op) + ".tmp.npz" np.savez(tmp, z=z, proprio=st, actions=ac, success=succ, prompt=ids_cache[t], task_index=t, encoder=enc_tag, cam_res=256) os.replace(tmp, op); n_done += 1 if n_done % 20 == 0: el = time.time() - t0 print(f"[enc] {k+1}/{len(files)} done={n_done} skip={n_skip} {el/n_done:.1f}s/ep", flush=True) print(f"[enc] DONE shard {a.shard}: {n_done} written, {n_skip} existed, encoder={enc_tag}", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Encode the ten LIBERO-10 instructions with T5 and cache the vectors.
Replaces the learned nn.Embedding(n_task) conditioning. An index lookup carries noinformation about WHAT the task is: it cannot transfer to a held-out instruction, and itgives the network a free shortcut so nothing forces the visual latent to represent theinstruction. A frozen T5 embedding conditions on the sentence itself.
Ten short strings, so this runs once and the result is a few hundred KB."""import argparse, numpy as np, torch, os
ap = argparse.ArgumentParser()ap.add_argument("--cache", required=True)ap.add_argument("--out", required=True)ap.add_argument("--model", default="google-t5/t5-11b")ap.add_argument("--pool", default="mean", choices=["mean", "first"])a = ap.parse_args()
m = np.load(f"{a.cache}/meta.npz", allow_pickle=True)# the cache stores directory names; recover the instruction the way the evaluator doesfrom libero.libero import benchmarkb = benchmark.get_benchmark_dict()["libero_10"]()names = [str(t) for t in m["tasks"]]by_name = {b.get_task(i).name: b.get_task(i).language for i in range(b.n_tasks)}texts = [by_name.get(n, n.replace("_", " ")) for n in names]for i, t in enumerate(texts): print(f" [{i}] {t}", flush=True)
from transformers import T5EncoderModel, T5Tokenizertok = T5Tokenizer.from_pretrained(a.model, legacy=False)enc = T5EncoderModel.from_pretrained(a.model, torch_dtype=torch.float16).eval()dev = "cuda" if torch.cuda.is_available() else "cpu"enc = enc.to(dev)with torch.no_grad(): bt = tok(texts, return_tensors="pt", padding=True) out = enc(input_ids=bt["input_ids"].to(dev), attention_mask=bt["attention_mask"].to(dev)).last_hidden_state msk = bt["attention_mask"].to(dev).unsqueeze(-1).float() vec = ((out.float() * msk).sum(1) / msk.sum(1)) if a.pool == "mean" else out[:, 0].float()vec = vec.cpu().numpy().astype(np.float32)np.savez(a.out, emb=vec, tasks=np.array(names, dtype=object), texts=np.array(texts, dtype=object), model=a.model, pool=a.pool)print(f"[t5] wrote {a.out} shape={vec.shape} " f"norm mean={np.linalg.norm(vec,axis=1).mean():.2f}", flush=True)# sanity: the two LIVING_ROOM_SCENE2 tasks differ only in the objects namedimport itertoolsD = np.linalg.norm(vec[:, None] - vec[None], axis=-1)iu = list(itertools.combinations(range(len(vec)), 2))d = [(D[i, j], i, j) for i, j in iu]d.sort()print(f"[t5] closest pair : t{d[0][1]} / t{d[0][2]} dist {d[0][0]:.2f}")print(f"[t5] farthest pair : t{d[-1][1]} / t{d[-1][2]} dist {d[-1][0]:.2f}")12345678910111213141516#!/bin/bash#SBATCH --job-name=encode_t5#SBATCH --account=vision-pulkitag#SBATCH --gres=gpu:1 --cpus-per-task=8 --mem=120G#SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.out#SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.errset -uo pipefailB=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationS=/data/pulkitag/users/rli14/rlinf_recap_task_expansionexport LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standardexport MUJOCO_GL=osmesa PYTHONUNBUFFERED=1export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1$B/venvs/rlinf-libero-eval-venv/bin/python \ /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/encode_t5.py \ --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ --out /data/pulkitag/users/rli14/rsm_libero_runs/t5_lib10.npz12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025"""Closed-loop LIBERO-10 success rate for an rsm_libero policy.
Reuses the LANE'S evaluator wholesale -- featurization, env construction, seeding,task ordering, chunk execution -- and swaps ONLY the policy call. That isdeliberate: the 0.584 +- 0.025 `bcdemos_m120k` bar was produced by`09032026_latent_head_eval.py`, and a success rate measured by any other harnessis not comparable to it.
Featurization contract copied exactly from that evaluator: * ROT180 to serving orientation (`obs[key][::-1, ::-1]`) * 128 -> 224 bilinear * per-camera 2048-d pool, agentview ++ wrist -> 4096 * proprio = eef_pos(3) ++ eef_ori(3) ++ gripper_qpos(2) = 8
Features are z-scored with the SAME per-dim statistics the policy trained under,loaded from the training cache (`feat_stats.npz`). Getting normalisation wrong ineither direction evaluates a good policy off-distribution and isindistinguishable from the policy being bad, so the stats travel with the runrather than being reconstructed here."""from __future__ import annotationsimport argparse, hashlib, importlib.util, json, os, sysfrom pathlib import Pathimport numpy as npimport torch
WT = os.environ.get("RSM_WT", "/data/pulkitag/hamer_diffusion_policy_project/projects/" "continual_learning_for_manipulation/.claude/worktrees/08312026_jvq_recap_worktree")# RSM_WT: the CLM worktree holding scripts/rlinf_jvq (the latent-cache BUILDER). On IBM it# is /proj/dmfexp/zwhong/rli14_jvq_worktree; the builder itself reads OGPO_PI05_BASE and# OGPO_TOKENIZER for its weights.sys.path.insert(0, WT + "/scripts/rlinf_jvq")sys.path.insert(0, str(Path(__file__).resolve().parent))
# build_paligemma / tokenize_prompt / encode_frames live in the latent-cache# BUILDER; the rollout producer merely imports it under the local name `ogpo`.# Importing the producer instead gives a module without those attributes, which# kills the evaluator on its first line of work. This is the SAME builder that# wrote the training cache -- verified to reproduce it at cos 0.9999 offline and# 0.9903 from live env frames.BUILDER = WT + "/scripts/rlinf_jvq/08312026_1110pm_ogpo_latent_cache.py"_spec = importlib.util.spec_from_file_location("ogpo_cache", BUILDER)ogpo = importlib.util.module_from_spec(_spec)sys.modules["ogpo_cache"] = ogpo_spec.loader.exec_module(ogpo)
from model import Encoder, FlowPolicy, BCHead, ConcatFlowPolicyfrom is_ope import _LatWithProprio
def to224(img): """128 -> 224 bilinear, then ROUND AND CLAMP TO uint8.
The uint8 quantisation is not cosmetic. The latent cache was built from PIL uint8 images, so the encoder has only ever seen quantised pixels. Feeding it the raw float32 interpolation instead shifts the latent by up to 0.31 in a space whose per-dimension standard deviation is 0.107 -- a three-sigma perturbation on the dimensions that matter, re-applied at every one of the ~52 chunk decisions in an episode. Measured: the lane's own 0.584 policy scores 0/50 through this evaluator with float input and 0.46 through its own evaluator, which quantises. Cosine similarity (0.999898) hides this entirely, which is why it was not caught by the featurisation checks. """ t = torch.from_numpy(np.ascontiguousarray(img[None])).permute(0, 3, 1, 2).float() t = torch.nn.functional.interpolate(t, size=(224, 224), mode="bilinear", align_corners=False) return t.permute(0, 2, 3, 1).round().clamp(0, 255).byte().numpy()[0]
def _eef_ori(obs): """End-effector orientation as AXIS-ANGLE, matching the cache.
This was the bug that produced 0% everywhere. The cache's 8-d proprio is eef_pos(3) ++ ee_ori(3) ++ gripper_qpos(2), and LIBERO's `ee_ori` is robosuite AXIS-ANGLE. This evaluator previously converted the quaternion to Euler roll/pitch/yaw, so three of the eight proprio dimensions were a different quantity at every timestep. The policy still emitted plausible first actions -- the visual latent dominates the input -- which is why the featurisation checks, the offline fit and even a bit-exact comparison of the first action chunk all looked healthy.
Measured with the lane's own 0.584 policy on task 5: 0/5 through this evaluator with Euler, 5/5 through theirs with axis-angle, same machine and same weights. """ q = obs.get("robot0_eef_quat") if q is None: return np.zeros(3, np.float32) try: from robosuite.utils.transform_utils import quat2axisangle return np.asarray(quat2axisangle(np.asarray(q)), dtype=np.float32) except Exception: w = np.clip(q[3], -1, 1) ang = 2 * np.arccos(abs(w)) axis = q[:3] / (np.linalg.norm(q[:3]) + 1e-8) return (axis * ang).astype(np.float32)
_oodx = [] # (task, online t=0 feature) when --probe-ood: lets the online region be # compared against the cached demo and rollout clouds offline
# A checkpoint records the cache it trained on. When it was trained on the OTHER cluster,# resolve that path to the local twin: both caches are packed from the same pinned# episode list (index-identical, latents bit-identical) and their stats come from the# same arrays. Extend with RSM_CACHE_REMAP="from1=to1,from2=to2" if a new pair appears._CACHE_TWINS = { "/proj/dmfexp/zwhong/rsm_libero/cache/": "/data/pulkitag/users/rli14/rsm_libero_cache/", "/data/pulkitag/users/rli14/rsm_libero_cache/": "/proj/dmfexp/zwhong/rsm_libero/cache/",}
def _resolve_cache(path): import os as _os p = str(path or "") if not p or _os.path.exists(p): return p pairs = list(_CACHE_TWINS.items()) for kv in filter(None, _os.environ.get("RSM_CACHE_REMAP", "").split(",")): a, b = kv.split("=", 1); pairs.append((a, b)) for a, b in pairs: if p.startswith(a) and _os.path.exists(b + p[len(a):]): print(f"[cache] {p} -> {b + p[len(a):]} (cluster twin)", flush=True) return b + p[len(a):] return p
def _declared_cam_res(ckpt_path): """What resolution were this checkpoint's latents rendered at? From the checkpoint itself, else from its cache's RENDER.json / PACK.json. 'UNKNOWN' if neither.""" import json as _j try: ck = torch.load(ckpt_path, map_location="cpu", weights_only=False) except Exception: return "UNKNOWN" if ck.get("cam_res") not in (None, "UNKNOWN"): return ck["cam_res"] cache = _resolve_cache((ck.get("config") or {}).get("cache", "")) for f in ("RENDER.json", "PACK.json"): try: v = _j.load(open(f"{cache}/{f}")).get("cam_res") if v is not None: return v except Exception: pass return "UNKNOWN"
def _declared_encoder(ckpt_path): """Which feature encoder produced this checkpoint's latents (basename of the OGPO_PI05_BASE it was built with). Legacy checkpoints predate the tag -> pi05_base_pytorch.""" import json as _j try: ck = torch.load(ckpt_path, map_location="cpu", weights_only=False) except Exception: return "UNKNOWN" if ck.get("encoder"): return ck["encoder"] cache = _resolve_cache((ck.get("config") or {}).get("cache", "")) for f in ("PACK.json", "RENDER.json"): try: v = _j.load(open(os.path.join(cache, f))).get("encoder") if v: return v except Exception: pass return "pi05_base_pytorch"
def _guard_encoder(args): """Refuse to evaluate with a feature encoder different from the one the latents were encoded with (the 128/256 lesson applied to the encoder weights themselves).""" mine = os.path.basename(os.path.normpath(os.environ.get("OGPO_PI05_BASE", "pi05_base_pytorch"))) bad = [] for label, path in (("policy", args.policy), ("policy2", getattr(args, "policy2", "")), ("critic", args.critic), ("qf-ckpt", args.qf_ckpt), ("hop-policy", getattr(args, "hop_policy", ""))): if not path: continue v = _declared_encoder(path) if v != mine: bad.append(f"{label} {path}: latents from encoder '{v}', evaluator encoder '{mine}'") if bad and not args.allow_cam_mismatch: raise SystemExit("[guard] ENCODER MISMATCH -- refusing:\n " + "\n ".join(bad)) for b in bad: print(f"[guard] OVERRIDDEN encoder mismatch: {b}", flush=True)
def _guard_render_resolution(args): """Refuse to evaluate a policy/critic at a resolution its latents were not rendered at. This is the defect that voided every result before 2026-09-13 (i251): rollout latents at 256, evaluator at 128, and nothing complained.""" bad = [] for label, path in (("policy", args.policy), ("critic", args.critic), ("qf-ckpt", args.qf_ckpt), ("hop-policy", getattr(args, "hop_policy", ""))): if not path: continue v = _declared_cam_res(path) if v == "UNKNOWN": # trusting an undeclared checkpoint is exactly how the 128/256 mismatch ran # unnoticed for weeks; undeclared is refused like a mismatch bad.append(f"{label} {path}: render resolution UNDECLARED (no cam_res in checkpoint " f"or in its cache's RENDER.json/PACK.json)") elif str(v) != str(args.cam_res): bad.append(f"{label} {path}: latents rendered at {v}, evaluator at {args.cam_res}") if bad and not args.allow_cam_mismatch: raise SystemExit("[guard] RENDER RESOLUTION MISMATCH -- refusing:\n " + "\n ".join(bad) + "\n (--allow-cam-mismatch 1 to override; never for a reported number)") for b in bad: print(f"[guard] OVERRIDDEN mismatch: {b}", flush=True)
def load_policy(critic_path, policy_path, n_task, device, lane_norm=""): """Encoder from the critic checkpoint + the trained policy.
The policy may read the FULL observation (`policy_features=raw`, the default since the reward-predictive bottleneck was found to strip action detail) or the critic latent. Which one is recorded in the policy checkpoint, so the evaluator can never feed a policy the features it was not trained on. """ d_in = 4096 + 8 pk = torch.load(policy_path, map_location=device, weights_only=False)
# HARNESS CONTROL: a lane checkpoint (key "model") is wrapped so it runs # through THIS evaluator unchanged. If it reproduces the score its own # evaluator gives, this harness is proven equivalent and any 0% belongs to # our training rather than to deployment. if "model" in pk: import importlib.util as _il _sp = _il.spec_from_file_location("lh", WT + "/scripts/rlinf_jvq/" "09032026_latent_head_bc.py") _lh = _il.module_from_spec(_sp); sys.modules["lh"] = _lh _sp.loader.exec_module(_lh) c = pk["config"] head = _lh.Head(4096, 8, len(_lh.FS15), c["hidden"], c["depth"], c["chunk"]).to(device) head.load_state_dict(pk["model"]); head.eval() if not lane_norm: raise SystemExit("a lane checkpoint needs --lane-norm <norm npz>") nz = np.load(lane_norm) zm = torch.tensor(nz["zm"], dtype=torch.float32, device=device) zs = torch.tensor(nz["zs"], dtype=torch.float32, device=device) pm = torch.tensor(nz["pm"], dtype=torch.float32, device=device) ps = torch.tensor(nz["ps"], dtype=torch.float32, device=device)
class _LaneWrap(torch.nn.Module): """Exposes the lane Head through our (pfeat, sample) interface.""" d_act = c["chunk"] * 7
def __init__(self): super().__init__(); self.h = head; self.chunk = c["chunk"]
@torch.no_grad() def sample(self, x, task): z = (x[:, :4096] - zm) / zs pr = (x[:, 4096:] - pm) / ps adv = torch.full((x.shape[0],), 2, dtype=torch.long, device=x.device) a = torch.randn(x.shape[0], self.chunk, 7, device=x.device) for st in range(10): kk = torch.full((x.shape[0],), 1 - st / 10, device=x.device) a = a + self.h(z, pr, task, adv, a, kk).view_as(a) / 10 return a.flatten(1)
mu0 = torch.zeros(d_in, device=device); sd1 = torch.ones(d_in, device=device) return ((lambda x: x), _LaneWrap(), c["chunk"], {"d_z": 0}, "lane", d_in, (mu0, sd1)) # the exact transform the policy trained under -- never re-derived here # the stats file must match the pool the policy trained under _np = pk["config"].get("norm_pool", "all") st = Path(_resolve_cache(pk["config"].get("cache", ""))) / ( "feat_stats.npz" if _np == "all" else f"feat_stats_{_np}.npz") if not st.exists(): raise FileNotFoundError( f"feature stats missing: {st}. The policy was trained on normalised " f"features; evaluating it on raw ones is off-distribution.") _s = np.load(st) if int(_s["dim"]) != d_in: raise ValueError(f"feat_stats dim {int(_s['dim'])} != evaluator dim {d_in}") nmu = torch.tensor(_s["mu"], dtype=torch.float32, device=device) nsd = torch.tensor(_s["sd"], dtype=torch.float32, device=device) # A raw-feature policy trains on CENTERED input, which the data layer # produces by z-scoring and then rescaling the visual block back by # sd / mean(sd). Rebuilt here from the same stats file so the evaluator and # is_ope.policy_features cannot drift apart. Proprio (last 8 dims) keeps its # per-dim z-score. _sd = np.asarray(_s["sd"], np.float32) _sc = np.ones(d_in, np.float32) _sc[:4096] = _sd[:4096] / max(float(_sd[:4096].mean()), 1e-6) nsc = torch.tensor(_sc, dtype=torch.float32, device=device) if pk["config"].get("policy_features", "latent") == "raw": # a raw-feature policy needs no encoder at all, so a BC arm evaluates # without ever loading a critic cls = (ConcatFlowPolicy if pk["config"].get("policy_family", "flow") == "concat" else FlowPolicy) _kw = {} if pk["config"].get("policy_family", "flow") == "concat": _kw = dict(width=int(pk["config"].get("pol_width", 1024) or 1024), depth=int(pk["config"].get("pol_depth", 4) or 4)) pol = cls(d_in, pk["config"]["chunk"] * 7, n_task, **_kw).to(device) pol.load_state_dict(pk["pol"]); pol.eval() return ((lambda x: x * nsc), pol, pk["config"]["chunk"], {"d_z": 0}, "raw", d_in, (nmu, nsd)) if not critic_path: raise SystemExit("this policy reads latent features; pass --critic") ck = torch.load(critic_path, map_location=device, weights_only=False) c = ck["config"] n_pr = int(ck.get("n_pr", 0) or 0) base = Encoder(d_in, c["d_z"], c["enc_width"]).to(device) base.load_state_dict(ck["enc"]) pcfg = pk["config"] chunk = pcfg["chunk"] mode = pcfg.get("policy_features", "latent")
mu = sd = torch.zeros(0, device=device) if n_pr: # proprio normalisation must come from the cache the CRITIC was fit on, # not a hard-coded path: different caches have different proprio stats. pcache = Path(pcfg.get("cache", "")) / "proprio.f32.npy" if not pcache.exists(): raise FileNotFoundError(f"proprio stats cache missing: {pcache}") pr = np.asarray(np.load(pcache, mmap_mode="r")[::37], np.float32) mu = torch.tensor(pr.mean(0), device=device) sd = torch.tensor(pr.std(0) + 1e-6, device=device) enc = _LatWithProprio(base, n_pr, mu, sd).to(device).eval()
if mode == "raw": pfeat, d_lat = (lambda x: x), d_in else: pfeat, d_lat = enc, c["d_z"] + n_pr
cls = (ConcatFlowPolicy if pcfg.get("policy_family", "flow") == "concat" else FlowPolicy) pol = cls(d_lat, chunk * 7, n_task).to(device) pol.load_state_dict(pk["pol"]) pol.eval() return pfeat, pol, chunk, c, mode, d_lat, (nmu, nsd)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--critic", default="", help="only needed when the policy reads latent features") ap.add_argument("--policy", required=True) ap.add_argument("--tasks", default="0,1,2,3,4,5,6,7,8,9") ap.add_argument("--n-init", type=int, default=10) ap.add_argument("--execute", type=int, default=10) ap.add_argument("--max-steps", type=int, default=520) ap.add_argument("--suite", default="libero_10") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--policy-seed", type=int, default=0) ap.add_argument("--fresh", type=int, default=0) ap.add_argument("--qf-gate", type=float, default=0.0, help="only OVERRIDE the policy's own action when the best " "candidate beats it by more than this margin in Q units. " "0 = always take the arg-max (plain ranking, 0.550); a " "large value never fires and reduces exactly to the " "policy (0.630). The ranker is weak on average -- " "expert-vs-perturbation wins only 0.515 at small " "perturbations -- so acting on it only where it is " "confident is the way to use it without paying for its " "average quality.") ap.add_argument("--policy-sde", type=float, default=0.0, help="noise injected DURING integration when --q-filter is " "on. Unlike --policy-temp this follows the learned " "drift, so candidates stay near the manifold. Measured: " "test-time ranking (0.550) beats distilling the selected " "actions (0.410), because distillation replaces the " "policy while ranking only picks among its own samples.") ap.add_argument("--policy-sde-anneal", type=int, default=0, help="1 = scale --policy-sde noise by the remaining noise " "fraction so the last integration steps are clean.") ap.add_argument("--policy-temp", type=float, default=1.0, help="scales the proposal's initial noise when --q-filter is " "on. A trained flow clone samples at action std 0.029 " "against the data's 0.421, so 8 candidates are near " "copies and there is nothing to rank. Diversity only " "pays once the ranker has the right SIGN, which the " "supervised student Q does and our counterfactual Q did " "not.") ap.add_argument("--qf-ckpt", default="", help="main_rsm.pt from rsm_main.py. Ranks --q-filter candidate " "chunks by the DISTILLED student qf(z,a), which main " "supervises on real (s,a,s') transitions, instead of by " "conditioning the occupancy on a counterfactual action.") ap.add_argument("--save-frames", default="", help="directory to write per-episode agentview JPEG strips. Lets a " "closed-loop FAILURE be inspected: the scalar SR says an arm " "lost an episode, not what the arm did wrong.") ap.add_argument("--frame-stride", type=int, default=12) ap.add_argument("--init-jitter", type=float, default=0.0, help="metres of uniform xy perturbation applied to every object " "free joint after reset. BOTH stock init states and env.reset() " "are narrow (std 0.024 / 0.014), and both sit inside " "BC-on-demos's training support, so neither tests whether a " "demo-trained policy degrades off-support. This widens the " "initial-state distribution explicitly. Applies to A and B " "alike; 0 = off.") ap.add_argument("--select", default="argmaxq", choices=["argmaxq", "random", "medoid", "qnear", "quantile", "randgate"], help="how to pick among the --q-filter candidates. argmaxq uses " "the critic. random picks uniformly (must reproduce plain BC, " "and is the sanity check that the harness adds nothing). " "medoid picks the candidate nearest the other N-1, a " "CRITIC-FREE variance reducer -- if best-of-N helps for any " "reason other than value, medoid captures it, and any gain " "over medoid is what the critic actually contributes.") ap.add_argument("--demo-cand", type=int, default=0, help="append this many nearest-DEMO action chunks to the " "candidate set, retrieved by L2 in the same normalised " "feature space the policy reads. The ranker is otherwise " "confined to the proposal's own support: 8 samples from a " "flow with action std 0.029 against the data's 0.421 are " "near-copies, so even a perfect ranker has nothing to " "choose. Demo chunks are off-proposal but ON-manifold, " "unlike --policy-sde noise which cost 0.22.") ap.add_argument("--q-filter", type=int, default=0, help="sample this many action chunks from the policy and " "execute the one the RSM critic scores highest. 0 = off. " "Uses the occupancy model at DEPLOYMENT, which needs only " "a critic that RANKS actions, not one that is calibrated.") ap.add_argument("--qf-beta", type=float, default=0.97, help="hop length for the filter, inside the critic's training " "band [0.85, 0.97]; 0.97 looks ~33 frames ahead") ap.add_argument("--qf-depth", type=int, default=1, help="depth 1 needs no continuation policy: the recursion " "breaks before it would have to re-draw an action in a " "latent the flow only imagined") ap.add_argument("--qf-particles", type=int, default=16) ap.add_argument("--qf-mode", default="restart", choices=["restart", "fold"], help="restart: geometric mixture of beta-hops (restart prob " "(gamma-beta)/(gamma(1-beta))) = the gamma-occupancy, reward read " "once at the stopping state. fold: the OCBench product fold " "Q_k = c_k + (1-c_k) gamma^(1/(1-beta)) Q_{k+1} over a FIXED " "number of hops (--qf-depth).") ap.add_argument("--policy2", default="", help="second proposer checkpoint; --q-filter2 of its samples are appended " "to the candidate set (test-time stitching of two policies)") ap.add_argument("--q-filter2", type=int, default=0) ap.add_argument("--select-q", type=float, default=0.9, help="select=quantile: execute the candidate at this quantile of Q " "(rank round(q*(N-1)) in ascending order) instead of the arg-max.") ap.add_argument("--qf-crn", type=int, default=0, help="1 = common random numbers across candidates in the Q " "recursion (same flow noise / restart coins / hop-policy noise " "for particle i of every candidate), so the arg-max compares " "paired estimates. Independent draws rank near-copies by noise.") ap.add_argument("--qnear-k", type=int, default=4, help="select=qnear: arg-max Q among the K candidates nearest the medoid") ap.add_argument("--hop-policy", default="", help="bc_arm checkpoint trained with --policy-features latent over the " "SAME critic encoder. Required for --qf-depth >= 2: the beta-hop " "composition continues the trajectory from the sampled latent z' " "with pi(a|z'), and the raw-feature proposer cannot read z'.") ap.add_argument("--qf-pessimism", type=float, default=2.0) ap.add_argument("--partial-only", type=int, default=0, help="write only <out>.partial.t<k> files; the final JSON is left to an assembly run") ap.add_argument("--allow-cam-mismatch", type=int, default=0, help="override the render-resolution guard. Never for a reported number.") ap.add_argument("--init-source", default="libero", choices=["libero", "demo", "rollout"], help="where episode k's initial state comes from. libero = the stock " "init_states (protocol A) or env.reset() (protocol B); demo = the " "EXACT first sim state of demo k from the LIBERO hdf5; rollout = the " "first sim_state of the k-th cached rollout of this task.") ap.add_argument("--save-video-frames", default="", help="dir: write full-res agentview frames (uint8, every --video-stride " "steps) per episode, for mp4 export") ap.add_argument("--video-stride", type=int, default=2) ap.add_argument("--cam-res", type=int, default=256, help="render resolution of both cameras. 128 is the LIBERO demo-hdf5 " "convention and what the demo cache was encoded from; 256 is what " "RLinf's libero_10 env (the lane's evaluator AND the rollout " "collector) uses, i.e. the space the 43k rollout latents live in. " "A policy must be evaluated at the resolution its latents were " "encoded at, or it is off-support from step 1 (i251).") ap.add_argument("--probe-ood", type=int, default=0, help="print the first decision's action scale per episode. Default " "off so queued evals are unaffected.") ap.add_argument("--lane-norm", default="", help="norm npz for a lane checkpoint run as a harness control") ap.add_argument("--out", required=True) args = ap.parse_args() _guard_render_resolution(args) _guard_encoder(args)
dev = "cuda" if torch.cuda.is_available() else "cpu" # an assembly run (all tasks in partials) needs no GPU tower = ogpo.build_paligemma(dev) from libero.libero import benchmark, get_libero_path from libero.libero.envs import OffScreenRenderEnv import time as _time _T0 = _time.time() def _lap(msg): print(f"[eval][t+{_time.time()-_T0:6.0f}s] {msg}", flush=True) bench = benchmark.get_benchmark_dict()[args.suite]() _lap("imports + benchmark ready")
canon = [n.strip() for n in Path( os.environ.get("RSM_TASKS_FILE", "/data/pulkitag/hamer_diffusion_policy_project/projects/" "continual_learning_for_manipulation/logs/09052026_lib10_tasks.txt") ).read_text().replace("\n", ",").split(",") if n.strip()] by_name = {t: i for i, t in enumerate(canon)}
pfeat, pol, chunk, ccfg, pmode, d_lat, (nmu, nsd) = load_policy( args.critic, args.policy, len(canon), dev, lane_norm=args.lane_norm) _lap("policy (+encoder) loaded") pol2 = pfeat2 = None if args.policy2: # Second proposer: its candidates are appended to the first's, so the selector # can stitch between a narrow strong policy (demos) and a broad one (successes) # per decision. Both must share the feature normalisation (checked). pfeat2, pol2, chunk2, _c2, _m2, _d2, (nmu2, nsd2) = load_policy( args.critic, args.policy2, len(canon), dev, lane_norm=args.lane_norm) if chunk2 != chunk or not torch.allclose(nmu2, nmu) or not torch.allclose(nsd2, nsd): raise SystemExit("--policy2 must share chunk length and feature normalisation with --policy") print(f"[eval] second proposer: {args.policy2} x {args.q_filter2} candidates", flush=True)
qf = None gate_stats = {"fire": 0, "hold": 0} if args.q_filter and args.qf_ckpt and torch.load(args.qf_ckpt, map_location="cpu", weights_only=False).get("iql_q"): # IQL baseline, ranked with EXACTLY the RSM arm's best-of-N machinery: same # proposal policy, same N, same arg-max; only the source of Q differs. The IQL # Q reads the frozen encoder of the RSM critic it was trained against. from iql import QNet as _QNet from is_ope import load_critic as _lc from data import LiberoRSMData ck = torch.load(args.qf_ckpt, map_location=dev, weights_only=False) _pc = torch.load(args.policy, map_location="cpu", weights_only=False)["config"] _dq = LiberoRSMData(_resolve_cache(_pc["cache"]), chunk=chunk, seed=0, in_ram=False, reward_mode="dense", norm_pool=_pc.get("norm_pool", "all")) _enc, _r, _f, _rms, _cfg = _lc(_resolve_cache(ck["critic"]), _dq.feat_dim, _dq.n_task, dev, data=_dq) _enc.eval() _qc = ck.get("config") or {} qnet = _QNet(ck["d_z"], ck["d_act"], ck["n_task"], width=int(_qc.get("width", 512) or 512), depth=int(_qc.get("depth", 3) or 3)).to(dev) qnet.load_state_dict(ck["q"]); qnet.eval()
def qf(x_norm, tt, cand): z = _enc(x_norm).expand(cand.shape[0], -1) q = qnet(z, cand, tt.expand(cand.shape[0])) if args.select == "quantile": # Rank the candidates by Q and execute the one at quantile --select-q # (0.9 of 8 -> the 2nd best, of 32 -> the 4th best). The arg-max is the # candidate most exposed to off-support optimism; a high-but-not-top # quantile keeps a strongly-scored action while discarding the extreme. _order = torch.argsort(q) # ascending _r = int(round(args.select_q * (cand.shape[0] - 1))) gate_stats["fire"] += 1 return int(_order[min(max(_r, 0), cand.shape[0] - 1)]) best = int(q.argmax()) if args.qf_gate > 0 and float(q[best] - q[0]) < args.qf_gate: gate_stats["hold"] += 1 return 0 gate_stats["fire"] += 1 return best print(f"[eval] IQL Q reader ON: {args.q_filter} candidates (tau={ck['config'].get('tau')})", flush=True) elif args.q_filter and args.qf_ckpt: # main's reader: a student Q supervised on logged transitions. from model import Encoder as _Enc from rsm_main import QStudent ck = torch.load(args.qf_ckpt, map_location=dev, weights_only=False) c = ck["config"] qenc = _Enc(4096 + 8, c["d_z"], c["enc_width"]).to(dev) qenc.load_state_dict(ck["enc"]); qenc.eval() qnet = QStudent(c["d_z"], ck["d_act"], len(canon)).to(dev) qnet.load_state_dict(ck["qf"]); qnet.eval()
def qf(x_norm, tt, cand): z = qenc(x_norm).expand(cand.shape[0], -1) q = qnet(z, cand, tt.expand(cand.shape[0])) best = int(q.argmax()) # candidate 0 is an ordinary draw from the policy: the default action if args.qf_gate > 0 and float(q[best] - q[0]) < args.qf_gate: gate_stats["hold"] += 1 return 0 gate_stats["fire"] += 1 return best print(f"[eval] qf reader ON: {args.q_filter} candidates, student Q " f"(arrival AUC {ck.get('arrival_auc', float('nan')):.4f})", flush=True) elif args.q_filter and args.select not in ("argmaxq", "qnear", "quantile"): # randgate/medoid/random are critic-free qf = None # critic-free selector; no critic needed print(f"[eval] CRITIC-FREE selector '{args.select}' over " f"{args.q_filter} candidates", flush=True) elif args.q_filter: if not args.critic: raise SystemExit("--q-filter needs --critic or --qf-ckpt") from data import LiberoRSMData from is_ope import load_critic, q_recursive pcfg_cache = torch.load(args.policy, map_location="cpu", weights_only=False)["config"] _d = LiberoRSMData(_resolve_cache(pcfg_cache["cache"]), chunk=chunk, seed=0, in_ram=False, reward_mode="dense", norm_pool=pcfg_cache.get("norm_pool", "all")) q_enc, q_rew, q_flow, q_rms, q_cfg = load_critic( args.critic, _d.feat_dim, _d.n_task, dev, data=_d)
hop_pol = None if args.qf_depth >= 2: if not args.hop_policy: raise SystemExit("--qf-depth >= 2 needs --hop-policy (latent-feature BC over the critic encoder)") from is_ope import make_policy as _mk _hk = torch.load(args.hop_policy, map_location=dev, weights_only=False) _hc = _hk["config"] if _hc.get("policy_features") != "latent": raise SystemExit(f"--hop-policy must be a --policy-features latent checkpoint (got {_hc.get('policy_features')})") class _HA: pass _ha = _HA(); [setattr(_ha, k, v) for k, v in _hc.items()] hop_pol = _mk(_ha, _d, dev, d_z=q_cfg["d_z"]) hop_pol.load_state_dict(_hk["pol"]); hop_pol.eval() print(f"[eval] beta-hop policy loaded: {args.hop_policy} (depth {args.qf_depth}, " f"restart p={(0.99 - args.qf_beta) / (0.99 * (1 - args.qf_beta)):.3f})", flush=True)
from is_ope import q_fold if args.qf_mode == "fold": print(f"[eval] Q = OCBench product fold, depth {args.qf_depth}, " f"gamma^h = {0.99 ** (1 / (1 - args.qf_beta)):.3f} per hop, crn={args.qf_crn}", flush=True) def qf(x_norm, tt, cand): """cand: [N, chunk*7] -> index of the highest-scoring chunk.""" z = q_enc(x_norm).expand(cand.shape[0], -1) if args.qf_mode == "fold": q, _ = q_fold(z, cand, tt.expand(cand.shape[0]), rew=q_rew, flow=q_flow, rms=q_rms, pol=hop_pol, beta=args.qf_beta, gamma=0.99, depth=args.qf_depth, n_particles=args.qf_particles, crn=bool(args.qf_crn)) else: q, _ = q_recursive(z, cand, tt.expand(cand.shape[0]), rew=q_rew, flow=q_flow, rms=q_rms, pol=hop_pol, wend=None, beta=args.qf_beta, gamma=0.99, depth=args.qf_depth, n_particles=args.qf_particles, use_is=False, pessimism=args.qf_pessimism, crn=bool(args.qf_crn)) if args.select == "qnear": # Support-constrained arg-max: the critic orders only the K candidates # nearest the medoid. Measured failure of plain arg-max: off-support # candidates draw diffuse futures whose read-out drifts to the base rate # and outranks confident low scores on real actions; the medoid never # selects those outliers, and beat plain arg-max on B by 0.05-0.08. _dd = torch.cdist(cand, cand).sum(1) _near = torch.topk(-_dd, k=min(args.qnear_k, cand.shape[0])).indices best = int(_near[q[_near].argmax()]) gate_stats["fire"] += 1 return best if args.select == "quantile": # Rank the candidates by Q and execute the one at quantile --select-q # (0.9 of 8 -> the 2nd best, of 32 -> the 4th best). The arg-max is the # candidate most exposed to off-support optimism; a high-but-not-top # quantile keeps a strongly-scored action while discarding the extreme. _order = torch.argsort(q) # ascending _r = int(round(args.select_q * (cand.shape[0] - 1))) gate_stats["fire"] += 1 return int(_order[min(max(_r, 0), cand.shape[0] - 1)]) best = int(q.argmax()) if args.qf_gate > 0 and float(q[best] - q[0]) < args.qf_gate: gate_stats["hold"] += 1 return 0 gate_stats["fire"] += 1 return best print(f"[eval] Q-filter ON: {args.q_filter} candidates, beta={args.qf_beta}, " f"depth={args.qf_depth}, pessimism={args.qf_pessimism}, " f"gate={args.qf_gate}", flush=True) print(f"[eval] chunk={chunk} policy_features={pmode} d_policy={d_lat} " f"suite={args.suite}", flush=True) _lap("critic / selector ready")
demo_bank = None if args.demo_cand > 0: import numpy as _np pcfg_c = torch.load(args.policy, map_location="cpu", weights_only=False)["config"] _ca = pcfg_c["cache"] _m = _np.load(f"{_ca}/meta.npz", allow_pickle=True) _isd = _m["ep_demo"].astype(bool) if not _isd.any(): raise SystemExit("--demo-cand: cache has no demo episodes") _zs = _np.load(f"{_ca}/z.f16.npy", mmap_mode="r") _pr = _np.load(f"{_ca}/proprio.f32.npy", mmap_mode="r") _ac = _np.load(f"{_ca}/act.f32.npy", mmap_mode="r") _idx = [] for _e in _np.where(_isd)[0]: _lo, _hi = int(_m["ep_from"][_e]), int(_m["ep_to"][_e]) # only frames with a full chunk ahead inside the same episode if _hi - _lo > chunk: _idx.append(_np.arange(_lo, _hi - chunk)) _idx = _np.concatenate(_idx) _f = _np.concatenate([_np.asarray(_zs[_idx], _np.float32), _np.asarray(_pr[_idx], _np.float32)], 1) _f = torch.tensor(_f, device=dev) _f = ((_f - nmu) / nsd).half() # identical transform to x _off = _np.arange(chunk)[None, :] + _idx[:, None] _A = torch.tensor(_np.asarray(_ac[_off], _np.float32).reshape(len(_idx), -1), device=dev) demo_bank = (_f, _A) print(f"[eval] demo-cand ON: {args.demo_cand} nearest of " f"{len(_idx)} demo frames appended to each candidate set", flush=True)
demo_pick = {"demo": 0, "policy": 0} mix_pick = {"p1": 0, "p2": 0} results, episodes = {}, {} # Resume from a preempted run: tasks already finished are in <out>.partial. On IBM's # preemptable queue an hour-long eval is interrupted every ~30 min; without this it # never completes. Episodes within a task are re-run (seeds are per-episode, so the # completed tasks are unaffected by where the restart happens). import glob as _glob for _pp in sorted(_glob.glob(args.out + ".partial*")): try: _pj = json.loads(Path(_pp).read_text()) results.update(_pj.get("results", {})); episodes.update(_pj.get("episodes", {})) except Exception as _e: print(f"[eval] partial file {_pp} unreadable ({_e}); ignored", flush=True) if results: print(f"[eval] RESUMED: {len(results)} tasks already done from partial files", flush=True) for tid in [int(x) for x in args.tasks.split(",")]: task = bench.get_task(tid) tname = task.name if tname in results: print(f"[eval] t{tid} {tname[:40]}: done in a previous run (SR {results[tname]:.2f}), skipping", flush=True) continue if tname not in by_name: raise ValueError(f"task {tid} ({tname}) not in the canonical libero_10 list") thead = by_name[tname] ids = ogpo.tokenize_prompt(task.language) inits = bench.get_task_init_states(tid) if args.init_source == "demo": import h5py as _h5 with _h5.File(f"/data/pulkitag/users/rli14/libero_datasets/libero_10/{tname}_demo.hdf5", "r") as _H: _ks = sorted(_H["data"].keys(), key=lambda q: int(q.split("_")[1])) inits = [np.asarray(_H["data"][q]["states"][0]) for q in _ks] print(f"[eval] t{tid}: {len(inits)} EXACT demo initial states from hdf5", flush=True) elif args.init_source == "rollout": import pyarrow.parquet as _pq, re as _re _m = np.load("/data/pulkitag/users/rli14/rsm_libero_cache/full_demo_cam256/meta.npz", allow_pickle=True) _PAT = _re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$") inits = [] for _e in np.where((_m["ep_task"] == tid) & ~_m["ep_demo"].astype(bool))[0]: _g = _PAT.search(str(_m["ep_src"][_e])); _t, _b, _i, _x = _g.groups() _pp = (f"/data/pulkitag/users/rli14/pi05_lib10_sde_v1/task{int(_t)}_block{int(_b)}" f"/rank_0/id_{int(_i)}/data/chunk-000/episode_{int(_x):06d}.parquet") if not Path(_pp).exists(): continue inits.append(np.asarray(_pq.read_table(_pp, columns=["sim_state"])["sim_state"][0].as_py())) if len(inits) >= args.n_init: break print(f"[eval] t{tid}: {len(inits)} rollout initial sim_states from parquet", flush=True) _lap(f"t{tid}: creating env") env = OffScreenRenderEnv( bddl_file_name=str(Path(get_libero_path("bddl_files")) / task.problem_folder / task.bddl_file), camera_heights=args.cam_res, camera_widths=args.cam_res) _lap(f"t{tid}: env ready") _objn, _objb, _target = [], [], [] if args.save_frames: try: _objn = list(env.env.obj_body_id.keys()) _objb = [env.env.obj_body_id[n] for n in _objn] _target = list(env.env.obj_of_interest) print(f"[eval] t{tid} objects={_objn} target={_target}", flush=True) except Exception as _e: print(f"[eval] object handles unavailable: {_e}", flush=True) succ, episodes[tname] = [], [] # Per-episode progress: the EGL driver on IBM aborts the process (SIGABRT, no # traceback) at random points DURING a task, not only at teardown, so a 50-episode # task job that dies at episode 40 must not redo 40 episodes. Every finished # episode is appended to <out>.progress.t<tid>; a restarted job reloads it and # skips those episode indices (inits are seeded per (seed, tid, k), so the # remaining episodes are the same ones the dead job would have run). _prog = Path(args.out + f".progress.t{tid}") _done_k = set() try: if _prog.exists(): for _e in json.loads(_prog.read_text()): if int(_e["episode"]) < args.n_init and int(_e["episode"]) not in _done_k: episodes[tname].append(_e); succ.append(bool(_e["success"])) _done_k.add(int(_e["episode"])) if _done_k: print(f"[eval] t{tid}: resumed {len(_done_k)} episodes from {_prog.name}", flush=True) except Exception as _e: print(f"[eval] t{tid}: progress file unreadable ({_e}); starting over", flush=True) episodes[tname], succ, _done_k = [], [], set() for k in range(args.n_init): if k in _done_k: continue pseed = 7_919_003 + args.policy_seed * 500_009 + tid * 1_013 + k torch.manual_seed(pseed); torch.cuda.manual_seed_all(pseed) np.random.seed(args.seed * 100003 + tid * 1009 + k) if hasattr(env, "seed"): env.seed(args.seed * 100003 + tid * 1009 + k) env.reset() if args.init_source != "libero": env.env.sim.set_state_from_flattened(np.asarray(inits[k % len(inits)], np.float64)) env.env.sim.forward() elif not args.fresh: env.set_init_state(inits[k % len(inits)]) if args.init_jitter > 0: # Perturb object free joints only. mjtJoint FREE == 0; its qpos block is # [x, y, z, qw, qx, qy, qz], so writing indices 0-1 moves the object in # the table plane without touching height or orientation (which would # make the state unphysical). The robot is welded in LIBERO, so free # joints are exactly the manipulable objects. _sim = env.env.sim _st = np.asarray(_sim.get_state().flatten()).copy() _nq = _sim.model.nq _rs = np.random.RandomState( 987_631 + args.seed * 7919 + tid * 131 + k) _moved = 0 for _j in range(_sim.model.njnt): if int(_sim.model.jnt_type[_j]) != 0: continue _a = int(_sim.model.jnt_qposadr[_j]) if _a + 1 >= _nq: continue _st[1 + _a] += _rs.uniform(-args.init_jitter, args.init_jitter) _st[1 + _a + 1] += _rs.uniform(-args.init_jitter, args.init_jitter) _moved += 1 _sim.set_state_from_flattened(_st) _sim.forward() for _ in range(5): # let contacts settle onto the table _sim.step() if tid == 0 and k == 0: print(f"[eval] init-jitter {args.init_jitter*100:.1f} cm on " f"{_moved} object free joints", flush=True) done, steps = False, 0 _frames, _geo, _vid = [], [], [] obs, _, _, _ = env.step(np.zeros(7)) init_hash = hashlib.sha256( np.asarray(env.env.sim.get_state().flatten()).tobytes()).hexdigest() while steps < args.max_steps and not done: cams = [] for key in ("agentview_image", "robot0_eye_in_hand_image"): img = obs[key][::-1, ::-1] cams.append(to224(img)[None]) if args.save_video_frames and steps % args.video_stride == 0: _vid.append(np.asarray(obs["agentview_image"][::-1, ::-1], np.uint8).copy()) if args.save_frames and steps % args.frame_stride == 0: _frames.append(np.asarray(obs["agentview_image"][::-1, ::-1]).copy()) # geometry for offline failure typing: where the hand is, whether it # is closed, and where every object is. obj_of_interest names the # BDDL goal's target, so "went to the wrong object" is measurable # without touching a network. _ee = np.asarray(obs["robot0_eef_pos"], np.float32) _gq = np.asarray(obs["robot0_gripper_qpos"], np.float32) _op = np.stack([np.asarray(env.env.sim.data.body_xpos[_b], np.float32) for _b in _objb]) if _objb else np.zeros((0, 3), np.float32) _geo.append(np.concatenate([_ee, _gq[:2], _op.reshape(-1)])) z = np.concatenate( [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0] prop = np.concatenate([ obs["robot0_eef_pos"], _eef_ori(obs), obs["robot0_gripper_qpos"], ]).astype(np.float32) x = torch.tensor(np.concatenate([z, prop])[None], dtype=torch.float32, device=dev) x = (x - nmu) / nsd # same transform as LiberoRSMData._feat tt = torch.tensor([thead], device=dev) if args.probe_ood and steps == 0: # Off-distribution guard. A policy cloned from one pool can be a # near-perfect predictor on its own frames (held-out action MSE # 0.0008 at t=0 for BC_rollsucc) and still emit actions 5x too # large on the evaluator's first observation, which reads as a # flat 0/500 indistinguishable from a weak policy. Printing the # first action's scale next to the reference pools' action scale # separates "bad policy" from "policy evaluated off its manifold". with torch.no_grad(): _a0 = pol.sample(pfeat(x), tt)[0].view(chunk, 7) _oodx.append((int(tid), np.asarray(x[0].cpu(), np.float32))) print(f"[ood] task {tid} init {k}: |a| std={float(_a0.std()):.3f} " f"max={float(_a0.abs().max()):.3f} " f"frac|a|>1={float((_a0.abs() > 1).float().mean()):.3f} " f"(corpus action std ~0.43) |x|={float(x.norm()):.2f}", flush=True) with torch.no_grad(): if qf is None and not args.q_filter: a = pol.sample(pfeat(x), tt)[0].view(chunk, 7).cpu().numpy() else: feats = pfeat(x).expand(args.q_filter, -1) cand = pol.sample(feats, tt.expand(args.q_filter), temp=args.policy_temp, sde=args.policy_sde, sde_anneal=bool(args.policy_sde_anneal)) if pol2 is not None and args.q_filter2 > 0: cand2 = pol2.sample(pfeat2(x).expand(args.q_filter2, -1), tt.expand(args.q_filter2)) cand = torch.cat([cand, cand2], 0) n_pol = cand.shape[0] if demo_bank is not None: _fb, _Ab = demo_bank _d = torch.cdist(x.half(), _fb).squeeze(0) _nn = torch.topk(_d, args.demo_cand, largest=False).indices cand = torch.cat([cand, _Ab[_nn].to(cand.dtype)], 0) if args.select == "random": _pick = int(torch.randint(cand.shape[0], (1,)).item()) elif args.select == "randgate": # control for the critic gate: with prob --select-q execute a # random NON-default candidate, else the default (candidate 0) _pick = int(torch.randint(1, cand.shape[0], (1,)).item()) \ if float(torch.rand(1)) < args.select_q else 0 elif args.select == "medoid": _dd = torch.cdist(cand, cand) # [N,N] _pick = int(_dd.sum(1).argmin()) else: _pick = qf(x, tt, cand) if demo_bank is not None: demo_pick["demo" if _pick >= n_pol else "policy"] += 1 if pol2 is not None: mix_pick["p2" if args.q_filter <= _pick < args.q_filter + args.q_filter2 else "p1"] += 1 a = cand[_pick].view(chunk, 7).cpu().numpy() for act in a[: args.execute]: obs, _, done, _ = env.step(act.astype(np.float64)) steps += 1 if done or steps >= args.max_steps: break succ.append(bool(done)) episodes[tname].append({"episode": k, "success": bool(done), "steps": steps, "init_sha256": init_hash}) try: Path(args.out).parent.mkdir(parents=True, exist_ok=True) _tmp = _prog.with_suffix(_prog.suffix + ".tmp") _tmp.write_text(json.dumps(episodes[tname])); _tmp.replace(_prog) except Exception as _e: print(f"[eval] progress write failed ({_e})", flush=True) if (len(episodes[tname]) % 10) == 0: _lap(f"t{tid}: {len(episodes[tname])}/{args.n_init} episodes, SR so far {np.mean(succ):.2f}") if args.save_video_frames and _vid: _vd = Path(args.save_video_frames); _vd.mkdir(parents=True, exist_ok=True) np.savez_compressed(_vd / f"t{tid}_e{k}.npz", frames=np.stack(_vid), success=bool(done), steps=steps, task=tid, ep=k, stride=args.video_stride) if args.save_frames and _frames: import io as _io, base64 as _b64 from PIL import Image as _Im _fd = Path(args.save_frames); _fd.mkdir(parents=True, exist_ok=True) _enc = [] for _fr in _frames[:40]: _im = _Im.fromarray(_fr).convert("RGB"); _im.thumbnail((144, 144)) _bb = _io.BytesIO(); _im.save(_bb, "JPEG", quality=70) _enc.append(_b64.b64encode(_bb.getvalue()).decode()) np.savez_compressed( _fd / f"t{tid}_e{k}.npz", frames=np.array(_enc, dtype=object), geo=np.asarray(_geo, np.float32), objects=np.array(_objn, dtype=object), target=np.array(_target, dtype=object), success=bool(done), steps=steps, task=tid, ep=k) episodes[tname].sort(key=lambda _e: int(_e["episode"])) results[tname] = float(np.mean(succ)) try: # partial results survive a teardown abort or a preemption. Written BEFORE # env.close(): on IBM's EGL driver close() aborts the process (rc=134). Path(args.out).parent.mkdir(parents=True, exist_ok=True) # one file per task: parallel per-task jobs never write the same file Path(args.out + f".partial.t{tid}").write_text(json.dumps( {"results": {tname: results[tname]}, "episodes": {tname: episodes[tname]}}, indent=1)) except Exception: pass if os.environ.get("RSM_NO_ENV_CLOSE"): _keep_alive = globals().setdefault("_KEEP_ENVS", []); _keep_alive.append(env) else: try: env.close() except Exception as _e: print(f"[eval] env.close() raised (ignored): {_e}", flush=True) print(f"task {tid} {tname[:40]}: SR {results[tname]:.2f} " f"({sum(succ)}/{len(succ)})", flush=True)
overall = float(np.mean(list(results.values()))) n_tot = sum(len(v) for v in episodes.values()) n_suc = sum(e["success"] for v in episodes.values() for e in v) pooled = n_suc / max(n_tot, 1) # THROUGHPUT = SR * max_steps / mean_steps. Rewards finishing FAST, not just # finishing: a policy that solves in half the horizon does twice the work per # unit time. Reported two ways because they answer different questions: # _succ : mean over SUCCESSFUL episodes -- how fast is it when it works # _all : mean over ALL episodes -- failures burn the full horizon, so this # penalises failing twice (once in SR, once in the time it wasted) all_steps = [e["steps"] for v in episodes.values() for e in v] suc_steps = [e["steps"] for v in episodes.values() for e in v if e["success"]] mean_all = float(np.mean(all_steps)) if all_steps else float("nan") mean_suc = float(np.mean(suc_steps)) if suc_steps else float("nan") thr_all = pooled * args.max_steps / mean_all if mean_all == mean_all and mean_all > 0 else float("nan") thr_suc = pooled * args.max_steps / mean_suc if mean_suc == mean_suc and mean_suc > 0 else float("nan") per_task_thr = {} for tname, eps in episodes.items(): s = [e["steps"] for e in eps if e["success"]] if s: per_task_thr[tname] = results[tname] * args.max_steps / float(np.mean(s)) out = {"overall_task_mean_SR": overall, "successes": n_suc, "episodes": n_tot, "pooled_SR": pooled, "throughput_succ": thr_suc, "throughput_all": thr_all, "mean_steps_success": mean_suc, "mean_steps_all": mean_all, "max_steps": args.max_steps, "per_task_throughput": per_task_thr, "per_task": results, "critic": args.critic, "policy": args.policy, "chunk": chunk, "policy_features": pmode, "seed": args.seed, "n_init": args.n_init, "suite": args.suite, "episodes_detail": episodes} Path(args.out).parent.mkdir(parents=True, exist_ok=True) if args.partial_only: print("[eval] --partial-only: final JSON left to the assembly run", flush=True) else: Path(args.out).write_text(json.dumps(out, indent=1)) if args.probe_ood and _oodx: _p = str(Path(args.out).with_suffix("")) + "_oodx.npz" np.savez_compressed(_p, task=np.array([t for t, _ in _oodx], np.int64), x=np.stack([v for _, v in _oodx])) print(f"[ood] wrote {len(_oodx)} online t=0 features to {_p}", flush=True) if pol2 is not None: _m1, _m2 = mix_pick["p1"], mix_pick["p2"] print(f"[eval] mixed proposer: policy2 chosen {_m2}/{_m1+_m2} ({_m2/max(_m1+_m2,1):.3f})", flush=True) _dp, _pp = demo_pick["demo"], demo_pick["policy"] if _dp + _pp: print(f"[eval] demo-cand: expert chunk chosen {_dp}/{_dp+_pp} " f"({_dp/(_dp+_pp):.3f}) of decisions", flush=True) _gf, _gh = gate_stats["fire"], gate_stats["hold"] if _gf + _gh: print(f"[eval] gate={args.qf_gate}: fired {_gf}/{_gf+_gh} " f"({_gf/(_gf+_gh):.3f}) decisions overridden", flush=True) print(f"\nOVERALL task-mean SR {overall:.4f} | pooled {n_suc}/{n_tot} = {pooled:.4f}", flush=True) print(f"THROUGHPUT succ-only {thr_suc:.4f} all-episodes {thr_all:.4f} " f"(mean steps: success {mean_suc:.0f}, all {mean_all:.0f}, max {args.max_steps})", flush=True) print(f"BAR: bcdemos_m120k = 0.584 +- 0.025 (n=500, same harness family)", flush=True) # Everything is on disk. Skip interpreter teardown: on IBM's EGL driver robosuite's # context destructor aborts the process (rc=134), which on a normal exit would turn a # finished, written evaluation into a "failed" job. import sys as _sys; _sys.stdout.flush(); _sys.stderr.flush() os._exit(0)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990#!/bin/bash#SBATCH --job-name=rsm_libero_eval#SBATCH --account=vision-pulkitag#SBATCH --qos=lab-free#SBATCH --partition=csail-shared-h200#SBATCH --gres=gpu:1#SBATCH --cpus-per-task=8#SBATCH --mem=64G#SBATCH --time=20:00:00#SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.out#SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%j.err
# Closed-loop LIBERO-10 success rate for an rsm_libero policy.# Environment copied EXACTLY from the lane's own eval launcher# (08312026_0135am_libero10_pertask_eval.sbatch) so the number is comparable to# the bcdemos_m120k = 0.584 +- 0.025 bar. A success rate from a different# harness or a different render backend is not comparable to it.set -uo pipefailB=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationS=/data/pulkitag/users/rli14/rlinf_recap_task_expansionVENV=$B/venvs/rlinf-libero-eval-venvPY=$VENV/bin/python
export REPO_PATH=$B/external/rlinfexport PYTHONPATH="$REPO_PATH:${PYTHONPATH:-}"export LIBERO_CONFIG_PATH=$S/libero_configexport ROBOT_PLATFORM=LIBEROexport LIBERO_TYPE=standardexport MUJOCO_GL=eglexport PYOPENGL_PLATFORM=egl_GPU="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)"export MUJOCO_EGL_DEVICE_ID="$_GPU" EGL_DEVICE_ID="$_GPU"export TOKENIZERS_PARALLELISM=falseexport PYTHONUNBUFFERED=1export HF_HOME=/data/pulkitag/users/rli14/hf_cacheexport HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "")export HUGGINGFACE_HUB_TOKEN=$HF_TOKENexport HF_HUB_OFFLINE=1# the lane head sizes its task embedding from FL15_TASKS; harmless for our headsexport FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')"
CRITIC=${CRITIC:-} # only needed when the policy reads latent featuresPOLICY=${POLICY:?set POLICY}OUT=${OUT:?set OUT}LANE_NORM=${LANE_NORM:-}QFILTER=${QFILTER:-0}QFCKPT=${QFCKPT:-}PTEMP=${PTEMP:-1.0}PSDE=${PSDE:-0.0}QFGATE=${QFGATE:-0.0}QFBETA=${QFBETA:-0.97}QFDEPTH=${QFDEPTH:-1}QFPES=${QFPES:-2.0}NINIT=${NINIT:-10}SEED=${SEED:-0}# protocol A ignores SEED entirely (set_init_state overwrites the reset, and# np.random is unused in the loop). Its ONLY source of variation is the policy# sampling stream, which is keyed on --policy-seed.PSEED=${PSEED:-0}# steps of each predicted chunk actually executed. Hardcoding 10 made every# chunk>10 policy waste capacity on steps that are always discarded, which is an# unfair comparison across chunk lengths.EXEC=${EXEC:-10}DEMOCAND=${DEMOCAND:-0}# 0 = replay LIBERO's fixed init_states (which the demos were collected from);# 1 = env.reset() only, so object placements are sampled from the task's# continuous placement region. Fixed inits risk measuring memorisation.FRESH=${FRESH:-0}SELECT=${SELECT:-argmaxq}JITTER=${JITTER:-0.0}SAVEFRAMES=${SAVEFRAMES:-}PROBEOOD=${PROBEOOD:-0}TASKS=${TASKS:-0,1,2,3,4,5,6,7,8,9}MAXSTEPS=${MAXSTEPS:-520}CAMRES=${CAMRES:-256}INITSRC=${INITSRC:-libero}VIDEO=${VIDEO:-}
echo "[eval] critic=$CRITIC"echo "[eval] policy=$POLICY n_init=$NINIT seed=$SEED"$PY /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/eval_closed_loop.py \ ${CRITIC:+--critic "$CRITIC"} ${LANE_NORM:+--lane-norm "$LANE_NORM"} --policy "$POLICY" \ --tasks "$TASKS" --n-init "$NINIT" --seed "$SEED" --policy-seed "$PSEED" --fresh "$FRESH" \ --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" \ ${QFCKPT:+--qf-ckpt "$QFCKPT"} --policy-temp "$PTEMP" --policy-sde "$PSDE" --qf-gate "$QFGATE" \ --suite libero_10 --max-steps "$MAXSTEPS" --execute "$EXEC" \ --out "$OUT"RC=$?echo "[eval] done rc=$RC"exit $RC1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Build playable clips: demos (hdf5) vs rollout successes vs rollout failures (parquet).
Same task, same frame budget, same size -- so the three slices are directly comparableby eye. Demos come from the stock LIBERO hdf5 (agentview_rgb); rollouts from the sourcecorpus PNGs."""import argparse, base64, io, json, os, reimport numpy as np
SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"DEMO = "/data/pulkitag/users/rli14/libero_datasets/libero_10"PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
def src_parquet(ep_src): m = PAT.search(str(ep_src)) if not m: return None t, b, i, idx = m.groups() p = (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") return p if os.path.exists(p) else None
def enc(arr, px, q): from PIL import Image im = Image.fromarray(arr).convert("RGB") im.thumbnail((px, px)) b = io.BytesIO(); im.save(b, "JPEG", quality=q) return base64.b64encode(b.getvalue()).decode()
def pick(n, k): """k evenly spaced indices spanning 0..n-1, always including the last frame.""" if n <= k: return list(range(n)) return [int(round(i * (n - 1) / (k - 1))) for i in range(k)]
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True); ap.add_argument("--out", required=True) ap.add_argument("--per", type=int, default=3, help="episodes per slice per task") ap.add_argument("--nf", type=int, default=36); ap.add_argument("--px", type=int, default=84) ap.add_argument("--quality", type=int, default=45) args = ap.parse_args()
import pyarrow.parquet as pq, h5py m = np.load(f"{args.cache}/meta.npz", allow_pickle=True) d, s, task = m["ep_demo"].astype(bool), m["ep_success"].astype(bool), m["ep_task"] tasks = [str(t) for t in m["tasks"]] rng = np.random.default_rng(0) out = {"tasks": tasks, "nf": args.nf, "clips": []}
for ti, tname in enumerate(tasks): # demos straight from the stock LIBERO hdf5 h = f"{DEMO}/{tname}_demo.hdf5" if os.path.exists(h): with h5py.File(h, "r") as f: keys = sorted(f["data"].keys(), key=lambda x: int(x.split("_")[1])) for k in keys[:args.per]: rgb = f["data"][k]["obs"]["agentview_rgb"] ids = pick(rgb.shape[0], args.nf) # robosuite stores bottom-up; flip to human-upright like the evaluator fr = [enc(np.asarray(rgb[i])[::-1], args.px, args.quality) for i in ids] out["clips"].append({"slice": "demo", "task": ti, "len": int(rgb.shape[0]), "f": fr}) else: print(f"[clip] MISSING demo hdf5 for {tname}", flush=True) # rollouts from the source parquet for name, mask in (("success", s & ~d), ("failure", ~s & ~d)): cand = np.where(mask & (task == ti))[0] rng.shuffle(cand) got = 0 for e in cand: if got >= args.per: break p = src_parquet(m["ep_src"][e]) if not p: continue try: tb = pq.read_table(p, columns=["image"]) ids = pick(tb.num_rows, args.nf) from PIL import Image fr = [] for i in ids: im = Image.open(io.BytesIO(tb["image"][i].as_py()["bytes"])) fr.append(enc(np.asarray(im.convert("RGB")), args.px, args.quality)) out["clips"].append({"slice": name, "task": ti, "len": int(tb.num_rows), "f": fr}) got += 1 except Exception as ex: print(f"[clip] t{ti} {name}: {str(ex)[:50]}", flush=True) print(f"[clip] task {ti} done ({len(out['clips'])} clips)", flush=True)
json.dump(out, open(args.out, "w")) print(f"[clip] wrote {args.out} {os.path.getsize(args.out)/1e6:.1f} MB " f"{len(out['clips'])} clips", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Sample episodes from each corpus slice and emit a compact JSON bundle for the viewer.
Demos have no frames anywhere on disk (the OGPO demo cache stores latents only, andLIBERO's datasets/ dir is not installed), so frames are rollout-only. End-effectortrajectories come from proprio and exist for all three slices, which makes them the onedirectly comparable view."""import argparse, base64, io, json, os, re, sysimport numpy as np
SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
def src_parquet(ep_src): m = PAT.search(str(ep_src)) if not m: return None t, b, i, idx = m.groups() p = (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") return p if os.path.exists(p) else None
def jpeg(png_bytes, px, q): from PIL import Image im = Image.open(io.BytesIO(png_bytes)).convert("RGB") im.thumbnail((px, px)) b = io.BytesIO(); im.save(b, "JPEG", quality=q) return base64.b64encode(b.getvalue()).decode()
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--out", required=True) ap.add_argument("--n", type=int, default=100) ap.add_argument("--px", type=int, default=110) ap.add_argument("--quality", type=int, default=55) args = ap.parse_args()
import pyarrow.parquet as pq m = np.load(f"{args.cache}/meta.npz", allow_pickle=True) d, s = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) task, lo, hi = m["ep_task"], m["ep_from"], m["ep_to"] tasks = [str(t) for t in m["tasks"]] prop = np.load(f"{args.cache}/proprio.f32.npy", mmap_mode="r") rng = np.random.default_rng(0)
slices = {"demo": np.where(d)[0], "success": np.where(s & ~d)[0], "failure": np.where(~s & ~d)[0]} out = {"tasks": tasks, "episodes": []} for name, pool in slices.items(): # stratify across tasks so no slice is dominated by one scene pick = [] per = max(1, args.n // max(len(set(task[pool].tolist())), 1)) for t in sorted(set(task[pool].tolist())): c = pool[task[pool] == t] pick += list(rng.choice(c, size=min(per, len(c)), replace=False)) pick = list(rng.permutation(pick))[:args.n] print(f"[viz] {name}: {len(pick)} episodes", flush=True) for e in pick: a, b = int(lo[e]), int(hi[e]) P = np.asarray(prop[a:b], np.float32) k = max(1, len(P) // 60) rec = {"slice": name, "task": int(task[e]), "len": int(b - a), "eef": [[round(float(v), 4) for v in p[:3]] for p in P[::k]], "grip": [round(float(p[6]), 4) for p in P[::k]]} if name != "demo": p = src_parquet(m["ep_src"][e]) if p: try: tb = pq.read_table(p, columns=["image"]) n = tb.num_rows rec["frames"] = [ jpeg(tb["image"][i].as_py()["bytes"], args.px, args.quality) for i in (0, n // 2, n - 1)] except Exception as ex: rec["err"] = str(ex)[:60] out["episodes"].append(rec) with open(args.out, "w") as f: json.dump(out, f) mb = os.path.getsize(args.out) / 1e6 nf = sum(1 for e in out["episodes"] if "frames" in e) print(f"[viz] wrote {args.out} {mb:.1f} MB " f"{len(out['episodes'])} episodes, {nf} with frames", flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#!/bin/bash# Autoresearch for "RSM beats BC-on-demos": screen settings on a VALIDATION set of initial# conditions (protocol V: fresh inits, SEED=7, 20 per task = 200 episodes), select# checkpoints on BOTH sides by arg-max over checkpoints on V, then confirm the winners on# the untouched test protocols A/B x 3 seeds at n=500. Cells are named <arm>_<prop>_s7e7_V.# usage: ibm_autoresearch.sh train | stage1 | bcsel | stage2 <beta> <depth> | stage3 <arm> <env> [prop] [policy] [hop]set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; CACHE=$IB/cache/full_r256S="ssh -o BatchMode=yes -o ConnectTimeout=20"CB=$R/qsg_f/ckpt_best.pt; PROPL=$R/BCdemo_f/policy_last.pt; HOP=$R/HOPdemo_f/policy_r1.ptV="SEED=7, QFCRN=1, QFPART=${QFPART:-256}"; VN=20sub(){ echo "$(NINIT=$VN ./ibm_cell.sh "$1" "$2" 7 1 "$3" </dev/null) $1"; }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]*>"; }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"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"case "${1:?}" intrain) # BC with periodic checkpoints (for fair arg-max selection) + two critic variants echo "$(cell BCdemo_c "$BC --pool demos --out $R/BCdemo_c" </dev/null) BCdemo_c" 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" 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";;stage1) # beta_q x depth on V, plus the value-free baselines sub plain_DL_s7e7_V $PROPL "QFILTER=0, $V" sub medoid8_DL_s7e7_V $PROPL "SELECT=medoid, QFILTER=8, QFDEPTH=1, QFBETA=0.98, QFPES=0, QFGATE=0, $V" sub random8_DL_s7e7_V $PROPL "SELECT=random, QFILTER=8, QFDEPTH=1, QFBETA=0.98, QFPES=0, QFGATE=0, $V" for b in 90 95 98; do for d in 1 2 3; do 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" done; done;;bcsel) # plain BC at every periodic checkpoint of BCdemo_c, on V 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 sub plainC${st}_DL_s7e7_V $R/BCdemo_c/policy_s${st}.pt "QFILTER=0, $V" done;;stage2) # around the best (beta, depth): N, selector, Q mode, critic ckpt, pessimism, CRN off b=${2:?}; d=${3:?}; base="CRITIC=$CB, HOPPOL=$HOP, QFDEPTH=$d, QFBETA=0.$b, QFGATE=0, $V" sub RSMb${b}d${d}n32_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=32, QFPES=0, $base" sub RSMb${b}d${d}n16_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=16, QFPES=0, $base" sub RSMb${b}d${d}q90_DL_s7e7_V $PROPL "SELECT=quantile, SELQ=0.9, QFILTER=8, QFPES=0, $base" sub RSMb${b}d${d}q90n32_DL_s7e7_V $PROPL "SELECT=quantile, SELQ=0.9, QFILTER=32, QFPES=0, $base" sub RSMb${b}d${d}near4_DL_s7e7_V $PROPL "SELECT=qnear, QNEARK=4, QFILTER=8, QFPES=0, $base" sub RSMb${b}d${d}fold_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=0, QFMODE=fold, $base" sub RSMb${b}d${d}pes1_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=1, $base" 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" 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";;critsel) # critic checkpoint selection on V: RSM 3-hop at every periodic checkpoint of <run> run=${2:?}; b=${3:-95}; d=${4:-3} 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 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" done;;stage3) # confirm: <arm> <env> on A/B x seeds 0,1e1,2e2 at n=500 (proposer = BC ckpt of record) arm=${2:?}; env=${3:?}; prop=${4:-DL}; pol=${5:-$PROPL} 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} echo "$(./ibm_cell.sh ${arm}_${prop}_s${sfx}_$P $pol $s $F "$env, SEED=$s" </dev/null) ${arm}_${prop}_s${sfx}_$P" done; done;;esac12345678910111213141516#!/bin/bash# Proposer-bias diagnostic on IBM: no env, one GPU. Reuses ibm_eval.sh's environment block.set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/pythonexport RSM_TASKS_FILE=$IB/lib10_tasks.txt RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktreeexport OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorchexport OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.modelexport LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard MUJOCO_GL=egl PYOPENGL_PLATFORM=eglexport TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1export 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/"cd $IB/code$PY proposer_bias_diag.py --cache $IB/cache/full_r256 --critic "${CRITIC:-$R/qsg_f/ckpt_best.pt}" \ --hop-policy "${HOP:-$R/HOPdemo_f/policy_r1.pt}" --pol1 $R/BCdemo_f/policy_last.pt --pol2 $R/BCsuccv_f2/policy_r1.pt \ --depth "${DEPTH:-3}" --beta "${BETA:-0.95}" --n "${N:-8}" --frames "${FRAMES:-512}" --particles "${PART:-16}" \ --out "${OUT:-$R/diag/proposer_bias_d${DEPTH:-3}.json}"123456789101112131415161718192021#!/bin/bash# Submit one eval cell on IBM as 10 single-task jobs + 1 assembly job.# ibm_cell.sh <name> <policy> <pseed> <fresh> "<extra env, comma-separated>"# Each task job gets its own GPU (a second env on a used GPU aborts on this EGL driver);# the assembly job runs once all ten are done, resumes from the per-task partials, builds# no env, and writes <name>.json. Wall-clock per cell drops ~10x.set -uo pipefailNAME=${1:?}; POLICY=${2:?}; PSEED=${3:-0}; FRESH=${4:-0}; EXTRA=${5:-}IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logsQ=${LSF_QUEUE:-normal}; G=${LSF_GROUP:-grp_runtime}MANIFEST_ONLY=${MANIFEST_ONLY:-0}COMMON="all, POLICY=$POLICY, OUT=$E/$NAME.json, NINIT=${NINIT:-50}, PSEED=$PSEED, FRESH=$FRESH, CAMRES=256${EXTRA:+, $EXTRA}"ssh -o BatchMode=yes -o ConnectTimeout=20 bluevela "export MANIFEST_ONLY=$MANIFEST_ONLYprintf '%s' \"$COMMON\" > $E/$NAME.cell # manifest: the env this cell was submitted with (retries read it)[ \"\${MANIFEST_ONLY:-0}\" = 1 ] && exit 0for t in 0 1 2 3 4 5 6 7 8 9; do 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>&1donebsub -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]*>'" </dev/null 2>&1 | grep -v Authorized | tr -d '<>'12345678910111213#!/bin/bash# CRN diagnostic on IBM: no env, one GPU. Reuses ibm_eval.sh's environment block.set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/pythonexport RSM_TASKS_FILE=$IB/lib10_tasks.txt RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktreeexport OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorchexport OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.modelexport LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard MUJOCO_GL=egl PYOPENGL_PLATFORM=eglexport TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1export 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/"cd $IB/code$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}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#!/bin/bash# Closed-loop LIBERO-10 eval on IBM. Same evaluator (eval_closed_loop.py), the pinned venv# (version-identical to MIT), and the same 256 render -- results are admissible alongside# MIT's. Env: POLICY OUT [CRITIC QFCKPT QFILTER SELECT PSEED FRESH NINIT TASKS CAMRES ...]set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_liberoexport RSM_TASKS_FILE=/proj/dmfexp/zwhong/rsm_libero/lib10_tasks.txtexport RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktreeexport OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorchexport OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.modelexport LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standardexport MUJOCO_GL=egl PYOPENGL_PLATFORM=egl_G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)"; export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G"export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1# robosuite EGL context free() aborts the process on this driver: never close envs hereexport RSM_NO_ENV_CLOSE=1export 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/"PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/pythonTASKS=${TASKS:-0,1,2,3,4,5,6,7,8,9}; TASKS=${TASKS//;/,} # LSF -env cannot carry commas: pass task lists with ";"cd $IB/code# One LSF job = one GPU = one process. A second OffScreenRenderEnv on a GPU that already# hosted one aborts on this EGL driver (even across processes), so a full n=500 cell is# submitted as 10 single-task jobs (ibm_eval_matrix.sh) plus an assembly job that runs# with every task already in <out>.partial.t* and therefore builds no env.run_eval(){ $PY eval_closed_loop.py ${CRITIC:+--critic "$CRITIC"} --policy "${POLICY:?}" \ --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}" \ --cam-res "${CAMRES:-256}" --q-filter "${QFILTER:-0}" --select "${SELECT:-argmaxq}" \ --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}" \ ${QFCKPT:+--qf-ckpt "$QFCKPT"} --policy-temp "${TEMP:-1.0}" --policy-sde "${SDE:-0.0}" --policy-sde-anneal "${SDEANN:-0}" --probe-ood "${PROBEOOD:-0}" \ --suite libero_10 --max-steps "${MAXSTEPS:-520}" --execute 10 --out "${OUT:?}" --partial-only "${PARTIALONLY:-0}"; }if [ "${ASM:-0}" = 1 ]; then # Assembly: wait until every task's partial exists (task jobs retry on EGL aborts), then # run with nothing left to do -- no env is built, the JSON is written. 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 echo "[eval] assembly: $n/${NTASKS:-10} partials present"; run_eval; echo "[eval] done rc=$?"; exit 0fiRETRY=${RETRY:-0}; PARTIALONLY=${PARTIALONLY:-0}echo "[eval] start $(date -u +%FT%TZ) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}"run_eval; RC=$?echo "[eval] done rc=$RC $(date -u +%FT%TZ)"# Some GPUs are left in a bad EGL state by earlier jobs: the first env creation aborts# (SIGABRT 134 / SIGSEGV 139) with no traceback. Resubmit the task -- a different node is# likely -- up to 6 times. Only for single-task partial jobs, and only if the partial is# still missing.if [ "${PARTIALONLY:-0}" = 1 ] && { [ "$RC" = 134 ] || [ "$RC" = 139 ]; } && [ ! -f "${OUT}.partial.t${TASKS}" ] && [ "${RETRY:-0}" -lt 6 ]; then echo "[eval] EGL abort on $(hostname); resubmitting task ${TASKS} (retry $((RETRY+1)))" bsub -G "${LSF_GROUP:-grp_runtime}" -q "${LSF_QUEUE:-normal}" -gpu num=1 -n 8 -M 64G -J "${LSB_JOBNAME}" \ -o "${LSB_OUTPUTFILE:-/dev/null}" -e "${LSB_ERRORFILE:-/dev/null}" \ -env "all, RETRY=$((RETRY+1))" $IB/code/ibm_eval.shfiexit $RC1234567#!/bin/bash# beta-hop sweep cells only. usage: ibm_eval_depth.sh <proposer_run> <tag> <hop_run> [seeds] [depths]set -uo pipefailPROPRUN=${1:?}; TAG=${2:?}; HOPRUN=${3:?}; SEEDS=${4:-0}; DEPTHS=${5:-2,3}IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logsS="ssh -o BatchMode=yes -o ConnectTimeout=20"sub(){ ./ibm_cell.sh "$1" "$2" "$3" "$4" "$5"; }12345678910111213141516171819202122232425#!/bin/bash# Extraction matrix on IBM over a given PROPOSER policy: n=500, protocols A/B, evaluator# at 256, one LSF job per cell. usage: ibm_eval_matrix.sh <proposer_run_dir_name> <tag> [seeds]# e.g. ibm_eval_matrix.sh BCdemo_f D 0,1,2 -> cells RSMsg8_D_s0_A ... (D = demos proposer)# ibm_eval_matrix.sh BCsuccv_f2 S 0 -> the successes proposer ladderset -uo pipefailPROPRUN=${1:?proposer run dir}; TAG=${2:?tag}; SEEDS=${3:-0}; HOPRUN=${4:-} # 4th arg: latent hop policy run dir -> depth 2/3 cellsIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logsS="ssh -o BatchMode=yes -o ConnectTimeout=20"sub(){ ./ibm_cell.sh "$1" "$2" "$3" "$4" "$5"; }PROP=$R/$PROPRUN/policy_r1.pt; BON="QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=0, QFGATE=0"for s in ${SEEDS//,/ }; do for P in A B; do F=0; [ $P = B ] && F=1 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" echo "$(sub medoid8_${TAG}_s${s}_$P $PROP $s $F "SELECT=medoid, $BON") medoid8_$TAG s$s $P" echo "$(sub plain_${TAG}_s${s}_$P $PROP $s $F "QFILTER=0") plain_$TAG s$s $P"done; done# beta-hop sweep (depth 2, 3) with the matching latent hop policy (4th arg)[ -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 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"done; done; donefor P in A B; do F=0; [ $P = B ] && F=1 echo "$(sub RSMind8_${TAG}_s0_$P $PROP 0 $F "CRITIC=$R/qind_f/ckpt_best.pt, SELECT=argmaxq, $BON") RSMind8_$TAG s0 $P" echo "$(sub random8_${TAG}_s0_$P $PROP 0 $F "SELECT=random, $BON") random8_$TAG s0 $P" [ -n "${IQLQ:-}" ] && echo "$(sub IQL8_${TAG}_s0_$P $PROP 0 $F "QFCKPT=$IQLQ, SELECT=argmaxq, $BON") IQL8_$TAG s0 $P"done1234567891011121314151617181920212223242526272829303132333435363738#!/bin/bash# Extraction matrix over the BC-demos LAST checkpoint proposer (tag DL). The held-out# sampled-MSE proxy picked step 102k (policy_r1.pt) which evaluates ~0.10 SR below the# final step-120k weights (policy_last.pt), so every "DL" cell uses the last checkpoint on# the BC side. 3 seeds varying BOTH the policy sampling seed and the eval-init seed# (s0, s1e1, s2e2), protocols A/B, n=500. Submission order = decision priority.set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256PROPL=$R/BCdemo_f/policy_last.pt; HOP=$R/HOPdemo_f/policy_r1.ptCB=$R/qsg_f/ckpt_best.pt; CL=$R/qsg_f/ckpt.ptBON="QFILTER=8, QFBETA=0.98, QFPES=0, QFGATE=0"D3="SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=3, $BON"sub(){ echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }# 1) the claim: RSM-3hop vs BC-last plain, seeds 1,2 (seed 0 already done)for s in 1 2; do for P in A B; do F=0; [ $P = B ] && F=1 sub RSMsg8d3_DL_s${s}e${s}_$P $PROPL $s $F "CRITIC=$CB, $D3, SEED=$s" sub plain_DL_s${s}e${s}_$P $PROPL $s $F "QFILTER=0, SEED=$s"done; done# 2) value-free selectors on the same proposer (medoid / random of 8), all 3 seedsfor 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} sub medoid8_DL_s${sfx}_$P $PROPL $s $F "SELECT=medoid, QFDEPTH=1, $BON, SEED=$s" sub random8_DL_s${sfx}_$P $PROPL $s $F "SELECT=random, QFDEPTH=1, $BON, SEED=$s"done; done# 3) hop ladder (depth 1, 2) and the critic-LAST control for depth 3for 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} sub RSMsg8_DL_s${sfx}_$P $PROPL $s $F "CRITIC=$CB, SELECT=argmaxq, QFDEPTH=1, $BON, SEED=$s" sub RSMsg8d2_DL_s${sfx}_$P $PROPL $s $F "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=2, $BON, SEED=$s"done; donefor P in A B; do F=0; [ $P = B ] && F=1 sub RSMsg8d3L_DL_s0_$P $PROPL 0 $F "CRITIC=$CL, $D3"done# 4) hop-policy LAST checkpoint (HOPdemo_f best was step 36k of 120k) for depth 3HOPL=$R/HOPdemo_f/policy_last.ptfor P in A B; do F=0; [ $P = B ] && F=1 sub RSMsg8d3H_DL_s0_$P $PROPL 0 $F "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOPL, QFDEPTH=3, $BON"done1234567891011121314151617181920212223#!/bin/bash# OCBench block-quadruple techniques (hd_bon32 arm) transplanted onto LIBERO-10:# best-of-32 candidates, all scored on shared noise (common random numbers), Q = the# product fold Q_k = c_k + (1-c_k) gamma^(1/(1-beta)) Q_{k+1} over a FIXED number of# hops, read-out c = success/progress head; proposer = a broad BC policy (their actor# is BC on ALL data with q_coef=0; here BC-on-successes (S) is the broad one, BC-demos-# last (DL) the strong one). Controls: random-of-32 (no critic) and our restart-Q at N=32.# usage: ibm_eval_ocb.sh [critic_run=qsg_f] [tag_suffix]set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256CRIT=${1:-qsg_f}; SFX=${2:-}CB=$R/$CRIT/ckpt_best.ptsub(){ echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }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 IFS=: read TAG PROP HOP <<<"$spec" for P in A B; do F=0; [ $P = B ] && F=1 for D in 1 2 3; do 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" done 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" [ -z "$SFX" ] && sub random32_${TAG}_s0_$P $PROP 0 $F "SELECT=random, QFDEPTH=1, QFILTER=32, QFBETA=0.98, QFPES=0, QFGATE=0" donedone12345678910111213141516171819202122232425#!/bin/bash# Robustness grid for the RSM-3hop claim on the demos proposer:# (a) eval-seed variation: SEED 1,2 (init randomness) x PSEED 1,2, both protocols, for# RSM-3hop / plain / medoid# (b) checkpoint selection on both sides: critic LAST (400k) vs BEST (220k, win-rate# selected); BC-demos LAST (120k) vs BEST (102k, held-out-MSE selected)set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256PROP=$R/BCdemo_f/policy_r1.pt; PROPL=$R/BCdemo_f/policy_last.pt; HOP=$R/HOPdemo_f/policy_r1.ptCB=$R/qsg_f/ckpt_best.pt; CL=$R/qsg_f/ckpt.ptD3="SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=3, QFILTER=8, QFBETA=0.98, QFPES=0, QFGATE=0"BON="QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=0, QFGATE=0"sub(){ echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }# (a) eval seedsfor es in 1 2; do for P in A B; do F=0; [ $P = B ] && F=1 sub RSMsg8d3_D_s${es}e${es}_$P $PROP $es $F "CRITIC=$CB, $D3, SEED=$es" sub plain_D_s${es}e${es}_$P $PROP $es $F "QFILTER=0, SEED=$es" sub medoid8_D_s${es}e${es}_$P $PROP $es $F "SELECT=medoid, $BON, SEED=$es"done; done# (b) checkpoint selectionfor P in A B; do F=0; [ $P = B ] && F=1 sub RSMsg8d3L_D_s0_$P $PROP 0 $F "CRITIC=$CL, $D3" # critic LAST checkpoint sub plainL_D_s0_$P $PROPL 0 $F "QFILTER=0" # BC LAST checkpoint sub RSMsg8d3_DL_s0_$P $PROPL 0 $F "CRITIC=$CB, $D3" # RSM over the BC-last proposerdone1234567891011121314151617181920#!/bin/bash# Noisy-proposal cells: the flow BC policy's 8 ODE samples are near-copies (action std# 0.03 vs data 0.42), so a ranker has nothing to choose. Inject SDE noise during# integration (SDE=0.5; SDEANN=1 anneals it to zero by the last step) and compare the RSM# 3-hop pick against a RANDOM pick of the same noisy candidates (isolates the ranking) and# against plain ODE BC (the baseline). Seed 0, protocols A/B, both proposers.set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256CB=$R/qsg_f/ckpt_best.pt; BON="QFILTER=8, QFBETA=0.98, QFPES=0, QFGATE=0"sub(){ echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }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 IFS=: read TAG PROP HOP <<<"$spec" for nz in "sde5:SDE=0.5, SDEANN=0" "sde5a:SDE=0.5, SDEANN=1" "sde25a:SDE=0.25, SDEANN=1"; do IFS=: read NZ ENV <<<"$nz" for P in A B; do F=0; [ $P = B ] && F=1 sub RSMsg8d3${NZ}_${TAG}_s0_$P $PROP 0 $F "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=3, $BON, $ENV" sub random8${NZ}_${TAG}_s0_$P $PROP 0 $F "SELECT=random, QFDEPTH=1, $BON, $ENV" done donedone1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/bin/bash# Full-corpus wave on IBM (williamd4112/gen_q#252). Phases, run from MIT:# sync-code rsync rsm_libero -> IBM code dir# pack bsub: pack full_r256 on IBM from the pinned episode list (CPU, 220G)# meta-back scp IBM meta.npz -> MIT so the CPU labellers run without MIT's pack# sync-labels rsync subgoals_full + verified_mask -> IBM# train bsub: BC arms + critics + IQL (self-resubmitting preemptable cells)# eval bsub: n=500 A/B evals at 256 via IBM's run_eval.sh (self-check gated)set -uo pipefailPH=${1:?phase}G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_liberoS="ssh -o BatchMode=yes -o ConnectTimeout=20"IB=/proj/dmfexp/zwhong/rsm_libero; ID=/proj/dmfexp/zwhong/dataCACHE=$IB/cache/full_r256; RUNS=$IB/runs/full_r256; LOGS=$RUNS/logsPYT=/proj/dmfexp/zwhong/venvs/lerobot_env/bin/pythonMIT_META=/data/pulkitag/users/rli14/rsm_libero_cache/full_r256case $PH insync-code) rsync -a --exclude __pycache__ --exclude '*.pt' -e "$S" $G/ bluevela:$IB/code/ && echo "code synced";;pack) $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 \ \"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\"";;meta-back) 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;;sync-labels) rsync -a -e "$S" /data/pulkitag/users/rli14/rsm_libero_runs/subgoals_full bluevela:$RUNS/ && \ rsync -a -e "$S" /data/pulkitag/users/rli14/rsm_libero_runs/verify_full/verified_mask.npz bluevela:$RUNS/ && echo "labels+mask synced";;train|train-nomask) SG=$RUNS/subgoals_full; MASK=$RUNS/verified_mask.npz 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" 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" cell(){ # name cmd $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]*>"; } NOMASK="BCd_f|$BC --pool demos --out $RUNS/BCd_fBCroll_f|$BC --pool rollsucc --out $RUNS/BCroll_f" MASKED="BCrollv_f|$BC --pool rollsucc --success-mask $MASK --out $RUNS/BCrollv_fBCsucc_f|$BC --pool succ --success-mask $MASK --out $RUNS/BCsucc_fqind_f|$CR --reward-mode subgoal_ind --subgoal-dir $SG --success-mask $MASK --out $RUNS/qind_fqsg_f|$CR --reward-mode subgoal --subgoal-dir $SG --success-mask $MASK --out $RUNS/qsg_f" [ "$PH" = train-nomask ] && LIST="$NOMASK" || LIST="$MASKED" # </dev/null: ssh inside cell() would otherwise swallow the rest of the list from stdin while IFS='|' read -r n c; do [ -n "$n" ] && echo "$(cell "$n" "$c" </dev/null) $n"; done <<< "$LIST";;*) echo "unknown phase $PH"; exit 1;;esac123456789101112#!/bin/bash# Pack the on-policy corpus (eval_closed_loop --collect output) into a second cache with the# SAME feature normalisation as full_r256, plus subgoal labels. CPU job.set -euo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/pythonSRC=${SRC:-$R/collect_onpol/corpus}; OUT=${OUT:-$IB/cache/onpol_r256}cd $IB/code$PY pack.py --src $SRC --out $OUT --tasks-file $IB/lib10_tasks.txt --cam-res 256 --encoder pi05_base_pytorch --workers 16cp $IB/cache/full_r256/feat_stats.npz $IB/cache/full_r256/feat_stats_demos.npz $OUT/$PY subgoals_from_npz.py --cache $OUT --out $R/subgoals_onpolecho "[pack_onpol] DONE"123456789101112131415161718#!/bin/bash# rerender_rollouts.py on IBM (GPU/EGL). Env: POOL OUT CAMRES [DEMOCACHE ...]set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_liberoexport RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktree RSM_TASKS_FILE=$IB/lib10_tasks.txtexport RSM_DEMO_H5=/proj/dmfexp/zwhong/rli14_lib10/libero_datasets/libero_10export OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorchexport OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.modelexport LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standardexport MUJOCO_GL=egl PYOPENGL_PLATFORM=egl_G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)"; export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G"export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/pythoncd $IB/code$PY rerender_rollouts.py --pool "${POOL:?}" --out "${OUT:?}" --cam-res "${CAMRES:-256}" \ --demo-cache "${DEMOCACHE:-/proj/dmfexp/zwhong/data/libero10_demo_ogpo_cache_cam256}" \ --stats /proj/dmfexp/zwhong/rsm_libero/cache/full_r256/feat_stats_demos.npzecho "[rr] done rc=$?"123456789101112131415161718192021222324252627282930#!/bin/bash# Resubmit, through the per-task fan-out, every planned cell that has no final JSON on IBM.# Cells are re-derived from the plan (proposer x selector x seed x protocol); tasks whose# partial already exists are skipped by the evaluator's resume, so nothing done is redone.set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/evalS="ssh -o BatchMode=yes -o ConnectTimeout=20"have=$($S bluevela "ls $E/*.json 2>/dev/null | xargs -n1 basename | sed 's/.json$//'" </dev/null 2>/dev/null | grep -v Authorized)IQLQ=$R/iql_f_mit/iql_q.pt; BON="QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=0, QFGATE=0"plan(){ # name policy pseed fresh extra 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 echo "$have" | grep -qx "$1" && return echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" </dev/null) $1"; }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" PROP=$R/$PR/policy_r1.pt; HOP=$R/$HOPR/policy_r1.pt for s in $SEEDS; do for P in A B; do F=0; [ $P = B ] && F=1 plan RSMsg8_${TAG}_s${s}_$P $PROP $s $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=argmaxq, $BON" plan medoid8_${TAG}_s${s}_$P $PROP $s $F "SELECT=medoid, $BON" plan plain_${TAG}_s${s}_$P $PROP $s $F "QFILTER=0" 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 done; done for P in A B; do F=0; [ $P = B ] && F=1 plan RSMind8_${TAG}_s0_$P $PROP 0 $F "CRITIC=$R/qind_f/ckpt_best.pt, SELECT=argmaxq, $BON" plan random8_${TAG}_s0_$P $PROP 0 $F "SELECT=random, $BON" plan IQL8_${TAG}_s0_$P $PROP 0 $F "QFCKPT=$IQLQ, SELECT=argmaxq, $BON" [ $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" 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" 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"; } donedone12345678910111213141516#!/bin/bash# Resubmit per-task eval jobs whose partial is missing and which are not RUN/PEND, using# the cell manifest (<cell>.cell) written at submission. Idempotent; run repeatedly.set -uo pipefailssh -o BatchMode=yes -o ConnectTimeout=20 bluevela 'IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logs; n=0active=$(bjobs -noheader -w 2>/dev/null | awk "\$3==\"RUN\"||\$3==\"PEND\" {print \$7}")for m in $E/*.cell; do cell=$(basename $m .cell); [ -f $E/$cell.json ] && continue env=$(cat $m) for t in 0 1 2 3 4 5 6 7 8 9; do [ -f $E/$cell.json.partial.t$t ] && continue echo "$active" | grep -qx "${cell}_t$t" && continue 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)) done 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>&1done; echo "resubmitted $n task jobs"'12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Assemble the RSM-vs-baselines table from IBM eval JSONs, with PAIRED tests.
Cells are named <arm>_<proposer>_s<pseed>[e<evalseed>]_<A|B>. Two cells with the sameproposer, pseed/evalseed and protocol share initial conditions (init_sha256 per episode),so arm differences are paired: McNemar exact test on discordant episodes, plus the pairedthroughput difference. Reports every arm against `plain` (BC single action) and against`medoid8` (the value-free selector) on the same cell."""import argparse, glob, json, os, re, sysfrom collections import defaultdictfrom math import comb
def mcnemar(b, c): n = b + c if n == 0: return 1.0 k = min(b, c); p = sum(comb(n, i) for i in range(0, k + 1)) / 2 ** n return min(1.0, 2 * p)
def load(d): cells = {} for f in glob.glob(f"{d}/*.json"): n = os.path.basename(f)[:-5] m = re.match(r"(.+)_(D|S|DL|R|RL|DC)_s(\d)(?:e(\d))?_(A|B|V)$", n) if not m: continue arm, prop, ps, es, P = m.groups(); es = es or "0" j = json.load(open(f)) eps = {} for t, lst in j["episodes_detail"].items(): for e in lst: eps[(t, e["episode"], e["init_sha256"])] = (bool(e["success"]), int(e["steps"])) cells[(arm, prop, ps, es, P)] = dict(sr=j["pooled_SR"], thr=j["throughput_all"], n=j["episodes"], eps=eps) return cells
def pair(a, b): keys = set(a["eps"]) & set(b["eps"]) if not keys: return None sa = [a["eps"][k][0] for k in keys]; sb = [b["eps"][k][0] for k in keys] 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) 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] return dict(n=len(keys), dsr=(sum(sa) - sum(sb)) / len(keys), b=B, c=C, p=mcnemar(B, C), dthr=(sum(ta) - sum(tb)) / len(keys))
def main(): ap = argparse.ArgumentParser(); ap.add_argument("--dir", required=True); ap.add_argument("--prop", default="D") a = ap.parse_args(); cells = load(a.dir) arms = sorted({k[0] for k in cells if k[1] == a.prop}) print(f"proposer={a.prop} cells: {sum(1 for k in cells if k[1]==a.prop)}\n") 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}") for arm in arms: for (ar, pr, ps, es, P), c in sorted(cells.items()): if ar != arm or pr != a.prop: continue row = f"{arm:<14} {ps+'/'+es:>6} {P:>2} {c['sr']:6.3f} {c['thr']:6.3f} |" for base in ("plain", "medoid8"): bc = cells.get((base, pr, ps, es, P)) if bc is None or base == arm: row += f" {'':>12} {'':>7} {'':>7} |"; continue 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} |" print(row) # pooled across seeds for the headline arms print("\npooled over available (seed, protocol) pairs, arm minus baseline:") for arm in arms: for base in ("plain", "medoid8"): if arm == base: continue B = C = n = 0; dth = 0.0 for (ar, pr, ps, es, P), c in cells.items(): if ar != arm or pr != a.prop: continue bc = cells.get((base, pr, ps, es, P)); r = pair(c, bc) if bc else None if r: B += r["b"]; C += r["c"]; n += r["n"]; dth += r["dthr"] * r["n"] 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}")
if __name__ == "__main__": main()123456789101112131415#!/bin/bash# Retrain the RSM critic with the on-policy pack mixed into training batches.# env: MIX2 (fraction from cache2, default 0.5), OUT (run dir), STEPS (default 300000)set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/pythonexport PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1export 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/"cd $IB/code$PY train_rsm.py --cache $IB/cache/full_r256 --subgoal-dir $R/subgoals_full --reward-mode subgoal \ --cache2 $IB/cache/onpol_r256 --subgoal-dir2 $R/subgoals_onpol --mix2 "${MIX2:-0.5}" \ --reward-loss bce --append-proprio 1 --d-z 256 --enc-width 1024 --flow-width 1024 --flow-depth 4 \ --beta-lo 0.93 --beta-hi 0.995 --beta-q 0.98 --w-actcon 0.5 --batch 512 --lr 3e-4 --ema 0.995 \ --steps "${STEPS:-300000}" --save-every 20000 --eval-every 10000 --in-ram 1 --seed "${SEED:-0}" \ --out "${OUT:?}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259"""IQL critic + policy extraction, as the standard offline-RL baseline for RSM.
Matched to the RSM arms on purpose: same latents, same reward labels, sameFlowPolicy class, same AWR extraction, same offline score. The ONLY thing thatdiffers is where the advantage comes from -- IQL's expectile-regressed Q - Vversus RSM's occupancy read-out. That is what makes the comparison a test of thecritic rather than of the pipeline around it.
IQL (Kostrikov et al., ICLR 2022): L_V = E[ expectile_tau( Q_target(z,a) - V(z) ) ] L_Q = E[ ( r + gamma * V(z') - Q(z,a) )^2 ] advantage = Q(z,a) - V(z)Reward is the same DENSE P(success|z) label the RSM critic reads, so neither methodgets a reward the other does not see."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, jsonfrom pathlib import Pathimport numpy as npimport torchimport torch.nn.functional as F
from model import Encoder, mlp, FlowPolicyfrom data import LiberoRSMDatafrom is_ope import make_policy, policy_nll, train_bc, policy_featuresfrom train_rsm import auc
class QNet(torch.nn.Module): def __init__(self, d_z, d_act, n_task, d_task=64, width=512, depth=3): super().__init__() self.task = torch.nn.Embedding(n_task, d_task) self.net = mlp([d_z + d_act + d_task] + [width] * depth + [1], norm=True)
def load_state_dict(self, sd, strict=True): # Self-describing checkpoints: rebuild the MLP to the saved width/depth if the # caller constructed the default size (evaluator constructs QNet(d_z, d_act, n_task) # and is edited by more than one session; the checkpoint is the source of truth). lin = sorted((int(k.split(".")[1]), sd[k]) for k in sd if k.startswith("net.") and k.endswith(".weight") and sd[k].dim() == 2) if lin: d_in = int(lin[0][1].shape[1]); sizes = [d_in] + [int(w.shape[0]) for _, w in lin] mine = [m for m in self.net if isinstance(m, torch.nn.Linear)] if [d_in] + [m.out_features for m in mine] != sizes: self.net = mlp(sizes, norm=True).to(lin[0][1].device) return super().load_state_dict(sd, strict=strict)
def forward(self, z, a, task): return self.net(torch.cat([z, a, self.task(task)], -1)).squeeze(-1)
class VNet(torch.nn.Module): def __init__(self, d_z, n_task, d_task=64, width=512, depth=3): super().__init__() self.task = torch.nn.Embedding(n_task, d_task) self.net = mlp([d_z + d_task] + [width] * depth + [1], norm=True)
def forward(self, z, task): return self.net(torch.cat([z, self.task(task)], -1)).squeeze(-1)
def expectile_loss(diff, tau): return torch.where(diff > 0, tau, 1 - tau) * diff.pow(2)
def train_iql(d, enc, args, device, steps): """Expectile V + TD Q on the frozen reward-predictive latent.""" d_act = d.chunk * d.adim q = QNet(args.d_z, d_act, d.n_task).to(device) q_t = QNet(args.d_z, d_act, d.n_task).to(device) q_t.load_state_dict(q.state_dict()) for p in q_t.parameters(): p.requires_grad_(False) v = VNet(args.d_z, d.n_task).to(device) opt = torch.optim.AdamW(list(q.parameters()) + list(v.parameters()), lr=3e-4, weight_decay=0.01) rng = np.random.default_rng(args.seed + 3) for step in range(1, steps + 1): b = d.sample_frames(args.batch, rng, "train", device) # next state: one action-chunk ahead, clamped to the episode end t_next = np.minimum(b["t_idx"] + d.chunk, d.ep_to[b["ep"]] - 1) with torch.no_grad(): z = enc(b["x"]) xn = torch.from_numpy(d._feat(t_next)).to(device) zn = enc(xn) r = torch.from_numpy(d.r[t_next]).to(device) done = torch.from_numpy( (t_next >= d.ep_to[b["ep"]] - 1).astype(np.float32)).to(device) qt = q_t(z, b["a"], b["task"]) vv = v(z, b["task"]) l_v = expectile_loss(qt - vv, args.tau).mean() with torch.no_grad(): vn = v(zn, b["task"]) target = r + args.gamma * (1 - done) * vn l_q = (q(z, b["a"], b["task"]) - target).pow(2).mean() loss = l_v + l_q opt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_(list(q.parameters()) + list(v.parameters()), 1.0) opt.step() with torch.no_grad(): for pt, po in zip(q_t.parameters(), q.parameters()): pt.mul_(0.995).add_(po.detach(), alpha=0.005) if step % 1000 == 0: with torch.no_grad(): adv = (q(z, b["a"], b["task"]) - vv) print(f"[iql] {step} l_v={float(l_v):.4f} l_q={float(l_q):.4f} " f"|adv|={float(adv.abs().mean()):.4f}", flush=True) q.eval(); v.eval() return q, v
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--norm-pool", default="all", choices=["all", "demos"], help="frames the feature statistics come from. demos is worth +0.15 closed-loop over rollout-dominated statistics.")
ap.add_argument("--adv-norm", default="std", choices=["std", "none"], help="standardise the advantage inside the AWR weight. " "Without it beta is uninterpretable and the weight " "collapses to a hard sign filter.")
ap.add_argument("--init-pool", default="succ", choices=["succ", "demos", "demos_succ", "all"], help="episodes the pi_0 clone is fit on. Both critic arms must " "use the SAME value or the comparison measures the initialisation rather than the critic.")
ap.add_argument("--lr", type=float, default=3e-4)
ap.add_argument("--feat-scale", default="zscore", choices=["zscore", "center"], help="how the POLICY sees the observation. zscore matches the " "lane BC recipe that reaches 0.584; center keeps relative " "dim importance. Ranked on held-out sampled action MSE, " "never on the CFM loss.")
ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"], help="what the POLICY reads: raw = full observation (BC-baseline " "parity), latent = critic bottleneck. Advantage always " "comes from the critic latent.")
ap.add_argument("--critic", required=True, help="RSM checkpoint -- used ONLY for its frozen encoder, so " "IQL and RSM read the same latent") ap.add_argument("--out", required=True) ap.add_argument("--chunk", type=int, default=25) ap.add_argument("--tau", type=float, default=0.7, help="IQL expectile") ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--awr-beta", type=float, default=1.0) ap.add_argument("--w-max", type=float, default=20.0) ap.add_argument("--iql-steps", type=int, default=12000) ap.add_argument("--bc-steps", type=int, default=3000) ap.add_argument("--awr-steps", type=int, default=1500) ap.add_argument("--rounds", type=int, default=2) ap.add_argument("--batch", type=int, default=256) ap.add_argument("--awr-pool", default="succ", choices=["all", "succ", "demos"], 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.") ap.add_argument("--policy-family", default="concat", choices=["concat", "flow", "gauss"]) ap.add_argument("--in-ram", type=int, default=0) ap.add_argument("--success-gamma", type=float, default=0.98, help="discount for reward-mode=soft: the label is " "success_gamma ** (frames until success)") ap.add_argument("--subgoal-dir", default="", help="per-frame satisfied-conjunct labels (reward-mode subgoal*)") ap.add_argument("--success-mask", default="", help="admissibility mask npz (keep); drops non-reproducing successes") ap.add_argument("--q-only", type=int, default=0, help="train IQL Q/V, save them as iql_q.pt for best-of-N ranking in the evaluator, and stop. " "No BC clone, no AWR: the extraction is then IDENTICAL to the RSM arm except for where Q comes from.") ap.add_argument("--reward-mode", default="dense", choices=["dense","terminal","soft","subgoal","subgoal_ind"], help="dense = P(task succeeds|z), every frame of a success is a " "positive (~50%%). terminal = last k frames only (~0.5%%), which " "leaves Q near-constant in the action.") ap.add_argument("--seed", type=int, default=0) args = ap.parse_args()
torch.manual_seed(args.seed) dev = "cuda" if torch.cuda.is_available() else "cpu" d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode=args.reward_mode, success_gamma=getattr(args, 'success_gamma', 0.98), norm_pool=args.norm_pool, subgoal_dir=args.subgoal_dir, success_mask=args.success_mask) from is_ope import load_critic enc, _rew, _flow, _rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) args.d_z = cfg["d_z"] pfeat, d_pol = policy_features(args, enc, d, cfg, dev) Path(args.out).mkdir(parents=True, exist_ok=True) print(f"[iql] {d.n_ep} eps, chunk={d.chunk}, d_z={args.d_z}, tau={args.tau}", flush=True)
q, v = train_iql(d, enc, args, dev, args.iql_steps) torch.save({"iql_q": True, "cam_res": getattr(d, "cam_res", "UNKNOWN"), "q": q.state_dict(), "v": v.state_dict(), "config": vars(args), "d_act": d.chunk * d.adim, "d_z": args.d_z, "n_task": d.n_task, "critic": args.critic}, Path(args.out) / "iql_q.pt") print(f"[iql] saved Q/V -> {Path(args.out) / 'iql_q.pt'}", flush=True) if args.q_only: print("[iql] DONE (q-only)", flush=True); return
from awr import offline_score rng = np.random.default_rng(args.seed + 23) pol = train_bc(d, enc, args, dev, only_success=args.init_pool, steps=args.bc_steps, pfeat=pfeat, d_policy=d_pol, resume_path=str(Path(args.out) / 'bc_resume.pt')) log = {"config": vars(args), "pi_0": offline_score(d, enc, pol, rng, dev, pfeat=pfeat), "rounds": []} print(f"[iql] pi_0 {log['pi_0']}", flush=True)
for r in range(1, args.rounds + 1): new = make_policy(args, d, dev, d_z=d_pol) new.load_state_dict(pol.state_dict()) opt = torch.optim.AdamW(new.parameters(), lr=1e-4, weight_decay=0.01) rg = np.random.default_rng(args.seed + 11 + r) stats = [] for step in range(1, args.awr_steps + 1): b = d.sample_frames(args.batch, rg, "train", dev) if args.awr_pool != "all": keep = ((b["succ"] > 0.5) if args.awr_pool == "succ" else (b["demo"] > 0.5)) if keep.sum() < 8: continue km = keep.cpu().numpy() b = {k: (v_[km] if isinstance(v_, np.ndarray) else (v_[keep] if torch.is_tensor(v_) else v_)) for k, v_ in b.items()} with torch.no_grad(): z = enc(b["x"]) # critic latent -> advantage zp = pfeat(b["x"]) # policy features -> action head adv = q(z, b["a"], b["task"]) - v(z, b["task"]) # See awr.awr_step: the raw advantage saturates the exponent and # turns AWR into a hard sign filter on a critic whose action win # rate is 0.568. if args.adv_norm == "std": adv = (adv - adv.mean()) / adv.std().clamp_min(1e-6) w = (args.awr_beta * adv).exp().clamp(0, args.w_max) w = w / w.mean().clamp_min(1e-6) loss = (w * policy_nll(new, zp, b["task"], b["a"], reduce=False)).mean() opt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_(new.parameters(), 1.0); opt.step() if step % 500 == 0: stats.append({"step": step, "loss": float(loss), "mean_abs_adv": float(adv.abs().mean())}) print(f"[iql-awr] r{r} {step} loss={float(loss):.3f} " f"|adv|={float(adv.abs().mean()):.4f}", flush=True) new.eval(); pol = new sc = offline_score(d, enc, pol, rng, dev, pfeat=pfeat) log["rounds"].append({"round": r, "awr": stats, "score": sc}) print(f"[iql] round {r} {sc}", flush=True) out = Path(args.out); out.mkdir(parents=True, exist_ok=True) torch.save({"pol": pol.state_dict(), "round": r, "config": vars(args)}, out / f"policy_r{r}.pt") (out / "loop.json").write_text(json.dumps(log, indent=2)) print("[iql] DONE", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727"""Importance-sampled off-policy evaluation of Q^pi with the RSM occupancy.
Implements the notes' Sections 7-9 without ever needing a normalized actiondensity, which matters because the behavior policy here is a pi0.5 flow modelsampled as an SDE at noise 0.5 and has no tractable likelihood.
Step 1 per-decision ratio by CLASSIFICATION. Train c(z, A) to separate a logged chunk (label 0, from mu) from a chunk sampled from pi at the SAME logged state (label 1). On balanced classes the logit is exactly log pi/mu, so `w_j = exp(logit)` replaces pi(a_j|s_j)/mu(a_j|s_j).
Step 2 chunk product. A beta-hop spans several 10-step decisions; the first is conditioned on, so W = prod over the INTERIOR decisions only. With a 10-action chunk a 50-frame hop carries ~5 factors instead of 50, which is the variance argument for doing the correction per hop rather than over a flat trajectory.
Step 3 Rao-Blackwellize onto the endpoint. Regress W onto (z, A, z') under squared loss; the minimizer is E[W | endpoint] = d^pi_beta / d^mu_beta. This is the only form usable at inference, because the occupancy model emits an endpoint and never the intervening actions.
Step 4 recursive read. Q^pi = E[ C * r(z_end) ] / (1-gamma) with C the product of endpoint weights along the hops, self-normalized. Boundary actions are drawn from pi, so only chunk interiors need correcting.
VALIDATION (the gate, and it can fail): a synthetic target policy whoseoccupancy we can compute directly. Take pi := "mu restricted to episodes thatsucceed". d^pi is then estimable by fitting the occupancy on successes only,while the IS estimate reweights the all-data model. If the corrected estimatedoes not move toward the success-only reference, the weights are not working andno policy is trained on them."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, json, timefrom pathlib import Pathimport numpy as npimport torchimport torch.nn.functional as F
from types import SimpleNamespace
from model import (Encoder, RewardHead, OccFlow, RatioNet, EndpointRatio, BCHead, FlowPolicy)from data import LiberoRSMDatafrom train_rsm import sample_future, auc
class _LatWithProprio(torch.nn.Module): """Encoder wrapper that re-appends the proprio channel to the latent.
Training may append n_pr normalised proprio dims to the 256-d latent so the successor has to PREDICT an action-sensitive channel (action-proprio |r| 0.98 vs action-latent 0.49). The checkpoint therefore carries a d_z+n_pr latent, and rebuilding the heads at d_z alone fails with a size mismatch. """
def __init__(self, enc, n_pr, mu, sd): super().__init__() self.enc = enc; self.n_pr = n_pr self.register_buffer("mu", mu); self.register_buffer("sd", sd)
def forward(self, x): z = self.enc(x) if not self.n_pr: return z return torch.cat([z, (x[:, -self.n_pr:] - self.mu) / self.sd], -1)
def back(self, z): """PCA checkpoints only: latent -> full state (n_pr == 0 there).""" return self.enc.back(z)
def load_critic(path, d_in, n_task, device, data=None): ck = torch.load(path, map_location=device, weights_only=False) c = ck["config"] n_pr = int(ck.get("n_pr", 0) or 0) enc_kind = ck.get("enc_kind", c.get("enc", "mlp")) or "mlp" if enc_kind == "identity": # train_rsm.py --enc identity: the z-scored feature is the latent (d_z == feature dim). # The blob's d_in records the feature width the run saw; a cache of another width # would silently mis-size every head, so refuse it here. d_ck = int(ck.get("d_in", c["d_z"])) if int(d_in) != d_ck: raise RuntimeError(f"identity-encoder checkpoint was trained on {d_ck}-d features, " f"cache provides {d_in}-d") from model import IdentityEncoder base = IdentityEncoder(d_in).to(device) d_lat = d_in + n_pr elif enc_kind == "pca": d_ck = int(ck.get("d_in", d_in)) if int(d_in) != d_ck: raise RuntimeError(f"PCA checkpoint was fitted on {d_ck}-d features, cache provides {d_in}-d") from model import PCAEncoder base = PCAEncoder(d_in, int(c["pca_dim"])).to(device) base.load_state_dict(ck["enc"]) # mean + W buffers d_lat = int(c["pca_dim"]) + n_pr else: d_lat = c["d_z"] + n_pr base = Encoder(d_in, c["d_z"], c["enc_width"]).to(device) base.load_state_dict(ck["enc"]) if n_pr: if data is None or data.proprio is None: raise RuntimeError(f"checkpoint appends {n_pr} proprio dims; pass data=") pr = np.asarray(data.proprio[::37], np.float32) mu = torch.tensor(pr.mean(0), device=device) sd = torch.tensor(pr.std(0) + 1e-6, device=device) else: mu = sd = torch.zeros(0, device=device) enc = _LatWithProprio(base, n_pr, mu, sd).to(device) rew = RewardHead(d_lat, n_task).to(device) flow = OccFlow(d_lat, ck["d_act"], n_task, width=c["flow_width"], depth=c["flow_depth"], norm=bool(c.get("flow_norm", 0)), dropout=float(c.get("flow_dropout", 0.0) or 0.0)).to(device) rew.load_state_dict(ck["rew"]) flow.load_state_dict(ck["flow"]) for m in (enc, rew, flow): m.eval() for p in m.parameters(): p.requires_grad_(False) c = dict(c); c["d_z"] = d_lat # downstream sizes policies by the FULL latent c["enc_kind"] = enc_kind return enc, rew, flow, ck["rms"].to(device), c
# --------------------------------------------------------------------------- ## pi_0: behaviour cloning on a chosen slice of the corpus# --------------------------------------------------------------------------- #def make_policy(args, d, device, d_act=None, d_z=None): """Flow by default. A Gaussian target against a flow-SDE behaviour policy let the ratio classifier hit 100% accuracy by recognising the SAMPLER rather than the policy: E_mu[W] came out 0.181 in BOTH the signal gate and the null gate where the two policies were meant to be the same. Matching the family removes that shortcut.""" fam = getattr(args, "policy_family", "concat") da = d_act or (d.chunk * d.adim) dz = args.d_z if d_z is None else d_z if fam == "gauss": return BCHead(dz, da, d.n_task).to(device) if fam == "flow": return FlowPolicy(dz, da, d.n_task).to(device) from model import ConcatFlowPolicy return ConcatFlowPolicy(dz, da, d.n_task, width=int(getattr(args, "pol_width", 1024) or 1024), depth=int(getattr(args, "pol_depth", 4) or 4)).to(device)
def policy_features(args, enc, d, cfg, device=None): """(module, width) feeding the POLICY -- deliberately separate from the critic's latent. See model.RawFeat for why raw is the default.""" from model import RawFeat mode = getattr(args, "policy_features", "raw") if mode != "raw": return enc, cfg["d_z"] scale = np.ones(d.feat_dim, np.float32) if getattr(args, "feat_scale", "zscore") == "center" and d.norm_sd is not None: n_pr = 0 if d.proprio is None else d.proprio.shape[1] n_z = d.feat_dim - n_pr sd_z = d.norm_sd[:n_z] scale[:n_z] = sd_z / max(float(sd_z.mean()), 1e-6) # undo the whitening rf = RawFeat(d.feat_dim, torch.from_numpy(scale)) return (rf if device is None else rf.to(device)), d.feat_dim
def policy_nll(pol, z, task, a, reduce=True): """-log pi surrogate: exact for the Gaussian head, per-sample flow-matching loss for the flow head (the substitution the smolvla AWR run used).""" if hasattr(pol, "fm_loss"): return pol.fm_loss(z, task, a, reduce=reduce) lp = -pol.log_prob(z, task, a) return lp.mean() if reduce else lp
@torch.no_grad()def sampled_action_mse(pol, d, pfeat, rng, device, pool, n=2048, chunk_len=None): """Held-out ODE-sampled reconstruction MSE -- THE flow-BC metric.
The raw conditional-flow-matching loss is a velocity residual at a random flow time and does NOT track how good the ACTIONS the policy emits are: on this corpus it ranked raw features best (0.158) while the closed loop said otherwise. What the lane's own BC sweep ranks on, and what we rank on here, is the MSE between the logged chunk and the chunk the policy actually integrates out of noise.""" cl = chunk_len or d.chunk eps_pool = np.array([e for e in d.val_eps if pool[e]]) if not len(eps_pool): return float("nan") w = d.ep_len[eps_pool].astype(np.float64); w /= w.sum() e = rng.choice(eps_pool, size=n, p=w) lo, hi = d.ep_from[e], d.ep_to[e] t = lo + (rng.random(n) * (hi - lo)).astype(np.int64) x = torch.from_numpy(d._feat(t)).to(device) a = torch.from_numpy(d._chunk_at(t, e, chunk_len=cl)).to(device) tk = torch.from_numpy(d.ep_task[e]).long().to(device) out = [] for i in range(0, n, 512): z = pfeat(x[i:i + 512]) out.append(((pol.sample(z, tk[i:i + 512]) - a[i:i + 512]) ** 2).mean(-1)) return float(torch.cat(out).mean())
# Optional W&B run for the BC loop (set by bc_arm.py when RSM_WANDB_ENTITY is set; None = off).# Kept as a module global rather than an args attribute so that vars(args) stays JSON/torch-serialisable.WANDB_RUN = None
def train_bc(d, enc, args, device, only_success=True, steps=8000, chunk_len=None, pfeat=None, d_policy=None, resume_path=None): """chunk_len=None fits the occupancy's action window. Pass the behaviour policy's DECISION period to fit a policy directly comparable to logged decisions: scoring the first 10 actions of a 100-action plan is not the same distribution a 10-action policy emits, and that mismatch alone kept the ratio classifier at 0.98 accuracy.""" cl = chunk_len or d.chunk pf = enc if pfeat is None else pfeat pol = make_policy(args, d, device, d_act=cl * d.adim, d_z=d_policy) # pool selector: "succ" = successful episodes, "demos" = demonstrations only # (the BC-on-demos baseline), None/False = everything. # plain Adam, no weight decay: the 0.584 recipe's optimiser opt = torch.optim.Adam(pol.parameters(), lr=getattr(args, "lr", 3e-4)) rng = np.random.default_rng(args.seed + 1) # ONE chain. This used to be two (the rollsucc branch was added as a fresh `if` # after the mask block), so the trailing `elif only_success:` -- true for any # non-empty string -- silently overrode "demos" with ALL successes. BC-on-demos # arms trained on 24,673 episodes instead of 500, and looked identical to the # successes arm on both clusters (2026-09-14). _mask = getattr(args, "success_mask", "") or "" _ver = None if _mask: _ver = np.load(_mask)["keep"].astype(bool) print(f"[bc] success mask: {int(_ver.sum())}/{len(_ver)} episodes verified", flush=True) if only_success == "demos": # a replayed demo that did not reproduce success is inadmissible (legacy demo # caches mark every demo successful, so this is a no-op for them) ok = d.ep_demo & d.ep_success elif only_success == "demos_succ": ok = d.ep_demo | d.ep_success elif only_success == "rollsucc_mix": _k = int(getattr(args, "demos_per_task", 5) or 0) ok = (d.ep_success & ~d.ep_demo).copy() _rs = np.random.default_rng(args.seed + 77) _added = 0 for _t in range(d.n_task): _cand = np.where(d.ep_demo & (d.ep_task == _t))[0] if len(_cand) == 0 or _k <= 0: continue _pick = _rs.choice(_cand, size=min(_k, len(_cand)), replace=False) ok[_pick] = True _added += len(_pick) print(f"[bc] rollsucc_mix: {int((d.ep_success & ~d.ep_demo).sum())} rollout " f"successes + {_added} demos ({_k}/task)", flush=True) elif only_success == "rollsucc": ok = d.ep_success & ~d.ep_demo elif only_success: # True / "succ": demos + successful rollouts ok = d.ep_success.copy() else: ok = np.ones(d.n_ep, bool) # Admissibility: a logged success that does not reproduce in the eval env is never # cloned. Applied to every pool that contains rollout successes (demos are always kept). if _ver is not None and only_success != "demos": _before = int(ok.sum()); ok = ok & (_ver | d.ep_demo) print(f"[bc] verified filter: {_before} -> {int(ok.sum())} episodes", flush=True) print(f"[bc] pool={only_success!r}: {int(ok.sum())} episodes " f"({int((ok & d.ep_demo).sum())} demos + {int((ok & ~d.ep_demo).sum())} rollouts)", flush=True) pool = np.array([e for e in d.train_eps if ok[e]]) # Init-density ablation: cap the number of EPISODES per task. Every demo and # every fresh-reset rollout starts from its own independent BDDL draw, so # episodes-per-task IS distinct-initial-conditions-per-task. Holding the pool # (hence data quality) fixed and varying this isolates coverage density from # quality, which the demos-vs-rollouts comparison confounds. _cap = int(getattr(args, "eps_per_task", 0) or 0) if _cap > 0: _keep, _seen = [], {} _rs = np.random.default_rng(args.seed + 5150) for _e in _rs.permutation(pool): _t = int(d.ep_task[_e]) if _seen.get(_t, 0) < _cap: _keep.append(_e); _seen[_t] = _seen.get(_t, 0) + 1 pool = np.array(sorted(_keep)) print(f"[bc] init-density cap: {_cap} episodes/task -> {len(pool)} episodes " f"over {len(_seen)} tasks", flush=True) ev_every = max(1, steps // 20) ev_rng = np.random.default_rng(args.seed + 77) best, best_sd, best_step = float("inf"), None, 0 # Resume support. These arms run on a preemptible queue; without it a # preemption at step 96000 restarts from zero and the arm never finishes. start = 0 if resume_path is not None and Path(resume_path).exists(): ck = torch.load(resume_path, map_location=device, weights_only=False) pol.load_state_dict(ck["pol"]); opt.load_state_dict(ck["opt"]) start, best, best_step = ck["step"], ck["best"], ck["best_step"] best_sd = ck["best_sd"] rng = np.random.default_rng(ck["rng_seed"]) print(f"[bc] resumed at step {start} (best {best:.5f} @ {best_step})", flush=True) # Hard Q-filter on the TRAINING DATA (the port's `qfilter_frac`, never run here). # Distinct from ranking (picks actions at test time) and from AWR (re-weights # gradients): this decides which logged (s,a) pairs are cloned at all, and the # resulting policy needs no test-time sampling -- so a value-free selector like # medoid cannot reproduce it. qf_frac = float(getattr(args, "qfilter_frac", 0.0) or 0.0) qf_ctx = None if qf_frac > 0: _enc, _rew, _flow, _rms, _cfg = load_critic(args.critic, d.feat_dim, d.n_task, device, data=d) qf_ctx = (_enc, _rew, _flow, _rms) print(f"[bc] Q-filter ON: cloning the top {qf_frac:.0%} of each " f"oversampled batch by critic advantage", flush=True)
for step in range(start + 1, steps + 1): nb = args.batch if qf_frac <= 0 else int(args.batch / qf_frac) w = d.ep_len[pool].astype(np.float64) _dw = float(getattr(args, "demo_weight", 1.0) or 1.0) if _dw != 1.0: w = w * np.where(d.ep_demo[pool], _dw, 1.0) # up-weight demonstrations in a mixed pool w /= w.sum() e = rng.choice(pool, size=nb, p=w) lo, hi = d.ep_from[e], d.ep_to[e] t = lo + (rng.random(nb) * (hi - lo)).astype(np.int64) x = torch.from_numpy(d._feat(t)).to(device) a = torch.from_numpy(d._chunk_at(t, e, chunk_len=cl)).to(device) task = torch.from_numpy(d.ep_task[e]).long().to(device) if qf_frac > 0: with torch.no_grad(): _e2, _r2, _f2, _rm2 = qf_ctx zc = _e2(x) q, _ = q_recursive(zc, a, task, rew=_r2, flow=_f2, rms=_rm2, pol=None, wend=None, beta=getattr(args, "beta_q", 0.98), gamma=0.99, depth=1, n_particles=8, use_is=False, pessimism=0.0) keep = torch.topk(q, args.batch).indices x, a, task = x[keep], a[keep], task[keep] with torch.no_grad(): z = pf(x) loss = policy_nll(pol, z, task, a) opt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_(pol.parameters(), 1.0); opt.step() if step % ev_every == 0 or step == steps: pol.eval() m = sampled_action_mse(pol, d, pf, ev_rng, device, ok, chunk_len=cl) pol.train() tag = "" if m == m and m < best: best, best_step = m, step best_sd = {k: v.detach().clone() for k, v in pol.state_dict().items()} tag = " <- best" print(f"[bc] {step} cfm={float(loss):.4f} sampled_mse={m:.5f}{tag}", flush=True) if WANDB_RUN is not None: try: WANDB_RUN.log({"bc/loss": float(loss), "bc/sampled_mse": m, "bc/best_sampled_mse": best, "bc/best_step": best_step}, step=step) except Exception as _e: # logging must never kill a run print(f"[bc] wandb log failed: {_e}", flush=True) if resume_path is not None: tmp = str(resume_path) + ".tmp" torch.save({"pol": pol.state_dict(), "opt": opt.state_dict(), "step": step, "best": best, "best_step": best_step, "best_sd": best_sd, "rng_seed": args.seed + 1}, tmp) _os.replace(tmp, resume_path) # atomic: a kill mid-write is safe _se = int(getattr(args, "save_every", 0) or 0) if resume_path is not None and _se and step % _se == 0: # Periodic checkpoints so the policy can be selected by arg-max over # checkpoints on a held-out set of VALIDATION initial conditions -- # the sampled-MSE proxy above picked a checkpoint 0.10 SR below the # last one (BCdemo_f: 102k vs 120k), so it is not a usable selector. torch.save({"pol": pol.state_dict(), "round": 1, "step": step, "config": vars(args), "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")}, str(Path(resume_path).parent / f"policy_s{step}.pt")) # Keep the checkpoint that emits the best ACTIONS, not the last one. if best_sd is not None: pol.load_state_dict(best_sd) print(f"[bc] restored best sampled_mse={best:.5f} from step {best_step}", flush=True) pol.eval() pol.best_sampled_mse = best return pol
# --------------------------------------------------------------------------- ## Step 1: per-decision density ratio by classification# --------------------------------------------------------------------------- #class LikelihoodRatio: """Genuine likelihood ratio pi(a|z)/mu_hat(a|z), no classifier.
The identity control killed the discriminative route: two BC policies trained on IDENTICAL data with different seeds are 0.945-0.977 separable, the same as target-vs-behaviour (0.941). A classifier reads WHICH NETWORK produced a sample -- sampler artifacts, generator fingerprints -- long before it reads a density difference, so its logit is not log pi/mu at all.
Evaluating densities AT THE LOGGED ACTION removes that channel: nothing is asked to tell samples apart. mu has no tractable density (pi0.5 flow SDE), so we fit `mu_hat`, a Gaussian behaviour model, by maximum likelihood on the logged actions. Both sides are then tractable and the ratio is a real one.
Null test is exact by construction: with pi == mu_hat the ratio is identically 1, which no classifier-based estimator could guarantee. """
def __init__(self, pi, mu_hat, clip=1.5): self.pi = pi; self.mu_hat = mu_hat; self.clip = clip
@torch.no_grad() def __call__(self, z, a, task): lr = self.pi.log_prob(z, task, a) - self.mu_hat.log_prob(z, task, a) return lr.clamp(-self.clip, self.clip)
def eval(self): return self
def state_dict(self): return {"pi": self.pi.state_dict(), "mu_hat": self.mu_hat.state_dict(), "clip": self.clip}
def train_likelihood_ratio(d, enc, args, device, steps=6000, only_success=True, chunk_len=None): """Fit tractable Gaussian densities for BOTH policies, then take their ratio.""" cl = chunk_len or d.chunk ga = SimpleNamespace(d_z=args.d_z, batch=args.batch, seed=args.seed, policy_family="gauss") print(f"[likratio] fitting mu_hat (Gaussian behaviour model, chunk {cl})", flush=True) mu_hat = train_bc(d, enc, ga, device, only_success=False, steps=steps, chunk_len=cl) gb = SimpleNamespace(d_z=args.d_z, batch=args.batch, seed=args.seed + 5, policy_family="gauss") print(f"[likratio] fitting pi ({'successes' if only_success else 'all data'})", flush=True) pi = train_bc(d, enc, gb, device, only_success=only_success, steps=steps, chunk_len=cl) # sanity: E_mu[pi/mu_hat] over LOGGED actions must be ~1 rng = np.random.default_rng(args.seed + 41) acc = [] with torch.no_grad(): for _ in range(8): b = d.sample_frames(1024, rng, "val", device) z = enc(b["x"]) a = torch.from_numpy( d._chunk_at(b["t_idx"], b["ep"], chunk_len=cl)).to(device) lr = (pi.log_prob(z, b["task"], a) - mu_hat.log_prob(z, b["task"], a)).clamp(-1.5, 1.5) acc.append(lr.exp()) w = torch.cat(acc) print(f"[likratio] E_mu[w] = {float(w.mean()):.4f} (target 1.0) " f"median {float(w.median()):.4f} ESS " f"{float((w.sum()**2)/(w.pow(2).sum()*len(w))):.3f} " f"p95 {float(w.quantile(0.95)):.3f}", flush=True) return LikelihoodRatio(pi, mu_hat), pi
def train_ratio(d, enc, pol, args, device, steps=6000): """Density-ratio classifier, optionally on SMOOTHED chunks.
Measured: with a Gaussian target vs the flow-SDE behaviour policy the classifier hit acc 0.999 (bce 0.0035) -- it was recognising the sampler. Matching the family (FlowPolicy) dropped it to acc 0.98 (bce 0.076), a 20x drop in confidence, but the two are still near-separable because the logged data was collected with SDE noise 0.5 while the target policy samples an ODE.
`ratio_smooth` adds the SAME Gaussian kernel to both classes before the classifier. That estimates the ratio of the SMOOTHED densities, which is well-defined by construction and trades a controlled bias for overlap. A ratio between two near-disjoint distributions is not estimable at all, so a blurred but finite ratio is the more useful object. """ rc = int(getattr(args, "ratio_chunk", 0) or d.chunk) net = RatioNet(args.d_z, rc * d.adim, d.n_task).to(device) opt = torch.optim.AdamW(net.parameters(), lr=3e-4, weight_decay=0.01) rng = np.random.default_rng(args.seed + 2) sm = float(getattr(args, "ratio_smooth", 0.0)) # Per-dimension kernel: the 7 action dims span std 0.031 to 0.975 (the # gripper is near-binary), so one scalar sigma would erase the fine dims # while barely touching the gripper. sigma_i = smooth * std_i. a_scale = None if sm > 0: _b = d.sample_frames(4096, np.random.default_rng(args.seed + 99), "train", device) _am = torch.from_numpy( d._chunk_at(_b["t_idx"], _b["ep"], chunk_len=rc)).to(device) a_scale = _am.std(0).clamp_min(1e-3) * sm print(f"[ratio] per-dim smoothing on, mean sigma " f"{float(a_scale.mean()):.4f}", flush=True) for step in range(1, steps + 1): b = d.sample_frames(args.batch, rng, "train", device) with torch.no_grad(): z = enc(b["x"]) a_pi = pol.sample(z, b["task"]) if a_pi.shape[-1] != rc * d.adim: a_pi = a_pi[:, :rc * d.adim] a_mu = torch.from_numpy( d._chunk_at(b["t_idx"], b["ep"], chunk_len=rc)).to(device) if sm > 0: a_mu = a_mu + a_scale * torch.randn_like(a_mu) a_pi = a_pi + a_scale * torch.randn_like(a_pi) logit_mu = net(z, a_mu, b["task"]) # logged -> label 0 logit_pi = net(z, a_pi, b["task"]) # from pi -> label 1 loss = (F.binary_cross_entropy_with_logits(logit_mu, torch.zeros_like(logit_mu)) + F.binary_cross_entropy_with_logits(logit_pi, torch.ones_like(logit_pi))) opt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0); opt.step() if step % 1000 == 0: with torch.no_grad(): acc = ((logit_pi > 0).float().mean() + (logit_mu < 0).float().mean()) / 2 print(f"[ratio] {step} bce={float(loss):.4f} acc={float(acc):.3f}", flush=True) net.eval() return net
# --------------------------------------------------------------------------- ## Step 2+3: chunk product -> endpoint weight# --------------------------------------------------------------------------- #@torch.no_grad()def precompute_decision_logratio(d, enc, ratio, device, batch=4096, rc=None): """One pass over the cache -> per-frame log pi/mu at DECISION points, plus a per-episode prefix sum.
The logged policy re-decided every `chunk` frames, so the only frames that carry a ratio factor are ep_from + chunk*j. Prefix-summing them turns the chunk product of Section 7 into an O(1) lookup per sample, instead of one network call per interior decision (16x fewer forwards per training step). """ N = int(d.ep_to[-1]) rc = rc or d.chunk lr = np.zeros(N, np.float32) dec = np.zeros(N, bool) for i in range(d.n_ep): lo, hi = int(d.ep_from[i]), int(d.ep_to[i]) dec[np.arange(lo, hi, rc)] = True idx = np.nonzero(dec)[0] ep_of = np.searchsorted(d.ep_to, idx, side="right") for s in range(0, len(idx), batch): sl = idx[s:s + batch] x = torch.from_numpy(d._feat(sl)).to(device) a = torch.from_numpy( d._chunk_at(sl, ep_of[s:s + batch], chunk_len=rc)).to(device) tk = torch.from_numpy(d.ep_task[ep_of[s:s + batch]]).long().to(device) lr[sl] = ratio(enc(x), a, tk).float().cpu().numpy() # log pi/mu pre = np.zeros(N + 1, np.float64) np.cumsum(lr, out=pre[1:]) # restart the prefix at every episode boundary so no product spans episodes for i in range(d.n_ep): lo = int(d.ep_from[i]) pre[lo + 1:int(d.ep_to[i]) + 1] -= pre[lo] return pre
def chunk_logW_fast(pre, t_idx, fut_idx): """log W over decisions strictly inside (t, fut). The decision AT t is the conditioned-on action a_t and is excluded, matching w_{t,k} in the notes.""" lo = np.minimum(t_idx + 1, fut_idx) return (pre[fut_idx] - pre[lo]).astype(np.float32)
def train_endpoint_ratio(d, enc, ratio, args, device, steps=6000, logw_clip=4.0): """Squared-loss regression of W onto (z, A, z'): the minimizer is E[W|endpoint].""" rc = int(getattr(args, "ratio_chunk", 0) or d.chunk) pre = precompute_decision_logratio(d, enc, ratio, device, rc=rc) # Sized by the OCCUPANCY chunk: w*(z, A, z') conditions on the action the # successor was conditioned on. Only the per-decision classifier uses rc. net = EndpointRatio(args.d_z, d.chunk * d.adim, d.n_task).to(device) opt = torch.optim.AdamW(net.parameters(), lr=3e-4, weight_decay=0.01) rng = np.random.default_rng(args.seed + 3) for step in range(1, steps + 1): b = d.sample(args.batch, rng, args.beta_q, args.beta_q, "train", device) logW = torch.from_numpy( chunk_logW_fast(pre, b["t_idx"], b["fut_idx"])).to(device) W = logW.clamp(-logw_clip, logw_clip).exp() with torch.no_grad(): z = enc(b["x_now"]); zf = enc(b["x_fut"]) pred = net(z, b["a_now"], zf, b["task"]) loss = (pred - W).pow(2).mean() opt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0); opt.step() if step % 1000 == 0: print(f"[wend] {step} mse={float(loss):.4f} " f"E_mu[W]={float(W.mean()):.3f} E_mu[what]={float(pred.mean()):.3f}", flush=True) net.eval() # Global calibration: E_mu[w] must be 1 for a correct density ratio. Rescale # on held-out data and RECORD the factor -- a factor far from 1 means the # ratio is mis-fit, and that is a finding, not something to silently absorb. with torch.no_grad(): acc = [] for _ in range(8): b = d.sample(1024, rng, args.beta_q, args.beta_q, "val", device) z = enc(b["x_now"]); zf = enc(b["x_fut"]) acc.append(net(z, b["a_now"], zf, b["task"])) m = float(torch.cat(acc).mean()) net.calib = 1.0 / max(m, 1e-3) print(f"[wend] calibration E_mu[w]={m:.3f} -> scale x{net.calib:.3f}", flush=True) return net
# --------------------------------------------------------------------------- ## Step 4: recursive, importance-corrected Q# --------------------------------------------------------------------------- #@torch.no_grad()def q_recursive(enc_z, a_chunk, task, *, rew, flow, rms, pol, wend, beta, gamma, depth=2, n_particles=16, flow_steps=8, self_norm=True, use_is=True, logw_clip=4.0, pessimism=0.0, crn=False): """Q^pi(z,A) by composing beta-hops. Boundary actions come from pi, so only chunk interiors carry a weight. depth is small on purpose (2-3).
crn=True: common random numbers across the B rows (candidates). Particle i of every candidate uses the same flow noise, the same restart coin and the same hop- policy noise, so Q differences between candidates are paired and the Monte-Carlo error cancels in the arg-max (the OCBench recipe scores all N candidates on one shared z0 for exactly this reason). With independent draws, near-identical candidates are ranked by noise.""" dev = enc_z.device B = enc_z.shape[0] D = enc_z.shape[1] def _tile(t): # [n_particles, ...] -> [B*n_particles, ...] matching repeat_interleave return t.repeat(B, *([1] * (t.dim() - 1))) p = (gamma - beta) / (gamma * (1.0 - beta)) # restart probability p = float(np.clip(p, 0.0, 0.95)) # Truncating the recursion at `depth` is not free: the composition needs an # unbounded number of hops, so a finite depth realises a SHORTER effective # horizon than the nominal gamma. Report it rather than claim gamma. # E[hops] = (1 - p^L)/(1 - p), each hop covering 1/(1-beta) frames. z = enc_z.repeat_interleave(n_particles, 0) a = a_chunk.repeat_interleave(n_particles, 0) tk = task.repeat_interleave(n_particles, 0) bq = torch.full((z.shape[0],), beta, device=dev) logC = torch.zeros(z.shape[0], device=dev) alive = torch.ones(z.shape[0], dtype=torch.bool, device=dev) z_end = z.clone() for h in range(depth): x0 = _tile(torch.randn(n_particles, D, device=dev)) if crn else None zp = sample_future(flow, z, a, tk, bq, rms, flow_steps, n=1, x0=x0) if use_is and wend is not None: w = (wend(z, a, zp, tk) * getattr(wend, "calib", 1.0)).clamp_min(1e-4) logC = logC + torch.where(alive, w.log().clamp(-logw_clip, logw_clip), torch.zeros_like(logC)) z_end = torch.where(alive[:, None], zp, z_end) if h == depth - 1: break coin = _tile(torch.rand(n_particles, device=dev)) if crn else torch.rand(z.shape[0], device=dev) cont = alive & (coin < p) if not cont.any(): break z = torch.where(cont[:, None], zp, z) if crn and hasattr(pol, "sample_eps"): a_new = pol.sample_eps(z, tk, _tile(torch.randn(n_particles, pol.d_act, device=dev))) else: a_new = pol.sample(z, tk) a = torch.where(cont[:, None], a_new, a) alive = cont r = torch.sigmoid(rew(z_end, tk)).view(B, n_particles) C = logC.exp().view(B, n_particles) if self_norm: q = (C * r).sum(1) / C.sum(1).clamp_min(1e-6) else: q = (C * r).mean(1) if pessimism: # Penalise DISAGREEMENT between particles. The measured failure mode of # this critic is off-support optimism: conditioned on an action the data # never took, the occupancy flow produces diffuse samples that drift # toward the dataset mean, where the reward head returns roughly the base # rate -- which outranks a confident low reward on a genuinely failing # taken action. The action win rate accordingly starts near 0.55 and # decays below chance as the flow sharpens. Particle spread is exactly # the signal that separates the two cases, and subtracting it is the # standard offline-RL pessimism penalty. q = q - pessimism * r.std(1) ess = (C.sum(1) ** 2) / (C.pow(2).sum(1)).clamp_min(1e-9) / n_particles return q / (1 - gamma), ess
def q_fold(enc_z, a_chunk, task, *, rew, flow, rms, pol, beta, gamma, depth=1, n_particles=16, flow_steps=8, crn=True): """The OCBench product fold (ocbench_unified_rsm, rsm_core.step_q):
Q_k = c_k + (1 - c_k) * gamma**h * Q_{k+1}, h = 1/(1-beta), Q_{depth+1} = 0
read as reach-or-continue: c_k = read-out at the k-th hop state ("already at a success/goal state"), otherwise pay one hop of discount and inherit the next hop. Hop 1 is decoded from the QUERY action; hop k+1 from pol(hop_k). A FIXED number of hops (no restart coin), per-particle fold, Monte-Carlo mean over n_particles, all candidates (rows of enc_z) scored on the same noise when crn=True -- exactly the recipe's estimator. With the subgoal-fraction head, c_k is the fraction of the goal reached at hop k (partial credit); with the indicator head it is P(success state). Returns Q in [0, 1].""" dev = enc_z.device B, D = enc_z.shape h = 1.0 / (1.0 - beta) def _tile(t): return t.repeat(B, *([1] * (t.dim() - 1))) z = enc_z.repeat_interleave(n_particles, 0) a = a_chunk.repeat_interleave(n_particles, 0) tk = task.repeat_interleave(n_particles, 0) bq = torch.full((z.shape[0],), beta, device=dev) cs = [] for k in range(depth): x0 = _tile(torch.randn(n_particles, D, device=dev)) if crn else None z = sample_future(flow, z, a, tk, bq, rms, flow_steps, n=1, x0=x0) cs.append(torch.sigmoid(rew(z, tk))) if k == depth - 1: break if crn and hasattr(pol, "sample_eps"): a = pol.sample_eps(z, tk, _tile(torch.randn(n_particles, pol.d_act, device=dev))) else: a = pol.sample(z, tk) q = torch.zeros_like(cs[-1]) for c in reversed(cs): # backward fold q = c + (1.0 - c) * (gamma ** h) * q q = torch.nan_to_num(q, nan=0.0).clamp(0.0, 1.0).view(B, n_particles) return q.mean(1), torch.ones(B, device=dev)
def effective_horizon(beta, gamma, depth): """What a depth-truncated recursion actually estimates.""" p = float(np.clip((gamma - beta) / (gamma * (1.0 - beta)), 0.0, 0.95)) hops = (1.0 - p ** depth) / (1.0 - p) frames = hops / (1.0 - beta) return {"restart_p": p, "mean_hops": hops, "mean_hops_untruncated": 1.0 / (1.0 - p), "effective_frames": frames, "gamma_effective": 1.0 - 1.0 / max(frames, 1.0), "gamma_nominal": gamma, "truncation_mass": p ** depth}1234567891011121314151617181920#!/bin/bash#SBATCH --job-name=label_full#SBATCH --account=vision-pulkitag#SBATCH --qos=tig-main#SBATCH --partition=tig-cpu#SBATCH --cpus-per-task=4 --mem=32G#SBATCH --array=0-39#SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%a_%A.out#SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/eval/%x_%a_%A.errset -uo pipefailB=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationS=/data/pulkitag/users/rli14/rlinf_recap_task_expansionexport LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standardexport MUJOCO_GL=osmesa PYTHONUNBUFFERED=1T=$((SLURM_ARRAY_TASK_ID / 4)); K=$((SLURM_ARRAY_TASK_ID % 4))OUT=/data/pulkitag/users/rli14/rsm_libero_runs/subgoals_full; mkdir -p $OUT$B/venvs/rlinf-libero-eval-venv/bin/python \ /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/label_subgoals.py \ --cache /data/pulkitag/scratch/rli14/rsm_libero_cache/full_r256 \ --task $T --shard $K --num-shards 4 --out $OUT/task${T}_s${K}.npz --stride 5.gitattributes+4
README.mdAdded+34
THIRD_PARTY.mdAdded+18
frozen/rsm_libero_freeze_20261002/CLAUDE.mdAdded+291
frozen/rsm_libero_freeze_20261002/FINDINGS.mdAdded+344
frozen/rsm_libero_freeze_20261002/FREEZE_COMMITAdded+1
frozen/rsm_libero_freeze_20261002/README.mdAdded+737
frozen/rsm_libero_freeze_20261002/audit_logged_goal.pyAdded+93
frozen/rsm_libero_freeze_20261002/audit_logged_goal.sbatchAdded+17
frozen/rsm_libero_freeze_20261002/autoresearch_driver.pyAdded+78
frozen/rsm_libero_freeze_20261002/awr.pyAdded+275
frozen/rsm_libero_freeze_20261002/bc_arm.pyAdded+153
frozen/rsm_libero_freeze_20261002/calib_dwm.pyAdded+106
frozen/rsm_libero_freeze_20261002/capture_cpu.sbatchAdded+32
frozen/rsm_libero_freeze_20261002/capture_init_feats.pyAdded+88
frozen/rsm_libero_freeze_20261002/crn_diag.pyAdded+58
frozen/rsm_libero_freeze_20261002/data.pyAdded+587
frozen/rsm_libero_freeze_20261002/df_readout.pyAdded+228
frozen/rsm_libero_freeze_20261002/dinowm_readout.pyAdded+168
frozen/rsm_libero_freeze_20261002/dwm_model.pyAdded+562
frozen/rsm_libero_freeze_20261002/dwm_readout.pyAdded+314
frozen/rsm_libero_freeze_20261002/dwm_readout_timing.pyAdded+78
frozen/rsm_libero_freeze_20261002/encode_parquet.pyAdded+83
frozen/rsm_libero_freeze_20261002/encode_t5.pyAdded+52
frozen/rsm_libero_freeze_20261002/encode_t5.sbatchAdded+16
frozen/rsm_libero_freeze_20261002/eval_closed_loop.pyAdded+1025
frozen/rsm_libero_freeze_20261002/eval_slurm.sbatchAdded+90
frozen/rsm_libero_freeze_20261002/extract_clips.pyAdded+98
frozen/rsm_libero_freeze_20261002/extract_viz.pyAdded+90
frozen/rsm_libero_freeze_20261002/ibm_autoresearch.shAdded+53
frozen/rsm_libero_freeze_20261002/ibm_bias_diag.shAdded+16
frozen/rsm_libero_freeze_20261002/ibm_cell.shAdded+21
frozen/rsm_libero_freeze_20261002/ibm_crn_diag.shAdded+13
frozen/rsm_libero_freeze_20261002/ibm_eval.shAdded+51
frozen/rsm_libero_freeze_20261002/ibm_eval_depth.shAdded+7
frozen/rsm_libero_freeze_20261002/ibm_eval_matrix.shAdded+25
frozen/rsm_libero_freeze_20261002/ibm_eval_matrix_last.shAdded+38
frozen/rsm_libero_freeze_20261002/ibm_eval_ocb.shAdded+23
frozen/rsm_libero_freeze_20261002/ibm_eval_robust.shAdded+25
frozen/rsm_libero_freeze_20261002/ibm_eval_sde.shAdded+20
frozen/rsm_libero_freeze_20261002/ibm_full_wave.shAdded+44
frozen/rsm_libero_freeze_20261002/ibm_pack_onpol.shAdded+12
frozen/rsm_libero_freeze_20261002/ibm_rerender.shAdded+18
frozen/rsm_libero_freeze_20261002/ibm_resubmit_missing.shAdded+30
frozen/rsm_libero_freeze_20261002/ibm_retry_tasks.shAdded+16
frozen/rsm_libero_freeze_20261002/ibm_table.pyAdded+70
frozen/rsm_libero_freeze_20261002/ibm_train_onpol.shAdded+15
frozen/rsm_libero_freeze_20261002/iql.pyAdded+259
frozen/rsm_libero_freeze_20261002/is_ope.pyAdded+727
frozen/rsm_libero_freeze_20261002/label_full.sbatchAdded+20