diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..c5a763bc964a94321e824564ff71abade851c589 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +frozen/rsm_libero_freeze_20261002/notes/action_contrast.pdf filter=lfs diff=lfs merge=lfs -text +frozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -text +frozen/rsm_libero_rsmpi/notes/action_contrast.pdf filter=lfs diff=lfs merge=lfs -text +frozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c3fa3c7d1a271f982fb613a0abff855011375cd7 --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +--- +license: other +tags: [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) | + +```python +from huggingface_hub import hf_hub_download +p = 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/`. diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md new file mode 100644 index 0000000000000000000000000000000000000000..5ea5a417ddddae7dad535b394333bbfc222430a6 --- /dev/null +++ b/THIRD_PARTY.md @@ -0,0 +1,18 @@ +# 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 | diff --git a/frozen/rsm_libero_freeze_20261002/CLAUDE.md b/frozen/rsm_libero_freeze_20261002/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..d7ef613f133e4f77bd596d9cdf80179d3615f3ca --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/CLAUDE.md @@ -0,0 +1,291 @@ +# 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) and +every eval JSON under `rsm_libero_runs/eval/wrong_eval_env/` (143) was produced with the rollout +latents and the evaluator in DIFFERENT feature spaces. Do not cite, compare against, or resume +from them. The results tables further down in this file are retained only as a record of what +was 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 render +resolution 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 reported +number). `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 is +inadmissible 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 latent +must 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 actions +in the environment we evaluate in reproduces its reward labels. If it does not +reproduce, drop the trajectory.** + +This is not a data-cleaning nicety, it is a correctness condition. An offline learner +fits $(s,a,r,s')$ tuples and is then scored in the simulator. If those tuples cannot be +reproduced there, they describe different dynamics than the ones the policy is graded +against, and the learner is being fit to an environment that does not exist. That is the +standard 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, the +diagnostic goal-predicate check passes ~87% — the gap between the two is exactly the +set of trajectories that were honestly recorded but do not reproduce, and **those are +inadmissible 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 states +sbatch --export=ALL,POLICY=$P,NINIT=50,OUT=$E/x.json eval_slurm.sbatch +# B: continuous region +sbatch --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): + +```python +pseed = 7_919_003 + policy_seed*500_009 + tid*1_013 + k # policy sampling RNG +torch.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 RNG +env.reset() # B stops here +if 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-state +vectors (`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` uses +each stored state exactly once. + +**Protocol B** — no override, so object poses come from the task's BDDL placement +regions (`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 a +small 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 more +demanding of the two. (`stock_inside_fresh_support = 0.00` is a consequence of A being +wider, not of a distribution shift.) + +**Neither protocol reproduces the rollout corpus's init distribution.** The corpus was +collected with RLinf's `fresh_reset=true`, documented as "fresh 5 cm inits" — 0.05 +would be wider than both A and B. Our evaluator has no equivalent. Evaluating on the +genuine 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 init +shift under BOTH protocols. + +**Protocol A CANNOT be replicated by varying `SEED`.** `set_init_state` overwrites +whatever `env.reset()` sampled, so `env.seed` has no effect; `np.random.seed` is set but +never 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 500 +episodes. **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 those +same inits. Protocol B draws fresh placements per episode, so `SEED` gives genuine new +episodes 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 depends +on which policy or critic is being evaluated. So with `SEED=0` every arm sees the +identical 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 arms +you 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 collected +from, while the rollout corpus — which trains the critic and the success-pool policies +— comes from a different, wider region. That is a structural advantage for +BC-on-demos and a distribution shift against everything else. Protocol B is the one +where 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**, so +they are comparable by construction. Do not change this venv without re-deriving every +number 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 vendored +installed 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**; every +closed-loop number must come from MIT. + +**The replay divergence is NOT a version mismatch.** Collection and replay share the +venv and the versions, installed before collection and untouched since. Re-executing +logged actions reproduces only ~81% of successes because contact-rich manipulation is +chaotic and the two runs differ in floating-point detail (collection on GPU nodes under +EGL, replay on CPU under osmesa). This is why label correctness must be measured by +evaluating the goal predicate at the LOGGED FINAL state (~87% correct) rather than by +replay (~81%) -- replay conflates label error with non-reproducibility and overstates +it 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 gate +firing 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 on +a *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 of +32 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 gives +those 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 on +it, but it went 0.478 → 0.784 → 0.896 across critics while closed-loop went +0.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 run +through the chunk-10 concat harness scores exactly 0/350. Same signature as the +original 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 NOT +memorise the stock init states.** Protocol A is not inflating the baseline; the bar is +real. The remaining reason to run B is the reverse concern: the critic and the +success-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 beats +BC-on-demos. Using demo *data* without the label is unprivileged; beating +BC-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*. Its +ordering is calibrated only on the proposal's own distribution; outside it the ranking +is actively misleading, not merely uninformative. Corollary: AWR on a pool of uniformly +expert 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_libero +cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo # 5000 eps = 500 demo + 4500 rollout +runs /data/pulkitag/users/rli14/rsm_libero_runs/mit +evals /data/pulkitag/users/rli14/rsm_libero_runs/eval +best critic runs/mit/critic_1M_b995/ckpt_best.pt # band 0.93-0.995, step 110k +BC-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`. diff --git a/frozen/rsm_libero_freeze_20261002/FINDINGS.md b/frozen/rsm_libero_freeze_20261002/FINDINGS.md new file mode 100644 index 0000000000000000000000000000000000000000..f24eb52b9eb714b60ed1cb1d3c6dbceaca1c094a --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/FINDINGS.md @@ -0,0 +1,344 @@ +# 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, and +no 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.530 +through 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**. The +advantage 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, not +in any policy: it converted the end-effector quaternion to **Euler angles**, while +the latent cache stores robosuite **axis-angle**. Three of the eight +proprioception dimensions were a different physical quantity at every timestep of +every 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 did +not 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 float32 +interpolation where the cache builder rounds to uint8, shifting the latent by up +to 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 nothing +about 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 a +per-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 different +distribution (pi0.5 with SDE noise 0.5, about half failures). Whitening is +catastrophic because per-dim std spans 0.048 to 3.675, so it shrinks the few +informative 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 policy +want 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 value +is excellent throughout; only the action channel is missing. + +**The lever is the action window, not the hop.** Holding chunk at 10 and sweeping +the hop is flat (0.568 / 0.558 / 0.551). Widening the window to 100 frames is the +only thing that moves it. A 10-frame chunk does not determine enough about the +outcome on these tasks. + +This is consistent with the lane's own earlier measurement: over 5 frames the +executed action correlates with the **proprio** delta at |r| up to 0.98 but with +the **visual-latent** delta at only 0.49 (mean 0.10). A mean-pooled PaliGemma +embedding 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 own +precondition is that the proposal must be diverse, because ranking N copies of one +action 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 most +mean-collapsed policy.** Our earlier Q-filter was therefore ranking 32 near-copies +of 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 of +hugging 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 only +variable 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 is +uncorrelated with action quality.** Measured directly with +`probe_perturb.py` on demonstration frames, where the logged chunk is by +construction 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 every +level. + +That alone is ambiguous: it is equally consistent with "Q ignores the action" and +with "the Monte-Carlo estimator cannot resolve the action", because q_recursive +draws fresh flow noise per call. `probe_crn.py` separates them by scoring +candidates under COMMON random numbers, which cancels the shared noise from the +paired 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, roughly +linearly in the perturbation size, and at noise 0.8 the paired response exceeds +the estimator noise. What is missing is the SIGN: perturbing an expert action is +exactly as likely to raise Q as to lower it, even at the smallest perturbation and +even with the shared noise cancelled. + +The occupancy model has therefore learned an action-conditioned map whose +counterfactual gradient is meaningless. It is trained only on (state, action +actually taken, observed future); it never sees a counterfactual action with a +real outcome, so off the logged action it extrapolates confidently and +arbitrarily. Magnitude without direction. + +This explains every downstream result coherently, and explains the PARL sweep +better than "weak critic" does. Selection follows an arbitrary direction, so PARL +effectively picks a random member of its candidate set; the wider the set, the +further off-support the winner, and the worse the policy -- exactly the monotone +collapse 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 one +action is still that action, and it is also the only configuration that stays +inside the region where the model was ever trained. + +It also explains why the 0.568 offline win rate looked survivable: comparing the +logged chunk against a DIFFERENT episode's chunk is dominated by on-support versus +off-support, which the occupancy model does capture. Ranking a policy's own +candidates at the same state is a different question, and there the model has +nothing 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 different +question from ranking a policy's *own* candidates, which is what every extraction +method actually does. `probe_perturb.py` asks the right question directly: does Q +prefer 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 to +the WHOLE corpus, failures included, so its candidate set genuinely contains both +good and bad behaviour, then let the value filter it. A critic that can separate +success-like from failure-like actions should recover demonstration-level +performance 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 the +failure modes the critic was trained on, selection makes things worse, not better. + +That run also shows candidate diversity cannot be bought with data: fitting the +proposal to the whole corpus gives action std 0.056, against 0.053 for +demonstrations only. Flow matching learns the conditional mean regardless of how +varied the data behind it is. The only lever that moved diversity was sampling +temperature, and that pushes candidates off the manifold -- exactly where the +value's response was measured to be arbitrary. On-manifold and diverse are not +jointly 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-out +built on it can rank actions, and the horizon over which a short chunk matters is +too 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 moves +the action win rate off ~0.57. diff --git a/frozen/rsm_libero_freeze_20261002/FREEZE_COMMIT b/frozen/rsm_libero_freeze_20261002/FREEZE_COMMIT new file mode 100644 index 0000000000000000000000000000000000000000..3a17f1018fe8d46606e2ef54785b6ed4e30e6a5b --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/FREEZE_COMMIT @@ -0,0 +1 @@ +95842af1aa0e0854934b1fbf67f88a2cd6df850e diff --git a/frozen/rsm_libero_freeze_20261002/README.md b/frozen/rsm_libero_freeze_20261002/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7c5c121446e48c2825fe96a83772d1a0ee4714b4 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/README.md @@ -0,0 +1,737 @@ +# RSM + importance-sampled OPE on the LIBERO-10 rollout corpus + +Goal: learn an occupancy critic on the pi0.5 LIBERO-10 rollout corpus (43,135 +episodes, ~49.5% success), evaluate a target policy off-policy with the +importance-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 a +null 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 the +demos scores its own action the same as the demo action. Half of this corpus is +failure, 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 no +privileged success ball in this latent, so the read-out is a learned reward +decoder, which is what the image branch of `CLAUDE.md` requires anyway. + +The collapse analysis' central lesson drives the diagnostics: a value that ranks +STATES but cannot rank ACTIONS shows flat batch losses and then falls off a +cliff 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 the +state-level success AUC. + +## The importance-sampling correction + +The behaviour policy is a flow model sampled as an SDE at noise 0.5 and has **no +tractable 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 product +is 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 batch +compares against an action from a *different task*. Once the successor is +action-conditioned that lands off-manifold, and the frozen reward decoder scores +off-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 the +sweep, whose recursion originally used an untrained continuation head. + +With a within-task alternative and 8,192 pairs, the base critic ranks actions +above chance near the goal: 0.61 mean near-terminal win, vs a cross-task control +pinned 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 of +the trajectory to the continuation policy. Meanwhile reach at depth 1 grows from +25 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 the +occupancy was trained on a beta BAND covering the query horizon. Recursion earns +its 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) and +ranks near-terminal actions better (0.667 vs 0.609 over 12,000 pairs), but state +AUC 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 positive +at 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 the +contrastive idea. The 1.0 arm is also the one carrying the unexplained +depth-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 is +genuinely 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 not +there is a policy difference to correct, and never improves discrimination. + +**Cause, and it is an implementation error not a property of the method:** the +target policy was a diagonal Gaussian while the behaviour policy is a flow +sampled as an SDE. The classifier reached 100% accuracy by recognising the +SAMPLER, not the policy, so `log pi/mu` was a parametric-family artifact. This is +open question 2 of the notes -- a likelihood-free ratio only works if both +policies 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 control +that would have been reported as a working correction. + +**Fix:** `FlowPolicy` in `model.py` -- a flow-matching target policy that matches +the behaviour family. AWR weights the per-sample flow-matching loss in place of a +log-density. The fix is confirmed only if classifier accuracy drops below 1.0 AND +the 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 noise +0.5** deliberately injected for exploration; any policy fit to that data without +the same dispersion stays distinguishable from it. Exploration noise at +collection time is exactly what makes the behaviour distribution broad, and +breadth is what makes a target policy trivially separable from it. + +Across 3 critics and 2 policy families the correction consistently shifts values +18-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) and +did not fix the estimator. The clearest tell is the **+0.018 AUC gain in the NULL +gate**: a correction that improves discrimination when there is nothing to +correct is fitting something other than the policy difference. The endpoint +regression 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, the +per-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 CROSSES +ZERO -- after two rounds the policy fits FAILED chunks better than successful +ones. Iterating the loop does not merely fail to improve the policy, it +progressively 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 to +downweight the bad ones. With an advantage this weak (the critic ranks actions at +0.608 near the goal and at chance beyond one hop) that reduces to behaviour +cloning on the full half-failure corpus, undoing the success filtering that made +pi_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 baseline +it was supposed to beat: 0.0160-0.0221 in probability units vs the smolvla null +result'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 not +supported by this measurement.** + +**The correction is NOT what breaks the loop.** Turning it off changes nothing +qualitative: + +| 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-cloned +policy with the failure half of the corpus. + +**Caveat on the AWR arms:** `awr.py` seeded numpy but not torch, so the IS-on and +IS-off arms started from different policies (pi_0 gaps 0.0170 vs 0.0089). Each +arm's trajectory relative to its OWN baseline is valid; the absolute numbers are +not 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 than +successful ones. Restricting the pool slows the collapse a lot but still loses +3/4 of the starting gap. **None improves on its own starting point.** The +advantage from this critic is too weak to drive improvement even when it cannot +dilute. + +### 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 should +help. Inverted. That closes the question. + +## Status + +COMPLETE. Critic works; every off-policy result is negative. See the two FINAL +sections 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 it +to predict a 50-frame hop, so 4/5 of the transition came from actions the critic +never saw. A model-free probe shows the action's contribution to predicting success +rises 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 null +result'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, missing +smoothing, ratio scored over the conditioning window instead of decisions, target +policy at the wrong granularity, and two shape/order bugs). Overlap improved every +time -- classifier bce 0.0035 -> 0.286 -- and the weights still collapsed. + +The identity control explains why. Train two BC policies on **identical data** with +different 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** -- sampler +artifacts and generator fingerprints -- not a density difference. Every ratio it +produced was meaningless. `E_mu[W]` sat at 0.13-0.22 in all six configurations +regardless of critic, family, smoothing or granularity, and the final clean null +gate applied a **0.537 relative value shift where zero is correct**. + +**This RETRACTS the intermediate conclusion** that flow SDE noise 0.5 at collection +made the policies too separable and that the fix was data collection. The +separability was never between policies; less injected noise would not have helped. + +**Actual cause:** discriminative density-ratio estimation does not work on +continuous high-dimensional action chunks in this setup. It is an ESTIMATOR +property, not a data property. The notes' likelihood-free route -- classify instead +of requiring normalised densities -- is not viable here. A working correction needs +a genuine likelihood ratio (tractable densities on both sides) or a correction that +does 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, one +fit to the logged actions by maximum likelihood, densities evaluated AT the logged +action 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 the +endpoint regression needed a x10 calibration. + +**Cause is arithmetic.** At `beta_q=0.99` a hop spans 100 frames = **10 policy +decisions**, so W is a product of 10 factors each with p95 = 4.48. That product is +catastrophically heavy-tailed however well-calibrated each factor is. + +This is precisely the variance argument in the notes, and the real case for myopic +beta: keep each hop SHORT so the product has few factors, then recurse. The tension +is 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 per +product, where the probe still shows +0.0334 action contribution (40% above the +10-frame case). That is the configuration most likely to satisfy both, and it is +the 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 this +machine, scores **0.20 / 0.20 / 0.70 on tasks 0-2 (11/30 = 0.367)** before slurm +preempted it. The environment, EGL rendering, pi0.5 encoder, initial states and +success detection here are therefore sound, and any 0% is ours to fix. Two things +were needed to get it to run: `FL15_TASKS` must name the 10 libero_10 tasks (it +defaults to a 15-task list and the head's task embedding then refuses the +checkpoint), 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 is +trained to predict REWARD, so it keeps what separates success from failure and +discards what an action head needs. On a trained arm the policy beat a +predict-the-mean action baseline by only 14% in MSE (0.1456 vs 0.1701) with a +biased gripper channel. The policy now reads the full 4104-d observation; only +the 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.0374 +against 0.042 for the others) and still scored 0/100. Per-dim std on this corpus +spans 0.048 to 3.675, so whitening shrinks the few high-variance directions by up +to 34x relative to the median and flattens the spectrum. Offline the network +simply relearns its weights; at deployment the small online-vs-cache featurisation +difference is then comparable to the signal that survives. Centering removes the +uninformative common mode (mean vector norm 51.1 against a per-frame deviation of +9.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 this +evaluator is equivalent to the lane's; the 0.07 spread is seed variation at +n=100. + +### The whitening ablation is now clean + +A trained on demonstrations, center-scaled, scores 0.580. The identical run with +per-dim z-scored input scores 0.010. Same data, same head, same budget, same +seed -- only the input scaling differs. Whitening flattens a spectrum whose +per-dim std spans 0.048 to 3.675, shrinking the informative high-variance +directions 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 to +0.380. Both critic arms initialised on successes alone, which starts them 0.11 +below the BC-on-demos bar they must clear. `--init-pool demos_succ` now lets both +arms start from demonstrations plus successful rollouts, so the comparison +measures 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, the +concatenation flow head, chunk 10, batch 1024, 120k steps, seed 0. The critic +arms start from the SAME behaviour clone as arm A, so the comparison isolates the +improvement 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 and +0.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-frame +deviation of 9.0), WHICH frames the statistics come from matters (the rollout +corpus 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 to +34x 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 actually +taken 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 AUC +stays above 0.95. The state value is excellent and the action ranking is near +coin-flip. + +The cause is upstream of the occupancy model. This lane measured that over 5 +frames the executed action correlates with the proprio delta at |r| up to 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-frame chunk produces. Raising +the action-contrastive weight asks the flow to use information the latent does +not 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 and +beta 3 the exponent saturates, so the "soft" weight became a hard filter on the +sign of a 0.568-accurate critic. Standardising the advantage recovers most of the +loss (IQL 0.380 -> 0.490) but does not turn a coin-flip critic into an +improvement. + +## Where RSM stands (2026-09-11) + +Matched: full_demo cache, demo statistics, center scaling, concatenation flow +head, chunk 10, batch 1024, 120k steps, seed 0. C and D start from the SAME +demonstration 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 DOWN +from 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 actions +well (win 0.613 against 0.568 at chunk 10, confirming that over a 10-frame hop the +action barely moves the success probability). It does not rescue the result: BC at +chunk 100 fits far worse (sampled action MSE 0.114 against 0.049) and scores +0.00-0.20 per task over the first six, so the better critic sits on top of a much +weaker 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 measured +cause is upstream: over 5 frames the executed action correlates with the proprio +delta 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 a +good 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 uses +the same cache, demonstration statistics, center scaling, concatenation flow head, +batch 1024, 120k steps, seed 0. Both critic arms start from the SAME demonstration +clone 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 IQL +extraction on this dataset.** Behaviour cloning on the 500 demonstrations wins +outright, 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 and +two 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 at +chunk 100), while reward AUC stays above 0.95. The state value is strong; the +action channel is missing, and it is missing upstream of the occupancy model: over +5 frames the executed action correlates with the proprio delta at |r| up to 0.98 +but with the visual-latent delta at only 0.49 (mean 0.10). A mean-pooled PaliGemma +embedding does not resolve what a 10-frame chunk does. Every consumer of that +ranking therefore lowers a good policy rather than raising it. + +The chunk-100 result is the constructive part: lengthening the action window and +the hop is the one intervention that moved the win rate (0.568 -> 0.613), which +says the horizon, not the read-out, is what starves the signal. Making that +usable needs a policy that is still accurate at a 100-frame chunk; ours loses more +to 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, so +the ranking ceiling at chunk 10 is a property of the data rather than a modelling +failure. And the policy trades the other way: a chunk-100 policy loses more to the +longer chunk (sampled action MSE 0.114 against 0.049) than the critic gains. + +With this featurisation you can have an accurate policy or a discriminative +critic, not both. That is the finding, and it is what any future attempt on this +corpus 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, keep +the argmax, distill into a fresh head. The recipe's own precondition is that the +proposal's samples must be DIVERSE, because ranking N copies of one action cannot +improve 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 most +mean-collapsed one, so the earlier Q-filter run was ranking near-identical +candidates. 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. Every +other factor is fixed: same critic, same N, same distillation, same evaluator. +The only variable is how different the candidates are. If the value function +carried signal, widening the candidate set would help; it destroys the policy +instead, so the ranking is not weak, it is pointed the wrong way. A collapsed +proposal scores near BC simply because selection can do little harm when all 32 +candidates are the same action. + +This is the cleanest isolation of the critic in this lane, and it agrees with the +offline 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 critic +that 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 is +worse 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 to +choose among makes it worse, and removing the variance penalty -- so that +selection follows the raw value rather than staying near the mode -- makes it +worse again. The penalty was masking the problem by keeping choices close to the +proposal's mode, not by adding information. + +The RSM value's preference over actions is anti-correlated with action quality on +this corpus. That is a stronger and more useful statement than "the critic is +weak", and it is what the offline probe was too blunt to show: a 0.568 win rate +against dataset alternatives is dominated by on-support versus off-support, which +says nothing about ranking a policy's own candidates. diff --git a/frozen/rsm_libero_freeze_20261002/audit_logged_goal.py b/frozen/rsm_libero_freeze_20261002/audit_logged_goal.py new file mode 100644 index 0000000000000000000000000000000000000000..2364662b54d02b29a26149305dc0277149046b78 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/audit_logged_goal.py @@ -0,0 +1,93 @@ +"""Is the label wrong, or did the replay diverge? These are different claims. + +Replaying logged actions tests reproducibility; the corpus is documented as NOT +bit-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 FINAL +sim_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, base64 +import numpy as np +sys.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() diff --git a/frozen/rsm_libero_freeze_20261002/audit_logged_goal.sbatch b/frozen/rsm_libero_freeze_20261002/audit_logged_goal.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..c80805de4fa27acd9bf575760baf58bc3f1c3d02 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/audit_logged_goal.sbatch @@ -0,0 +1,17 @@ +#!/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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +OUT=/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.npz diff --git a/frozen/rsm_libero_freeze_20261002/autoresearch_driver.py b/frozen/rsm_libero_freeze_20261002/autoresearch_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..d14df344b7ecc8e44e5bb790d64d7a34292f5b98 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/autoresearch_driver.py @@ -0,0 +1,78 @@ +"""Autoresearch driver: reads the local JSON mirror, advances stages, launches the next +cells via ibm_autoresearch.sh. Idempotent (state in a JSON file); run it repeatedly.""" +import json, os, subprocess, sys, glob +sys.argv = ["x"]; sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import ibm_table as T +D = "/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).stdout +cells = 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 r +print(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 2 +s1 = [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" # RSMbd[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 selection +if "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/B +CB = 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 3 +if "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() diff --git a/frozen/rsm_libero_freeze_20261002/awr.py b/frozen/rsm_libero_freeze_20261002/awr.py new file mode 100644 index 0000000000000000000000000000000000000000..9705795ffc6f20f9dd5453ff4f1125e3bd8c4bfa --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/awr.py @@ -0,0 +1,275 @@ +"""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 fit +on demonstrations only, so Q(demo action) ~= Q(actor's own action) and the mean +absolute advantage was 0.019 -- no gradient. Here half the corpus is failure, so +the advantage has real spread, and the weights are additionally corrected toward +pi 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 the +wrong policy -- the notes flag exactly this. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from model import BCHead, FlowPolicy +from data import LiberoRSMData +from 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() diff --git a/frozen/rsm_libero_freeze_20261002/bc_arm.py b/frozen/rsm_libero_freeze_20261002/bc_arm.py new file mode 100644 index 0000000000000000000000000000000000000000..7c9addae5d5a56d9f034ff8d930c9ac6842a4df0 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/bc_arm.py @@ -0,0 +1,153 @@ +"""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 are +independent 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 that +differs across the four arms is where the improvement signal comes from. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import train_bc, policy_features +from 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.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() diff --git a/frozen/rsm_libero_freeze_20261002/calib_dwm.py b/frozen/rsm_libero_freeze_20261002/calib_dwm.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3abd90f8d3b4bac3e6c247458a060886d34a7c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/calib_dwm.py @@ -0,0 +1,106 @@ +"""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 real +frames, z-scored tokens/proprio exactly as in training) and writes /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/ --ckpt runs//rsm/DWM/ckpt_best.pt [--max-frames 20000] +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json, time +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from dwm_model import TokenRSMData +from dwm_readout import load_critic_dwm +from 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() diff --git a/frozen/rsm_libero_freeze_20261002/capture_cpu.sbatch b/frozen/rsm_libero_freeze_20261002/capture_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7d98b3ed49ab26b28ed51ff90ba1e741f0b7f920 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/capture_cpu.sbatch @@ -0,0 +1,32 @@ +#!/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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export 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=osmesa +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export 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)" diff --git a/frozen/rsm_libero_freeze_20261002/capture_init_feats.py b/frozen/rsm_libero_freeze_20261002/capture_init_feats.py new file mode 100644 index 0000000000000000000000000000000000000000..8a352429f3a7af7d1c51d63db6e6cd8de788801e --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/capture_init_feats.py @@ -0,0 +1,88 @@ +"""Capture the evaluator's t=0 feature vector without rolling out. + +The question this answers: are the features the closed-loop evaluator actually +feeds the policy in the DEMO region of the cache or the ROLLOUT region? It decides +whether 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 are +required -- reset, one zero step, encode, done. Uses the SAME featurization path as +eval_closed_loop.py (to224 quantisation, axis-angle proprio, cache normalisation); +any deviation would make the comparison meaningless. +""" +from __future__ import annotations +import argparse, importlib.util, sys, os +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.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() diff --git a/frozen/rsm_libero_freeze_20261002/crn_diag.py b/frozen/rsm_libero_freeze_20261002/crn_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..dfb5f48d034ff6fea75e08af0b8c32fe050b50e7 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/crn_diag.py @@ -0,0 +1,58 @@ +"""Does the Q arg-max over N near-copy candidates track the critic or the Monte-Carlo +noise? Score the same N candidates twice with fresh seeds, with independent draws and +with common random numbers (crn), and report arg-max agreement and the ratio of +between-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, torch +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, make_policy +from 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 = None +if 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 on +eps = 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}") diff --git a/frozen/rsm_libero_freeze_20261002/data.py b/frozen/rsm_libero_freeze_20261002/data.py new file mode 100644 index 0000000000000000000000000000000000000000..725401e7a2f03153b8c2d67856015c225ec0914d --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/data.py @@ -0,0 +1,587 @@ +"""Batch sampling over the packed LIBERO-10 rollout cache.""" +from __future__ import annotations +from pathlib import Path +import 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 load +import numpy as np +import 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 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, + } diff --git a/frozen/rsm_libero_freeze_20261002/df_readout.py b/frozen/rsm_libero_freeze_20261002/df_readout.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc7a30629084d32f178a38881033f466e5ccb7c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/df_readout.py @@ -0,0 +1,228 @@ +"""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 thing +changed -- 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 reimplemented +here -- it is `df_value.value_of_candidates`, the same function the offline spread gate runs, so an +eval 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 the +same 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 it +needs 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 applied +inside 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 is +never told N, so drawing noise per row would give every candidate its own noise and make the argmax +partly a noise draw. This module therefore calls df_value with `crn_rows=True`: ONE noise draw per +Monte-Carlo index, shared by every row of the call. `crn_seed` from the planner selects it, so a +cell 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 json +import os +import sys +from pathlib import Path + +import numpy as np +import 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: F401 +except 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: E402 +from df_core import DFRise # noqa: E402 +from 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.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 crit diff --git a/frozen/rsm_libero_freeze_20261002/dinowm_readout.py b/frozen/rsm_libero_freeze_20261002/dinowm_readout.py new file mode 100644 index 0000000000000000000000000000000000000000..486d6eb2f5acdcc2707183f58e57fbad24a969c7 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/dinowm_readout.py @@ -0,0 +1,168 @@ +"""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 only +worth running if it differs from RSM/DWM in the MODEL and in nothing else. That is why this module +is 60 lines instead of 600: `DINOWMCritic` SUBCLASSES `dwm_readout.DWMCritic` and overrides exactly +two methods, the transition and the hop length. The fold algebra, the hop-policy chaining, the +reward head, the token normaliser, the temperature calibration and the two-stage rescore are the +same 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 transformer +that 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//tokens/tok.f16.npy is +[N, 514, 384] = 2 cameras x (CLS + 256 patches) from dinov2_vits14 at 224 px), and dwm_model.DWM is +already "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 queried +at 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 patch +tokens 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 ESTIMATOR +deterministic. Past the candidate chunk the continuation action comes from the stochastic Gaussian +hop head -- the same object RSM chains with -- so at depth > 1 the M particles are M different action +sequences and Q is the mean over them, with common random numbers across candidates (`_q_once` draws +eps per particle and tiles it over the rows). This module used to force n_particles = 1 at EVERY +depth, so all 855 published DINO-WM MPC cells requested 16 particles and measured one roll-out. Only +depth == 1 is truly deterministic and keeps the force. Search cost therefore scales with M and the +flagship discloses it; the effective count is in the cell's `planner.scorer.effective_particles` and +in 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 therefore +matched 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, which +is why its arm label in verdict_table is "L 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 json +from 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 crit diff --git a/frozen/rsm_libero_freeze_20261002/dwm_model.py b/frozen/rsm_libero_freeze_20261002/dwm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b40a26004ba1c4eb7459bca31439ed1ffe446d53 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/dwm_model.py @@ -0,0 +1,562 @@ +"""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 and +proprio 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, and +its own 9-d residual on the future side, read out by a 424->9 head). The MLP cells model the +pooled 1545-d state, which INCLUDES proprio, and the Stage-2 hop policy consumes the pooled +state of the sampled future, so the DWM successor has to predict proprio too. Cost: 2 tokens +out of 1030. + +No learned encoder: DINO is frozen and its tokens are the state (Stage 1 "no learned encoder +in either case"). +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import json +from pathlib import Path +import numpy as np +import torch +import torch.utils.checkpoint +import torch.nn as nn +import torch.nn.functional as F + +from model import beta_fourier, time_embed +from data import truncated_geometric_future + +# token layout of cache//tokens/tok.f16.npy [N, 514, 384] +N_PATCH = 256 +D_TOK = 384 +TOK_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.01 +Z_CLIP = 10.0 +RHO_FLOOR = 0.01 +Y_CLIP = 10.0 +STATS_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//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 /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 root diff --git a/frozen/rsm_libero_freeze_20261002/dwm_readout.py b/frozen/rsm_libero_freeze_20261002/dwm_readout.py new file mode 100644 index 0000000000000000000000000000000000000000..73ed820711fa7a32933ff5ed072d49283bb90d3d --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/dwm_readout.py @@ -0,0 +1,314 @@ +"""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//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//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_logit +q_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//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 4 +particles, rescores the top-16 by q_logit with 64 particles, returns full-length arrays. + +reward="goal_clf", reward_path="runs//goal_clf/clf.pt" (PRIVILEGED ABLATION: env success via state +replay, which RISE's baselines never see): the read-out reward is the standalone GOAL-STATE +classifier (train_goal_clf.py; env-success-by-replay label) on the pooled 1545-d state of every sampled future +instead 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 noise +tensor shared by all B rows (candidates), so Q differences between candidates at the same +state 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 annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +from pathlib import Path +import numpy as np +import 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= 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 /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)) diff --git a/frozen/rsm_libero_freeze_20261002/dwm_readout_timing.py b/frozen/rsm_libero_freeze_20261002/dwm_readout_timing.py new file mode 100644 index 0000000000000000000000000000000000000000..0ccaf606d13d147733aac7b7f1af917748464569 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/dwm_readout_timing.py @@ -0,0 +1,78 @@ +"""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 the +agreement between the rankings. Candidates: `--chunks hop` loads stream B's hop head (runs//hop/flow) if its +loader is importable, else (default `logged`) 128 logged chunks from 128 random frames of the val split -- the timing +does not depend on which chunks are used. Writes /readout_timing.json. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json, time +from pathlib import Path +import numpy as np +import torch + +from dwm_model import TokenRSMData +from 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() diff --git a/frozen/rsm_libero_freeze_20261002/encode_parquet.py b/frozen/rsm_libero_freeze_20261002/encode_parquet.py new file mode 100644 index 0000000000000000000000000000000000000000..82cc23b17d2ccc2841c2b58aac33eb066bc4a781 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/encode_parquet.py @@ -0,0 +1,83 @@ +"""Encode RLinf LeRobot parquet rollouts straight from their RECORDED frames into the +per-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 at +cam_res 256 and RLinf stores them upright, i.e. already in the evaluator's serving +orientation), 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_BASE +points at, so this is how a LIBERO-finetuned pi0.5 (lerobot/pi05_libero_base) becomes the +feature encoder for a new cache; the tag is recorded in every episode. + +usage: OGPO_PI05_BASE= encode_parquet.py --root --out + [--shard i --num-shards n] [--task-file lib10_tasks.txt] +Layout in: /task{t}_block{b}/rank_*/id_{i}/data/chunk-*/episode_{k:06d}.parquet +Layout out: //ep_t{t}_b{b}_i{i}_{k:06d}.npz (same as the existing corpus) +""" +from __future__ import annotations +import argparse, io, os, re, sys, glob, time +from pathlib import Path +import numpy as np +sys.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() diff --git a/frozen/rsm_libero_freeze_20261002/encode_t5.py b/frozen/rsm_libero_freeze_20261002/encode_t5.py new file mode 100644 index 0000000000000000000000000000000000000000..daffa4c3fea458ba1fb4305ad79f386e7fcc5114 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/encode_t5.py @@ -0,0 +1,52 @@ +"""Encode the ten LIBERO-10 instructions with T5 and cache the vectors. + +Replaces the learned nn.Embedding(n_task) conditioning. An index lookup carries no +information about WHAT the task is: it cannot transfer to a held-out instruction, and it +gives the network a free shortcut so nothing forces the visual latent to represent the +instruction. 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 does +from libero.libero import benchmark +b = 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, T5Tokenizer +tok = 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 named +import itertools +D = 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}") diff --git a/frozen/rsm_libero_freeze_20261002/encode_t5.sbatch b/frozen/rsm_libero_freeze_20261002/encode_t5.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..2831f345740df0507115747322b2ff02fd1b36e5 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/encode_t5.sbatch @@ -0,0 +1,16 @@ +#!/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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +export 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.npz diff --git a/frozen/rsm_libero_freeze_20261002/eval_closed_loop.py b/frozen/rsm_libero_freeze_20261002/eval_closed_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..278b28a32e077e551b36368a06b488f823f99e71 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/eval_closed_loop.py @@ -0,0 +1,1025 @@ +"""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 is +deliberate: the 0.584 +- 0.025 `bcdemos_m120k` bar was produced by +`09032026_latent_head_eval.py`, and a success rate measured by any other harness +is 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 in +either direction evaluates a good policy off-distribution and is +indistinguishable from the policy being bad, so the stats travel with the run +rather than being reconstructed here. +""" +from __future__ import annotations +import argparse, hashlib, importlib.util, json, os, sys +from pathlib import Path +import numpy as np +import 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, ConcatFlowPolicy +from 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 ") + 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 .partial.t 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 .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 .progress.t; 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() diff --git a/frozen/rsm_libero_freeze_20261002/eval_slurm.sbatch b/frozen/rsm_libero_freeze_20261002/eval_slurm.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..df5bb495a8fd02c30d28cebaf63eff4d6d31bc01 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/eval_slurm.sbatch @@ -0,0 +1,90 @@ +#!/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 pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +VENV=$B/venvs/rlinf-libero-eval-venv +PY=$VENV/bin/python + +export REPO_PATH=$B/external/rlinf +export PYTHONPATH="$REPO_PATH:${PYTHONPATH:-}" +export LIBERO_CONFIG_PATH=$S/libero_config +export ROBOT_PLATFORM=LIBERO +export LIBERO_TYPE=standard +export MUJOCO_GL=egl +export 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=false +export PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export HF_HUB_OFFLINE=1 +# the lane head sizes its task embedding from FL15_TASKS; harmless for our heads +export FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')" + +CRITIC=${CRITIC:-} # only needed when the policy reads latent features +POLICY=${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 $RC diff --git a/frozen/rsm_libero_freeze_20261002/extract_clips.py b/frozen/rsm_libero_freeze_20261002/extract_clips.py new file mode 100644 index 0000000000000000000000000000000000000000..49c7156358b664f2ac1e6561cd869e3cd9eb4a05 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/extract_clips.py @@ -0,0 +1,98 @@ +"""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 comparable +by eye. Demos come from the stock LIBERO hdf5 (agentview_rgb); rollouts from the source +corpus PNGs. +""" +import argparse, base64, io, json, os, re +import 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() diff --git a/frozen/rsm_libero_freeze_20261002/extract_viz.py b/frozen/rsm_libero_freeze_20261002/extract_viz.py new file mode 100644 index 0000000000000000000000000000000000000000..deaf3f38c9537b9919abfdcdbbe33d05b61d906c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/extract_viz.py @@ -0,0 +1,90 @@ +"""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, and +LIBERO's datasets/ dir is not installed), so frames are rollout-only. End-effector +trajectories come from proprio and exist for all three slices, which makes them the one +directly comparable view. +""" +import argparse, base64, io, json, os, re, sys +import 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() diff --git a/frozen/rsm_libero_freeze_20261002/ibm_autoresearch.sh b/frozen/rsm_libero_freeze_20261002/ibm_autoresearch.sh new file mode 100644 index 0000000000000000000000000000000000000000..1686be6ff31b2f1ea9b0d36062de34ecddad992c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/ibm_autoresearch.sh @@ -0,0 +1,53 @@ +#!/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 __s7e7_V. +# usage: ibm_autoresearch.sh train | stage1 | bcsel | stage2 | stage3 [prop] [policy] [hop] +set -uo pipefail +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; CACHE=$IB/cache/full_r256 +S="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.pt +V="SEED=7, QFCRN=1, QFPART=${QFPART:-256}"; VN=20 +sub(){ echo "$(NINIT=$VN ./ibm_cell.sh "$1" "$2" 7 1 "$3" &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:?}" in +train) # 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 | 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=${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: 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" "" +# 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 .json. Wall-clock per cell drops ~10x. +set -uo pipefail +NAME=${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/logs +Q=${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_ONLY +printf '%s' \"$COMMON\" > $E/$NAME.cell # manifest: the env this cell was submitted with (retries read it) +[ \"\${MANIFEST_ONLY:-0}\" = 1 ] && exit 0 +for 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>&1 +done +bsub -G $G -q $Q -n 4 -M 32G -J ${NAME}_asm -o $L/${NAME}_asm.out -e $L/${NAME}_asm.err -env \"$COMMON, ASM=1\" $IB/code/ibm_eval.sh 2>&1 | grep -o '<[0-9]*>' +" &1 | grep -v Authorized | tr -d '<>' diff --git a/frozen/rsm_libero_freeze_20261002/ibm_crn_diag.sh b/frozen/rsm_libero_freeze_20261002/ibm_crn_diag.sh new file mode 100644 index 0000000000000000000000000000000000000000..3673365859d935fa2a4881daebb02446a8e310f0 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/ibm_crn_diag.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# CRN diagnostic on IBM: no env, one GPU. Reuses ibm_eval.sh's environment block. +set -uo pipefail +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256 +PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python +export RSM_TASKS_FILE=$IB/lib10_tasks.txt RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktree +export OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorch +export OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.model +export LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard MUJOCO_GL=egl PYOPENGL_PLATFORM=egl +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1 +export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/" +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}" diff --git a/frozen/rsm_libero_freeze_20261002/ibm_eval.sh b/frozen/rsm_libero_freeze_20261002/ibm_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff827ea2ff7e6a2227efae3e15242f94913875f6 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/ibm_eval.sh @@ -0,0 +1,51 @@ +#!/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 pipefail +IB=/proj/dmfexp/zwhong/rsm_libero +export RSM_TASKS_FILE=/proj/dmfexp/zwhong/rsm_libero/lib10_tasks.txt +export RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktree +export OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorch +export OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.model +export LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export 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 here +export RSM_NO_ENV_CLOSE=1 +export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/" +PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python +TASKS=${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 .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 0 +fi +RETRY=${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.sh +fi +exit $RC diff --git a/frozen/rsm_libero_freeze_20261002/ibm_eval_depth.sh b/frozen/rsm_libero_freeze_20261002/ibm_eval_depth.sh new file mode 100644 index 0000000000000000000000000000000000000000..8538e9e112ae5a851875c3f484f1863365aa29d9 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/ibm_eval_depth.sh @@ -0,0 +1,7 @@ +#!/bin/bash +# beta-hop sweep cells only. usage: ibm_eval_depth.sh [seeds] [depths] +set -uo pipefail +PROPRUN=${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/logs +S="ssh -o BatchMode=yes -o ConnectTimeout=20" +sub(){ ./ibm_cell.sh "$1" "$2" "$3" "$4" "$5"; } \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/ibm_eval_matrix.sh b/frozen/rsm_libero_freeze_20261002/ibm_eval_matrix.sh new file mode 100644 index 0000000000000000000000000000000000000000..e6815716a8c82bd8babf545b55f70ea555edf398 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/ibm_eval_matrix.sh @@ -0,0 +1,25 @@ +#!/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 [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 ladder +set -uo pipefail +PROPRUN=${1:?proposer run dir}; TAG=${2:?tag}; SEEDS=${3:-0}; HOPRUN=${4:-} # 4th arg: latent hop policy run dir -> depth 2/3 cells +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logs +S="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; done +for 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" +done diff --git a/frozen/rsm_libero_freeze_20261002/ibm_eval_matrix_last.sh b/frozen/rsm_libero_freeze_20261002/ibm_eval_matrix_last.sh new file mode 100644 index 0000000000000000000000000000000000000000..64f816fb0862ade1651f8bc819b8c82a7fabb13d --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/ibm_eval_matrix_last.sh @@ -0,0 +1,38 @@ +#!/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 pipefail +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256 +PROPL=$R/BCdemo_f/policy_last.pt; HOP=$R/HOPdemo_f/policy_r1.pt +CB=$R/qsg_f/ckpt_best.pt; CL=$R/qsg_f/ckpt.pt +BON="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" 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 pipefail +PH=${1:?phase} +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +S="ssh -o BatchMode=yes -o ConnectTimeout=20" +IB=/proj/dmfexp/zwhong/rsm_libero; ID=/proj/dmfexp/zwhong/data +CACHE=$IB/cache/full_r256; RUNS=$IB/runs/full_r256; LOGS=$RUNS/logs +PYT=/proj/dmfexp/zwhong/venvs/lerobot_env/bin/python +MIT_META=/data/pulkitag/users/rli14/rsm_libero_cache/full_r256 +case $PH in +sync-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_f +BCroll_f|$BC --pool rollsucc --out $RUNS/BCroll_f" + MASKED="BCrollv_f|$BC --pool rollsucc --success-mask $MASK --out $RUNS/BCrollv_f +BCsucc_f|$BC --pool succ --success-mask $MASK --out $RUNS/BCsucc_f +qind_f|$CR --reward-mode subgoal_ind --subgoal-dir $SG --success-mask $MASK --out $RUNS/qind_f +qsg_f|$CR --reward-mode subgoal --subgoal-dir $SG --success-mask $MASK --out $RUNS/qsg_f" + [ "$PH" = train-nomask ] && LIST="$NOMASK" || LIST="$MASKED" + # /dev/null | xargs -n1 basename | sed 's/.json$//'" /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; echo "manifest $1"; return; fi + echo "$have" | grep -qx "$1" && return + echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" .cell) written at submission. Idempotent; run repeatedly. +set -uo pipefail +ssh -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=0 +active=$(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>&1 +done; echo "resubmitted $n task jobs"' diff --git a/frozen/rsm_libero_freeze_20261002/ibm_table.py b/frozen/rsm_libero_freeze_20261002/ibm_table.py new file mode 100644 index 0000000000000000000000000000000000000000..6d75bc360954a9a72b5b2e97da025dfe9806782f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/ibm_table.py @@ -0,0 +1,70 @@ +"""Assemble the RSM-vs-baselines table from IBM eval JSONs, with PAIRED tests. + +Cells are named __s[e]_. Two cells with the same +proposer, pseed/evalseed and protocol share initial conditions (init_sha256 per episode), +so arm differences are paired: McNemar exact test on discordant episodes, plus the paired +throughput 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, sys +from collections import defaultdict +from 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() diff --git a/frozen/rsm_libero_freeze_20261002/ibm_train_onpol.sh b/frozen/rsm_libero_freeze_20261002/ibm_train_onpol.sh new file mode 100644 index 0000000000000000000000000000000000000000..279fc81ee5a1dce4b6ec7a037f310f96568aa0eb --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/ibm_train_onpol.sh @@ -0,0 +1,15 @@ +#!/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 pipefail +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256 +PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python +export PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1 +export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/" +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:?}" diff --git a/frozen/rsm_libero_freeze_20261002/iql.py b/frozen/rsm_libero_freeze_20261002/iql.py new file mode 100644 index 0000000000000000000000000000000000000000..fe469a03b5cdb80951551a8f0b59a8e910b28edd --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/iql.py @@ -0,0 +1,259 @@ +"""IQL critic + policy extraction, as the standard offline-RL baseline for RSM. + +Matched to the RSM arms on purpose: same latents, same reward labels, same +FlowPolicy class, same AWR extraction, same offline score. The ONLY thing that +differs is where the advantage comes from -- IQL's expectile-regressed Q - V +versus RSM's occupancy read-out. That is what makes the comparison a test of the +critic 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 method +gets a reward the other does not see. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from model import Encoder, mlp, FlowPolicy +from data import LiberoRSMData +from is_ope import make_policy, policy_nll, train_bc, policy_features +from 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() diff --git a/frozen/rsm_libero_freeze_20261002/is_ope.py b/frozen/rsm_libero_freeze_20261002/is_ope.py new file mode 100644 index 0000000000000000000000000000000000000000..19669c6e2149659a8f181413ecee924968f24348 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/is_ope.py @@ -0,0 +1,727 @@ +"""Importance-sampled off-policy evaluation of Q^pi with the RSM occupancy. + +Implements the notes' Sections 7-9 without ever needing a normalized action +density, which matters because the behavior policy here is a pi0.5 flow model +sampled 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 whose +occupancy we can compute directly. Take pi := "mu restricted to episodes that +succeed". d^pi is then estimable by fitting the occupancy on successes only, +while the IS estimate reweights the all-data model. If the corrected estimate +does not move toward the success-only reference, the weights are not working and +no policy is trained on them. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json, time +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from types import SimpleNamespace + +from model import (Encoder, RewardHead, OccFlow, RatioNet, EndpointRatio, + BCHead, FlowPolicy) +from data import LiberoRSMData +from 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} diff --git a/frozen/rsm_libero_freeze_20261002/label_full.sbatch b/frozen/rsm_libero_freeze_20261002/label_full.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..bb83d02365a8d65ee13748d92bb2c2c8013aff8f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/label_full.sbatch @@ -0,0 +1,20 @@ +#!/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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +T=$((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 diff --git a/frozen/rsm_libero_freeze_20261002/label_subgoals.py b/frozen/rsm_libero_freeze_20261002/label_subgoals.py new file mode 100644 index 0000000000000000000000000000000000000000..4d1ca82f4b3e449c56ea613ce064715a1945e400 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/label_subgoals.py @@ -0,0 +1,91 @@ +"""Per-frame satisfied-subgoal count: a reward that IS a function of state. + +gamma_s**(frames-to-success) is not a function of the state -- it depends on the +episode's outcome and the frame index, so identical configurations carry targets +differing by ~1.4 sigma of the reward range (measured). A regressor fit to it can only +recover P(success|z). + +Each LIBERO goal is a conjunction of BDDL predicates over object geometry. Evaluating +them per frame gives r(s) = (#conjuncts satisfied)/K: deterministic in the state, +identical for identical states, and defined for EVERY frame of EVERY episode including +failures -- which today contribute only zeros. + +Emits per-episode arrays aligned to the cache's frame index. +""" +import argparse, os, re, sys +import numpy as np +sys.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("--shard", type=int, default=0); ap.add_argument("--num-shards", type=int, default=1) + ap.add_argument("--stride", type=int, default=5, + help="evaluate every Nth frame and hold; subgoal count is piecewise " + "constant and changes a handful of times per episode") + 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) + task, lo, hi = m["ep_task"], m["ep_from"], m["ep_to"] + demo = m["ep_demo"].astype(bool) + todo = np.where((task == args.task) & ~demo)[0] # rollouts; demos have no parquet + todo = todo[args.shard::args.num_shards] # within-task sharding for the full corpus + b = benchmark.get_benchmark_dict()["libero_10"]() + t = b.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"] + K = len(goal) + print(f"[label] task {args.task}: {len(todo)} rollouts, K={K} conjuncts {goal}", flush=True) + + eps, vals = [], [] + for n, e in enumerate(todo): + p = src_parquet(m["ep_src"][e]) + nfr = int(hi[e] - lo[e]) + if p is None: + eps.append(int(e)); vals.append(np.full(nfr, -1, np.int8)); continue + tb = pq.read_table(p, columns=["sim_state"]) + N = min(tb.num_rows, nfr) + out = np.zeros(nfr, np.int8) + last = 0 + for i in range(0, N, args.stride): + st = np.asarray(tb["sim_state"][i].as_py(), np.float64) + env.env.sim.set_state_from_flattened(st); env.env.sim.forward() + last = sum(bool(env.env._eval_predicate(g)) for g in goal) + out[i:min(i + args.stride, nfr)] = last + if N < nfr: out[N:] = last + eps.append(int(e)); vals.append(out) + if (n + 1) % 100 == 0: + f = np.concatenate(vals) + print(f"[label] {n+1}/{len(todo)} mean subgoals {f[f>=0].mean():.3f}", flush=True) + env.close() + np.savez_compressed(args.out, ep=np.array(eps), + vals=np.array(vals, dtype=object), K=K, task=args.task) + f = np.concatenate(vals); f = f[f >= 0] + print(f"[label] task {args.task} DONE: {len(eps)} eps, mean subgoals " + f"{f.mean():.3f}/{K}, frames at 0/1/2 = " + f"{np.bincount(f, minlength=K+1).tolist()}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/label_subgoals.sbatch b/frozen/rsm_libero_freeze_20261002/label_subgoals.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..a8c493c9b91e9ce5f1acb9b98296cd1ad11e326f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/label_subgoals.sbatch @@ -0,0 +1,17 @@ +#!/bin/bash +#SBATCH --job-name=label_sub +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +OUT=/data/pulkitag/users/rli14/rsm_libero_runs/subgoals; 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/users/rli14/rsm_libero_cache/full_demo \ + --task $SLURM_ARRAY_TASK_ID --out $OUT/task$SLURM_ARRAY_TASK_ID.npz --stride 5 diff --git a/frozen/rsm_libero_freeze_20261002/lane_control.sbatch b/frozen/rsm_libero_freeze_20261002/lane_control.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..6e27aca6de89d6d047e29472a687039215370393 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/lane_control.sbatch @@ -0,0 +1,36 @@ +#!/bin/bash +#SBATCH --job-name=lane_ctl +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=64G +#SBATCH --time=12: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 +# CONTROL: the lane's OWN bcdemos policy through the lane's OWN evaluator on THIS +# machine. If it reproduces ~0.584 the env, EGL, encoder and init states here are +# sound and any 0% we see is our training's fault. If it does not, the harness is. +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +W=$B/.claude/worktrees/08312026_jvq_recap_worktree/scripts/rlinf_jvq +PY=$B/venvs/rlinf-libero-eval-venv/bin/python +export REPO_PATH=$B/external/rlinf +export PYTHONPATH="$REPO_PATH:${PYTHONPATH:-}" +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export 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 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +# The head's task embedding is sized by FL15_TASKS. It defaults to the 15-task +# libero_90 list, which cannot load a 10-task libero_10 checkpoint. +export FL15_TASKS="$(tr '\n' ',' < /data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')" +echo "[ctl] FL15_TASKS has $(echo "$FL15_TASKS" | tr ',' '\n' | grep -c .) tasks" +$PY $W/09032026_latent_head_eval.py \ + --ckpt /data/pulkitag/users/rli14/laneP_bc_v1/bcdemos_h1024d4.best.pt \ + --norm /data/pulkitag/users/rli14/laneP_bc_v1/bcdemos_h1024d4.norm.npz \ + --suite libero_10 --tasks 0,1,2,3,4,5,6,7,8,9 --n-init 10 \ + --max-steps 520 --execute 10 --seed 0 \ + --out /data/pulkitag/users/rli14/rsm_libero_runs/lane_control2/LANE_CONTROL.json +echo "[ctl] rc=$?" diff --git a/frozen/rsm_libero_freeze_20261002/launch_full_r256.sh b/frozen/rsm_libero_freeze_20261002/launch_full_r256.sh new file mode 100644 index 0000000000000000000000000000000000000000..d08174658b91a411416d8df2a04ec1ed2059690f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/launch_full_r256.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# The full-corpus, one-latent-space wave (williamd4112/gen_q#252). Submits a slurm DAG: +# pack -> stats -> {BC-demos, BC-rollsucc} -> n=500 evals A/B +# pack -> {label x40, verify x40} -> mask -> {BC-succ, BC-rollsucc-masked, critics ind/sg} -> evals +# critic qind_f -> IQL (q-only, same frozen encoder) -> BoN8 evals +# BC-demos + critics/IQL -> best-of-8 argmax / random / medoid, 3 policy seeds +# Every training job is --requeue + --resume; every eval is --requeue. No --export anywhere +# (tig-cpu kills exported jobs); values ride in the environment. +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +SR=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation/launchers/slurm_remote.sh +GPUP=vision-pulkitag-h200,vision-pulkitag-a100,vision-pulkitag-l40s,vision-pulkitag-a6000 +MEMP=vision-pulkitag-l40s,vision-pulkitag-a100,vision-pulkitag-h200 +Q=vision-pulkitag-free-cycles +CACHE=/data/pulkitag/users/rli14/rsm_libero_cache/full_r256 +RUNS=/data/pulkitag/users/rli14/rsm_libero_runs/mit; O=/data/pulkitag/users/rli14/rsm_libero_runs/eval +SG=/data/pulkitag/users/rli14/rsm_libero_runs/subgoals_full +MASK=/data/pulkitag/users/rli14/rsm_libero_runs/verify_full/verified_mask.npz +LEDGER=$O/launch_full_r256.ledger; : > $LEDGER +sub(){ local id; id=$($SR exec "cd $G && $1" 2>&1 | grep -o "Submitted batch job [0-9]*" | grep -o "[0-9]*$"); echo "$id $2" >> $LEDGER; echo "$id"; } + +# ---- data ---- +J_PACK=$(sub "sbatch --qos=$Q --partition=$MEMP $G/pack_full_r256.sbatch" pack_full_r256) +J_STATS=$(sub "sbatch --dependency=afterok:$J_PACK --qos=$Q --partition=$MEMP $G/stats_full.sbatch" stats_full) +J_LAB=$(sub "sbatch --dependency=afterok:$J_PACK $G/label_full.sbatch" label_full_x40) +J_VER=$(sub "sbatch --dependency=afterok:$J_PACK $G/verify_full.sbatch" verify_full_x40) +J_MASK=$(sub "sbatch --dependency=afterok:$J_LAB:$J_VER $G/merge_full.sbatch" merge_full) + +# ---- trainers ---- +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" +train(){ sub "CMD='$2' sbatch --job-name=$1 --dependency=afterok:$3 --qos=$Q --partition=$GPUP --requeue --time=20:00:00 $G/train_slurm.sbatch" "train $1"; } +J_BCD=$(train BCd_f "$BC --pool demos --out $RUNS/BCd_f" $J_STATS) +J_BCR=$(train BCroll_f "$BC --pool rollsucc --out $RUNS/BCroll_f" $J_STATS) +J_BCRV=$(train BCrollv_f "$BC --pool rollsucc --success-mask $MASK --out $RUNS/BCrollv_f" $J_STATS:$J_MASK) +J_BCS=$(train BCsucc_f "$BC --pool succ --success-mask $MASK --out $RUNS/BCsucc_f" $J_STATS:$J_MASK) +J_QI=$(train qind_f "$CR --reward-mode subgoal_ind --subgoal-dir $SG --success-mask $MASK --out $RUNS/qind_f" $J_STATS:$J_MASK) +J_QS=$(train qsg_f "$CR --reward-mode subgoal --subgoal-dir $SG --success-mask $MASK --out $RUNS/qsg_f" $J_STATS:$J_MASK) +IQ="iql.py --cache $CACHE --critic $RUNS/qind_f/ckpt_best.pt --out $RUNS/iql_f --chunk 10 --norm-pool demos --feat-scale center --policy-features raw --reward-mode subgoal_ind --subgoal-dir $SG --success-mask $MASK --tau 0.7 --gamma 0.99 --iql-steps 60000 --q-only 1 --in-ram 1 --seed 0" +J_IQL=$(train iql_f "$IQ" $J_QI) # same encoder as the RSM arm: only the source of Q differs + +# ---- evals: n=500, protocols A and B, evaluator at 256 ---- +ev(){ # name dep policy extra-env pseed + for P in A B; do F=0; [ $P = B ] && F=1 + sub "POLICY=$3 CAMRES=256 FRESH=$F NINIT=50 PSEED=$5 $4 OUT=$O/F_${1}_s$5_$P.json sbatch --job-name=e${1}$5$P --dependency=afterok:$2 --qos=$Q --partition=$GPUP --requeue --time=10:00:00 $G/eval_slurm.sbatch" "eval $1 seed$5 $P" >/dev/null + done; } +PROP=$RUNS/BCd_f/policy_r1.pt +for s in 0 1 2; do ev BCd $J_BCD $PROP "" $s; done +ev BCroll $J_BCR $RUNS/BCroll_f/policy_r1.pt "" 0 +ev BCrollv $J_BCRV $RUNS/BCrollv_f/policy_r1.pt "" 0 +ev BCsucc $J_BCS $RUNS/BCsucc_f/policy_r1.pt "" 0 +BON="QFILTER=8 QFBETA=0.98 QFDEPTH=1 QFPES=0 QFGATE=0" +for s in 0 1 2; do + ev RSMind_bon8 $J_BCD:$J_QI $PROP "CRITIC=$RUNS/qind_f/ckpt_best.pt $BON SELECT=argmaxq" $s + ev IQL_bon8 $J_BCD:$J_IQL $PROP "QFCKPT=$RUNS/iql_f/iql_q.pt $BON SELECT=argmaxq" $s + ev medoid8 $J_BCD $PROP "$BON SELECT=medoid" $s +done +ev RSMsg_bon8 $J_BCD:$J_QS $PROP "CRITIC=$RUNS/qsg_f/ckpt_best.pt $BON SELECT=argmaxq" 0 +ev random8 $J_BCD $PROP "$BON SELECT=random" 0 +echo "ledger: $LEDGER"; cat $LEDGER diff --git a/frozen/rsm_libero_freeze_20261002/lewm_data.py b/frozen/rsm_libero_freeze_20261002/lewm_data.py new file mode 100644 index 0000000000000000000000000000000000000000..29b2d0aff3cb14782451244266a0903bfaaddab1 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/lewm_data.py @@ -0,0 +1,177 @@ +"""Streaming frame windows for LeWM (gen_q#268) -- no image pack, by hard constraint. + +/proj/dmfexp runs at 99% full (5.6 T free of 350 T, and rsm_rise's own runs/ is 5.6 T), so an 84x84 +two-camera image pack of all seven tasks (~29 GB) is not something this lane may write. LeWM needs +pixels -- it is a JEPA that predicts its OWN encoder's embeddings, so feeding it frozen DINO features +would turn it into DINO-WM -- therefore the frames are streamed out of the task's source HDF5 at +training time instead. + +WHY AN EPISODE-RESIDENT BUFFER AND NOT RANDOM READS. A batch of 128 windows of 4 frames x 2 cameras +is 1024 separate 21 kB HDF5 reads; over this filesystem that is seconds per step and 100k steps is +out of reach. Whole episodes are contiguous, so the loader keeps `resident` episodes in RAM (each is +~300 frames x 2 cams x 21 kB = 13 MB, so 96 episodes is ~1.2 GB), draws every window from those, and +retires one episode every `refresh_every` steps. The buffer therefore turns over completely every +`resident * refresh_every` steps -- 768 at the defaults, i.e. ~130 full passes over a 100k-step run. + +ALIGNMENT. Frames come from the HDF5 but ACTIONS and the reward LABEL come from the packed cache, so +LeWM reads the same actions and the same provenance label as every other scorer in the table: + * cache//meta.npz ep_from/ep_to/ep_len/ep_src/ep_success (ep_src = the HDF5 demo key) + * cache//act.f32.npy (stride 1, cache row order) + * the label is ep_success, which is exactly what train_rsm.py --reward-mode dense turns into r=1 + on every frame of an expert episode -- the membership head's label. +The cache was packed from this HDF5 at stride 1 (PACK.json), so cache row ep_from[e]+j is frame j of +demo ep_src[e]; the constructor asserts that for every episode it loads. + +The episode split is the same permutation LiberoRSMData(seed=seed) uses, so LeWM's validation +episodes are the ones every other scorer held out. +""" +from __future__ import annotations + +import json +from collections import OrderedDict +from pathlib import Path + +import numpy as np +import torch + +CAMS = ("agentview_image", "robot0_eye_in_hand_image") + + +class StreamingFrameData: + def __init__(self, cache, hdf5="", chunk: int = 8, ctx: int = 3, n_preds: int = 1, + resident: int = 96, refresh_every: int = 8, val_frac: float = 0.1, + seed: int = 0, cams=CAMS, res: int = 84): + import h5py # imported here: the scorer never needs it + self.h5py = h5py + self.root = Path(cache) + m = np.load(self.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_success = m["ep_success"].astype(bool) + assert "ep_src" in m.files, f"{cache}/meta.npz has no ep_src: cannot map frames to the HDF5" + self.ep_src = [str(s) for s in m["ep_src"]] + self.adim = int(m["adim"]) + self.n_ep = len(self.ep_len) + self.act = np.ascontiguousarray(np.load(self.root / "act.f32.npy", mmap_mode="r")) + self.chunk, self.ctx, self.n_preds = chunk, ctx, n_preds + self.T = ctx + n_preds + self.cams, self.res = tuple(cams), res + self.d_act = chunk * self.adim + if not hdf5: + hdf5 = json.loads((self.root / "PACK.json").read_text())["src"] + self.hdf5 = str(hdf5) + self.f = h5py.File(self.hdf5, "r") + + 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:]) + # only episodes long enough to hold one window are usable + ok = self.ep_len >= self.T + self.train_eps = np.array([e for e in self.train_eps if ok[e]], np.int64) + self.val_eps = np.array([e for e in self.val_eps if ok[e]], np.int64) + self.resident, self.refresh_every = int(resident), int(refresh_every) + self.buf = {"train": OrderedDict(), "val": OrderedDict()} + self._n_draw = 0 + print(f"[lewm_data] {self.n_ep} eps ({len(self.train_eps)} train / {len(self.val_eps)} val), " + f"label positives {self.ep_success.mean():.4f}, frames from {self.hdf5}", flush=True) + + # ---- episode I/O --------------------------------------------------------------------------- + def _load_ep(self, e): + """[T, 2, res, res, 3] uint8 for one episode, read whole (contiguous in the HDF5).""" + g = self.f["data"][self.ep_src[e]]["obs"] + arrs = [] + for c in self.cams: + a = np.asarray(g[c][:]) + arrs.append(a) + n = int(self.ep_to[e] - self.ep_from[e]) + assert arrs[0].shape[0] == n, (f"episode {self.ep_src[e]}: HDF5 has {arrs[0].shape[0]} frames, " + f"cache has {n} -- the row map would be wrong") + assert arrs[0].shape[1:3] == (self.res, self.res), \ + f"{self.cams[0]} is {arrs[0].shape[1:3]}, expected {(self.res, self.res)}" + return np.stack(arrs, 1) + + def _ensure(self, split, rng): + pool = self.train_eps if split == "train" else self.val_eps + buf = self.buf[split] + want = self.resident if split == "train" else min(self.resident, max(8, len(pool))) + while len(buf) < want: + cand = [int(e) for e in pool if int(e) not in buf] + if not cand: + break + e = int(rng.choice(cand)) + buf[e] = self._load_ep(e) + # retire the oldest and pull one new episode in, so the buffer keeps turning over + if split == "train" and self.refresh_every > 0 and self._n_draw % self.refresh_every == 0 \ + and len(pool) > len(buf): + buf.popitem(last=False) + cand = [int(e) for e in pool if int(e) not in buf] + if cand: + e = int(rng.choice(cand)) + buf[e] = self._load_ep(e) + + # ---- windows ------------------------------------------------------------------------------- + def _chunk_at(self, t, e): + """the flattened `chunk`-step action window at cache row t, padded by repeating the last.""" + hi = int(self.ep_to[e]) + take = min(self.chunk, hi - t) + a = np.asarray(self.act[t:t + take], np.float32) + if take < self.chunk: + a = np.concatenate([a, np.repeat(a[-1:], self.chunk - take, 0)], 0) + return a.reshape(-1) + + def sample(self, batch, rng, split="train", device="cpu"): + """-> frames [B,T,6,res,res] uint8, actions [B,T,d_act], label [B], plus bookkeeping.""" + self._n_draw += 1 + self._ensure(split, rng) + buf = self.buf[split] + eps = np.array(list(buf.keys()), np.int64) + w = (self.ep_len[eps] - self.T + 1).astype(np.float64) + w = np.maximum(w, 1.0) + w /= w.sum() + pick = rng.choice(len(eps), size=batch, p=w) + fr = np.empty((batch, self.T, 2, self.res, self.res, 3), np.uint8) + ac = np.empty((batch, self.T, self.d_act), np.float32) + lab = np.empty(batch, np.float32) + for j, pi in enumerate(pick): + e = int(eps[pi]) + n = int(self.ep_len[e]) + j0 = int(rng.integers(0, max(n - self.T + 1, 1))) + fr[j] = buf[e][j0:j0 + self.T] if n >= self.T else \ + np.concatenate([buf[e], np.repeat(buf[e][-1:], self.T - n, 0)], 0)[:self.T] + base = int(self.ep_from[e]) + j0 + for i in range(self.T): + ac[j, i] = self._chunk_at(min(base + i, int(self.ep_to[e]) - 1), e) + lab[j] = float(self.ep_success[e]) + # [B,T,2,H,W,3] -> [B,T,6,H,W]: the two cameras become channels (declared deviation 1) + f6 = torch.from_numpy(fr).permute(0, 1, 2, 5, 3, 4).reshape(batch, self.T, 6, self.res, self.res) + return {"frames": f6.to(device, non_blocking=True), + "actions": torch.from_numpy(ac).to(device, non_blocking=True), + "label": torch.from_numpy(lab).to(device, non_blocking=True)} + + def close(self): + try: + self.f.close() + except Exception: + pass + + +def frames_from_obs(obs_t, cams=CAMS, res=84): + """The scorer's side of the SAME transform: the planner's obs dict -> [B,6,res,res] uint8. + + The planner hands float CHW images in [0,1] (robomimic ObsUtils.process_frame); LeWM's encoder + expects raw uint8 because it does the /127.5 - 1 itself, so the round trip back to uint8 here is + what makes scoring see the same inputs training did. + """ + out = [] + for c in cams: + x = obs_t[c] + x = torch.as_tensor(x) + if x.ndim == 4 and x.shape[-1] == 3: # NHWC -> NCHW + x = x.permute(0, 3, 1, 2) + if x.dtype.is_floating_point: + x = (x.clamp(0, 1) * 255.0).round().to(torch.uint8) + out.append(x) + return torch.cat(out, 1) diff --git a/frozen/rsm_libero_freeze_20261002/lewm_model.py b/frozen/rsm_libero_freeze_20261002/lewm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..67b705107fcaab82afd76e8047365f186760b45d --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/lewm_model.py @@ -0,0 +1,237 @@ +"""LeWorldModel (LeWM), ported to torch from the JAX reference for gen_q#268. + +Reference implementation: /proj/dmfexp/zwhong/projs/wt-i97-beta/rsm_vla/lewm.py (flax) and its +`rsm_vla/models.py:Encoder`. This is a line-for-line port of the *method*: JEPA next-embedding +prediction with an AdaLN-zero causal predictor, collapse prevented by SIGReg alone -- NO +stop-gradient and NO EMA target encoder, which is the recipe's defining choice and the easiest thing +to "fix" by accident into a different method. Every constant below is the reference's: + + CTX = 3 history frames the predictor conditions on + N_PREDS = 1 next-step target only + LAMBDA = 0.09 SIGReg weight + LR = 5e-5, WD = 1e-3, global-norm clip 1.0 (AdamW) + LEWM_SIZES (emb_dim, depth, heads, mlp_dim); "m" is the official ~15M config + +WHY A PORT AND NOT THE ORIGINAL. The reference is JAX/flax; rsm_rise's venv has torch only (no +jax), and the reference's shell runners point at a clone that no longer exists on this filesystem. +The port therefore has to be checked rather than trusted: tests/test_lewm_port.py asserts the SIGReg +statistic against an independent numpy implementation and asserts the AdaLN-zero block is the +identity at initialisation (which is what "zero" means and what makes the recipe trainable). + +DECLARED DEVIATIONS from the reference, all forced by the rsm_rise observation and protocol: + 1. INPUT is 84x84 with SIX channels -- the two RISE cameras (agentview, wrist) stacked -- not one + 64x64 RGB frame. The encoder is resolution-general (stride-2 stages until the spatial size is + <= 4), so 84px needs 5 stages where 64px needs 4; nothing else changes. + 2. ACTIONS are the 8-step chunk the RISE actor emits, flattened, not a single step: that is the + candidate the planner ranks, so it is what the world model has to be conditioned on. + 3. The reward probe is a SINGLE-argument probe on the predicted embedding, trained by BCE on the + provenance/membership label, rather than the reference's (z, z_goal) pair probe. gen_q#268 + fixes the reward for every scorer to that label, and a goal-conditioned probe would be reading a + different reward than RSM, TD-Flow and DINO-WM do. +""" +from __future__ import annotations + +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F + +CTX = 3 +N_PREDS = 1 +LAMBDA = 0.09 +LR = 5e-5 +WD = 1e-3 +CLIP = 1.0 +PROBE_LR = 3e-4 +# (emb_dim, depth, heads, mlp_dim) +LEWM_SIZES = {"s": (128, 4, 8, 1024), "m": (192, 6, 16, 2048), "l": (384, 8, 16, 3072)} + + +class Encoder(nn.Module): + """uint8 image -> z_dim latent. Resolution-general: stride-2 stages until spatial <= 4. + + Port note: the reference divides by 127.5 and subtracts 1 INSIDE the encoder, so the caller + hands it raw uint8. Keeping that boundary here means the scorer can feed the planner's frames + through the identical transform the trainer used. + """ + + CHANS = (32, 64, 128, 256, 512, 512, 512) + + def __init__(self, z_dim=192, in_ch=6, res=84): + super().__init__() + layers, c_in, s = [], in_ch, res + i = 0 + while s > 4: + c_out = self.CHANS[min(i, len(self.CHANS) - 1)] + layers += [nn.Conv2d(c_in, c_out, 3, stride=2, padding=1), + nn.GroupNorm(8, c_out), nn.SiLU()] + c_in, s, i = c_out, (s + 1) // 2, i + 1 + self.conv = nn.Sequential(*layers) + self.flat = c_in * s * s + self.fc1 = nn.Linear(self.flat, 512) + self.fc2 = nn.Linear(512, z_dim) + self.n_stages, self.out_res = i, s + + def forward(self, img_u8): + x = img_u8.float() / 127.5 - 1.0 + x = self.conv(x).flatten(1) + return self.fc2(F.silu(self.fc1(x))) + + +class ProjMLP(nn.Module): + """Dense(hidden) -> LayerNorm -> gelu -> Dense(out_dim), as in the reference.""" + + def __init__(self, in_dim, out_dim, hidden=2048): + super().__init__() + self.l1 = nn.Linear(in_dim, hidden) + self.ln = nn.LayerNorm(hidden) + self.l2 = nn.Linear(hidden, out_dim) + + def forward(self, x): + return self.l2(F.gelu(self.ln(self.l1(x)))) + + +class ActionEmbedder(nn.Module): + """Dense(A) -> Dense(4*emb) -> silu -> Dense(emb), applied per time step.""" + + def __init__(self, a_dim, emb_dim, mlp_scale=4): + super().__init__() + self.l0 = nn.Linear(a_dim, a_dim) + self.l1 = nn.Linear(a_dim, mlp_scale * emb_dim) + self.l2 = nn.Linear(mlp_scale * emb_dim, emb_dim) + + def forward(self, a): + return self.l2(F.silu(self.l1(self.l0(a)))) + + +def modulate(x, shift, scale): + return x * (1.0 + scale) + shift + + +class AdaLNBlock(nn.Module): + """One AdaLN-zero transformer block: the conditioning head is zero-initialised, so the block is + the IDENTITY at initialisation and the predictor starts as a pass-through of the embedding. + That is what makes this recipe trainable without a target network, so the zero init is not a + detail -- tests/test_lewm_port.py asserts it.""" + + def __init__(self, dim, heads, mlp_dim, dropout=0.0): + super().__init__() + self.ln1 = nn.LayerNorm(dim, elementwise_affine=False) + self.ln2 = nn.LayerNorm(dim, elementwise_affine=False) + self.heads, self.inner = heads, 64 * heads + self.to_qkv = nn.Linear(dim, 3 * self.inner, bias=False) + self.to_out = nn.Linear(self.inner, dim) + self.mlp = nn.Sequential(nn.Linear(dim, mlp_dim), nn.GELU(), nn.Linear(mlp_dim, dim)) + self.ada = nn.Linear(dim, 6 * dim) + nn.init.zeros_(self.ada.weight) + nn.init.zeros_(self.ada.bias) + self.dropout = dropout + + def forward(self, x, c, mask): + sh1, sc1, g1, sh2, sc2, g2 = self.ada(F.silu(c)).chunk(6, -1) + h = modulate(self.ln1(x), sh1, sc1) + B, T, _ = h.shape + q, k, v = self.to_qkv(h).chunk(3, -1) + q, k, v = (t.view(B, T, self.heads, 64).transpose(1, 2) for t in (q, k, v)) + o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, + dropout_p=self.dropout if self.training else 0.0) + x = x + g1 * self.to_out(o.transpose(1, 2).reshape(B, T, self.inner)) + return x + g2 * self.mlp(modulate(self.ln2(x), sh2, sc2)) + + +class ARPredictor(nn.Module): + """Causal transformer over the CTX embedding history, conditioned on the action embedding.""" + + def __init__(self, emb_dim, depth, heads, mlp_dim, num_frames=CTX, dropout=0.0): + super().__init__() + self.pos = nn.Parameter(torch.randn(1, num_frames, emb_dim) * 0.02) + self.blocks = nn.ModuleList([AdaLNBlock(emb_dim, heads, mlp_dim, dropout) for _ in range(depth)]) + self.norm = nn.LayerNorm(emb_dim) + mask = torch.tril(torch.ones(num_frames, num_frames, dtype=torch.bool)) + self.register_buffer("mask", mask[None, None], persistent=False) + + def forward(self, emb_ctx, act_ctx): + x = emb_ctx + self.pos[:, : emb_ctx.shape[1]] + m = self.mask[..., : x.shape[1], : x.shape[1]] + for blk in self.blocks: + x = blk(x, act_ctx, m) + return self.norm(x) + + +class LeWM(nn.Module): + """encoder -> projector -> causal predictor -> pred_proj, JEPA-style.""" + + def __init__(self, size="m", a_dim=56, in_ch=6, res=84, ctx=CTX, dropout=0.0): + super().__init__() + emb, depth, heads, mlp = LEWM_SIZES[size] + self.emb_dim, self.ctx, self.a_dim = emb, ctx, a_dim + self.encoder = Encoder(emb, in_ch=in_ch, res=res) + self.projector = ProjMLP(emb, emb) + self.pred_proj = ProjMLP(emb, emb) + self.act_enc = ActionEmbedder(a_dim, emb) + self.predictor = ARPredictor(emb, depth, heads, mlp, num_frames=ctx, dropout=dropout) + + def embed(self, frames_u8): + """frames [B,T,C,H,W] uint8 -> embeddings [B,T,D] (encoder + projector).""" + B, T = frames_u8.shape[:2] + z = self.encoder(frames_u8.reshape(B * T, *frames_u8.shape[2:])) + return self.projector(z).view(B, T, -1) + + def step_emb(self, emb_hist, act_hist): + """[B,ctx,D] history + [B,ctx,A] actions -> the NEXT embedding [B,D].""" + h = self.predictor(emb_hist, self.act_enc(act_hist)) + return self.pred_proj(h)[:, -1] + + def forward(self, frames_u8, actions): + """frames [B,ctx+N_PREDS,C,H,W] uint8, actions [B,ctx+N_PREDS,A] + -> (pred [B,ctx,D], emb [B,ctx+N_PREDS,D]). `emb` is NOT detached anywhere: the target of + the prediction loss is the live encoder's own output, which is the recipe.""" + emb = self.embed(frames_u8) + act = self.act_enc(actions) + h = self.predictor(emb[:, : self.ctx], act[:, : self.ctx]) + return self.pred_proj(h), emb + + +def sigreg_stat(emb_tbd, generator=None, knots=17, num_proj=1024, A=None): + """Epps-Pulley SIGReg statistic, ported verbatim from the reference. + + emb_tbd: [T, B, D]. Projects onto `num_proj` random unit directions and compares the empirical + characteristic function of each projection against a standard normal's on a trapezoid grid over + t in [0, 3]. Scaled by B and averaged over time slices, exactly as the reference does. + This term is the ONLY thing preventing representation collapse in LeWM -- there is no target + network -- so its weight (LAMBDA = 0.09) and its scaling are load-bearing. + """ + dev, dt_ = emb_tbd.device, emb_tbd.dtype + T, B, D = emb_tbd.shape + t = torch.linspace(0.0, 3.0, knots, device=dev, dtype=dt_) + dt = 3.0 / (knots - 1) + w = torch.full((knots,), 2 * dt, device=dev, dtype=dt_) + w[0] = dt + w[-1] = dt + phi = torch.exp(-t ** 2 / 2.0) + weights = w * phi + # `A` is injectable ONLY so test_lewm_port.py can check the statistic against an independent + # implementation on the same projections; training always draws it fresh, as the reference does. + if A is None: + A = torch.randn(D, num_proj, device=dev, dtype=dt_, generator=generator) + A = A / A.norm(dim=0, keepdim=True) + x_t = (emb_tbd @ A).unsqueeze(-1) * t # [T,B,P,K] + err = (x_t.cos().mean(-3) - phi) ** 2 + x_t.sin().mean(-3) ** 2 # [T,P,K] + return ((err @ weights) * B).mean() + + +class RewardProbe(nn.Module): + """p(membership | z): logit MLP on one embedding (see the deviation note in the module docstring).""" + + def __init__(self, emb_dim, hidden=512): + super().__init__() + self.net = nn.Sequential(nn.Linear(emb_dim, hidden), nn.SiLU(), + nn.Linear(hidden, hidden), nn.SiLU(), nn.Linear(hidden, 1)) + + def forward(self, z): + return self.net(z).squeeze(-1) + + +def make_optimizer(model, lr=LR, wd=WD): + return torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=wd) diff --git a/frozen/rsm_libero_freeze_20261002/lewm_readout.py b/frozen/rsm_libero_freeze_20261002/lewm_readout.py new file mode 100644 index 0000000000000000000000000000000000000000..2b32779e285284abd8896deb6051faa9a923604b --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/lewm_readout.py @@ -0,0 +1,265 @@ +"""LeWM read-out: best-of-N scoring of RISE-actor action chunks with a LeWM world model (gen_q#268). + +Q(s, A) for a candidate chunk A at the current frame s: + + z_0 = projector(encoder(s)) one frame, repeated to fill the ctx history + z_k+1 = pred_proj(predictor(hist_k, act_k)) one LeWM step under the chunk + c_k = sigmoid(probe(z_k)) the membership reward probe + Q = c_1 (mode "d1", L = 1) + = c_1 + (1-c_1) g^h (c_2 + (1-c_2) g^h (...)) (mode "fold", L hops, h = chunk frames) + +The fold is the SAME reach-or-continue algebra RSM, DWM and DINO-WM use, so the L>1 columns differ +in the model and not in the read-out arithmetic. + +TWO DEVIATIONS, BOTH FORCED AND BOTH DECLARED + 1. HISTORY. LeWM conditions on 3 frames; the planner hands a scorer the SINGLE current frame + (rsm_planner.plan_get_action: `obs_t = {k: v[:, -1] ...}`). The history is therefore filled by + repeating that frame. Changing the planner to keep a frame stack would change what EVERY other + scorer sees, so this is the only choice that keeps the comparison matched. + 2. CONTINUATION PAST THE FIRST HOP is sampled from the SAME stochastic Gaussian hop head RSM and + DINO-WM chain with, but conditioned on the pooled DINO state of the CURRENT observation rather + than of the rolled latent (gen_q#288, owner 2026-09-25: "should definitely be M different chains + for DINOWM and LeWM with stochastic continuations just like RSM"). The staleness is forced, not + chosen: LeWM predicts in ITS OWN embedding space, so a rolled state has no pooled DINO vector and + a policy over DINO states cannot be queried there; training a BC head on LeWM's latent would make + the continuation a DIFFERENT actor from RSM's, which is the one thing #288 asks to hold fixed. + So the action DISTRIBUTION is the same actor's, the conditioning state is s_0 for every hop, and + that is stated in the table. What this REPLACES is a zero-order hold -- every hop re-used the + candidate chunk -- which made the roll deterministic and every LeWM MPC cell a single rollout + even though it requested 16 (630 published cells; see `effective_particles` below). + `hop_policy=None` still gives the old zero-order hold at n_particles=1, byte-identical, so the + published M=1 arms remain reproducible. + + 3. PARTICLES. With (2) the roll is stochastic, so M particles are M different action sequences and + Q is the mean over them, with common random numbers across candidates (particle m's eps is drawn + once per hop and tiled over the candidate rows, exactly as dwm_readout._q_once does). Only + depth == 1 has no continuation to sample and stays deterministic at n_particles = 1. + +PROPRIO is not an input to LeWM (the reference is pixels + actions), so the `pr` half of the +scorer's input tuple is accepted and ignored rather than being silently concatenated somewhere. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from lewm_model import LeWM, RewardProbe + + +class LeWMCritic: + """The interface robomimic's RSMScorer expects of a backend core (see rsm_scorer.DWMBackend).""" + + def __init__(self, ck, device): + a = ck["arch"] + self.device = torch.device(device) + self.arch = dict(a) + self.chunk = int(a["chunk"]) + self.adim = int(a["adim"]) + self.d_act = int(ck["d_act"]) + self.res = int(a["res"]) + self.ctx = int(a["ctx"]) + self.in_ch = int(a["in_ch"]) + self.model = LeWM(size=a["size"], a_dim=self.d_act, in_ch=self.in_ch, res=self.res, + ctx=self.ctx).to(self.device) + self.probe = RewardProbe(int(a["emb_dim"])).to(self.device) + self.model.load_state_dict(ck["lewm"]) + self.probe.load_state_dict(ck["probe"]) + for m in (self.model, self.probe): + m.eval() + for p in m.parameters(): + p.requires_grad_(False) + self.config = dict(ck.get("config", {})) + self.step = int(ck.get("step", -1)) + self.q_action_winrate = ck.get("q_action_winrate", float("nan")) + self.temperature = 1.0 + self.calib = None + self.hop_frames = float(self.chunk) + self.cams = tuple(ck.get("cams", ("agentview_image", "robot0_eye_in_hand_image"))) + self.autocast = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) \ + if self.device.type == "cuda" else (lambda: torch.autocast("cpu", enabled=False)) + + # ------------------------------------------------------------------------------------------ + def _gen(self, seed): + g = torch.Generator(device=self.device) + g.manual_seed(int(0 if seed is None else seed)) + return g + + def n_eff_particles(self, n_particles, depth, mode, hop_policy=None): + """DISTINCT roll-outs a (n_particles, depth, mode) cell actually averages -- see deviation 3. + + Recorded in the eval cell's `planner.scorer.effective_particles` so verdict_table's arm key can + carry the MEASURED M rather than the requested one. Before gen_q#288 this critic collapsed + every count to 1, so 630 published LeWM cells requested 16 and measured one rollout; without + this field a repaired M=16 cell would pool with them. + """ + d = 1 if mode == "d1" else int(depth or 1) + if d <= 1 or hop_policy is None: + return 1 + return int(n_particles or 1) + + @staticmethod + def _pooled_of(inp): + """The pooled 1545-d DINO state of the CURRENT observation, if the scorer carried it. + + rsm_scorer hands LeWM `(frames, proprio)` historically and `(frames, proprio, pooled_raw)` + since gen_q#288, because the hop head is a policy over pooled DINO states (deviation 2). A + 2-tuple therefore means "no hop head on this cell" and takes the zero-order-hold path. + """ + return inp[2] if isinstance(inp, (tuple, list)) and len(inp) > 2 else None + + def _prep(self, inp, a_chunk): + img = inp[0] if isinstance(inp, (tuple, list)) else inp + x = torch.as_tensor(img).to(self.device) + if x.dtype.is_floating_point: # the planner's frames are float in [0,1] + x = (x.clamp(0, 1) * 255.0).round().to(torch.uint8) + assert x.ndim == 4 and x.shape[1] == self.in_ch, \ + f"LeWM expects [B,{self.in_ch},{self.res},{self.res}] frames, got {tuple(x.shape)}" + aa = torch.as_tensor(a_chunk).to(self.device).float().view(x.shape[0], -1) + assert aa.shape[1] == self.d_act, f"a_chunk must be [B,{self.d_act}], got {tuple(aa.shape)}" + return x, aa + + @torch.no_grad() + def q(self, inp, a_chunk, beta=None, n_particles=16, crn_seed=None, depth=1, mode="d1", + 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, the mean over `n_particles` stochastic roll-outs (gen_q#288; see deviations 2-3). + + `beta` is inert -- LeWM has no discount, and the per-hop discount uses hop_frames = the action + chunk. `flow_steps` is inert (no ODE). `hop_policy(pooled_raw [R,1545], eps [R,d_act]) -> + a_chunk [R,d_act]` is the continuation actor: the SAME callable rsm_scorer builds for DWM and + DINO-WM. With hop_policy=None the roll falls back to the pre-#288 zero-order hold at one + particle, byte-identical, so the published M=1 arms stay reproducible. + """ + if mode == "d1": + depth = 1 + elif mode not in ("fold", "mpc", "mpc_disc"): + # gen_q#273: the MPC read-outs, identical in meaning to dwm_readout's -- the SAME open-loop + # roll-out this method already performs, combined as terminal / discounted-sum instead of + # through the beta-hazard fold. Additive: d1 and fold are untouched. + raise ValueError(f"mode {mode!r}: use 'd1', 'fold', 'mpc' or 'mpc_disc'") + depth = max(int(depth), 1) + n = self.n_eff_particles(n_particles, depth, mode, hop_policy) + if return_lcb is not None: + # The particle distribution now EXISTS at n > 1, but the caller also needs the (q, ql, lcb) + # triple rsm_scorer.DWMBackend returns, and LeWMBackend does not build it. Refuse rather + # than return a mean where a quantile was asked for. + raise ValueError("plan_score=conformal_lcb is not implemented for the LeWM backend " + "(gen_q#288 gives it a particle bundle; the LCB plumbing is not wired)") + x, aa = self._prep(inp, a_chunk) + pooled = self._pooled_of(inp) + B = x.shape[0] + T = float(self.temperature if temperature is None else temperature) + d_act = int(getattr(hop_policy, "d_act", self.d_act)) if hop_policy is not None else self.d_act + # CRN: one eps per (hop, particle), drawn UP FRONT so it is independent of the micro-batching + # and shared by every candidate -- particle m of every row sees the same continuation noise, + # which is the variance-reduction convention dwm_readout._q_once uses (`.repeat(B, 1)` there, + # an index by row % n here because the micro loop slices the repeat_interleave'd rows). + eps = None + if n > 1 or (hop_policy is not None and depth > 1): + if hop_policy is not None and pooled is None: + raise ValueError( + "LeWM's continuation actor is a policy over the POOLED 1545-d DINO state, but the " + "scorer passed inp=(frames, proprio) without it. rsm_scorer.RSMScorer._inputs must " + "hand LeWM (frames, proprio, pooled_raw) whenever a hop head is loaded (gen_q#288).") + g = self._gen(crn_seed) + eps = torch.randn(max(depth - 1, 1), n, d_act, device=self.device, generator=g) + xr = x.repeat_interleave(n, 0) if n > 1 else x + ar = aa.repeat_interleave(n, 0) if n > 1 else aa + pr_pool = None if pooled is None else (pooled.repeat_interleave(n, 0) if n > 1 else pooled) + R = B * n + logits, cs = [], [] + m = max(int(micro), 1) + for i in range(0, R, m): + j = min(i + m, R) + xi, ai = xr[i:j], ar[i:j] + pid = torch.arange(i, j, device=self.device) % n # which particle each row is + with self.autocast(): + z0 = self.model.embed(xi.unsqueeze(1))[:, 0] # one frame -> [b, D] + hist = z0.unsqueeze(1).repeat(1, self.ctx, 1) # deviation 1: repeat it + acts = ai.unsqueeze(1).repeat(1, self.ctx, 1) # hop 1 IS the candidate + lg_i, cs_i = [], [] + for k in range(depth): + with self.autocast(): + z = self.model.step_emb(hist, acts) + lg = self.probe(z).float() + lg_i.append(lg) + cs_i.append(torch.sigmoid(lg / T)) + if k == depth - 1: + break + hist = torch.cat([hist[:, 1:], z.unsqueeze(1).float()], 1) + if hop_policy is not None: + # deviation 2: fresh draw from RSM's OWN hop head, conditioned on s_0's pooled state + nxt = torch.as_tensor(hop_policy(pr_pool[i:j].float(), eps[k][pid])).to( + self.device).float().view(j - i, -1) + if nxt.shape[1] != self.d_act: + raise ValueError(f"hop_policy returned {nxt.shape[1]}-d chunks, LeWM needs " + f"{self.d_act}") + else: + nxt = acts[:, -1] # pre-#288 zero-order hold + acts = torch.cat([acts[:, 1:], nxt.unsqueeze(1)], 1) + logits.append(torch.stack(lg_i, 0)) + cs.append(torch.stack(cs_i, 0)) + lg_all = torch.cat(logits, 1) # [depth, R] + cs_all = torch.cat(cs, 1) + # COMBINE OVER HOPS FIRST, AVERAGE OVER PARTICLES LAST -- the order dwm_readout._q_once uses. + # Averaging the per-hop c_k over particles first and folding the means afterwards is a + # different (and biased) estimator for every non-linear read-out, i.e. for the fold. + if mode == "d1": + q = cs_all[0] + elif mode in ("mpc", "mpc_disc"): + h = self.hop_frames + if mode == "mpc": + q = cs_all[-1] + else: + w = [float(gamma) ** (h * k) for k in range(depth)] + tot = float(sum(w)) + q = sum(wk * cs_all[k] for k, wk in enumerate(w)) / tot + else: + h = self.hop_frames + q = torch.zeros_like(cs_all[-1]) + for k in range(depth - 1, -1, -1): + c = cs_all[k] + 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_all[-1], nan=0.0).view(B, n).mean(1) + out = (q, q_logit) if return_logit else q + if return_hops: + return out, [c.view(B, n) for c in cs_all] + return out + + def hop_sample(self, x, eps): + raise RuntimeError("LeWMCritic has no hop head of its own; the continuation actor is passed in " + "as `hop_policy` by rsm_scorer.LeWMBackend (gen_q#288) and is a policy over " + "POOLED DINO states, so sample it there, not here") + + def describe(self): + return {"backend": "lewm", "size": self.arch.get("size"), "emb_dim": self.arch.get("emb_dim"), + "ctx": self.ctx, "chunk": self.chunk, "hop_frames": self.hop_frames, + "step": self.step, "q_action_winrate": self.q_action_winrate, + # gen_q#288: the TRANSITION is deterministic, the ROLL-OUT is not (the continuation is + # sampled from the hop head past hop 1), so this flag now names the transition only. + "deterministic": True, "deterministic_transition": True, + "stochastic_continuation": True} + + +def load_critic_lewm(path, device="cuda", calib="auto") -> LeWMCritic: + ck = torch.load(str(path), map_location="cpu", weights_only=False) + m = str(ck.get("model", "?")) + if m != "lewm": + raise RuntimeError(f"{path} is a {m!r} checkpoint, not a LeWM one (train_lewm.py writes " + f"model='lewm')") + crit = LeWMCritic(ck, device) + 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"[lewm_readout] calib.json unreadable ({e}); T=1", flush=True) + return crit diff --git a/frozen/rsm_libero_freeze_20261002/make_video_report.py b/frozen/rsm_libero_freeze_20261002/make_video_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8187fc90470f1eac3969e78708de4de06c32f299 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/make_video_report.py @@ -0,0 +1,94 @@ +"""Turn the eval matrix (video frames + per-episode outcomes) into a report: +mp4 per episode, one collage per cell (10 tasks x first/mid/last frame, outcome-coded), +and an HTML index with the SR table and links. Cells are named by the eval job: + __, e.g. r256_demo = BC_rollsucc @256 from exact demo inits.""" +import argparse, json, glob, os +from pathlib import Path +import numpy as np + + +def mp4(frames, path, fps=15): + import imageio + w = imageio.get_writer(path, fps=fps, codec="libx264", quality=7, macro_block_size=1) + for f in frames: w.append_data(f) + w.close() + + +def collage(cell_dir, out_png, title): + from PIL import Image, ImageDraw + files = sorted(glob.glob(f"{cell_dir}/t*_e*.npz"), + key=lambda p: (int(Path(p).stem.split("_")[0][1:]), int(Path(p).stem.split("_")[1][1:]))) + by_task = {} + for f in files: + z = np.load(f, allow_pickle=True); by_task.setdefault(int(z["task"]), []).append((f, z)) + tasks = sorted(by_task); n_ep = max(len(v) for v in by_task.values()) if by_task else 0 + S = 96; cols = 3 * n_ep; rows = len(tasks) + im = Image.new("RGB", (cols * S + 60, rows * S + 24), (245, 245, 245)); dr = ImageDraw.Draw(im) + dr.text((4, 4), title, fill=(0, 0, 0)) + for r, t in enumerate(tasks): + dr.text((4, 24 + r * S + S // 2 - 6), f"t{t}", fill=(0, 0, 0)) + for e, (f, z) in enumerate(by_task[t]): + fr = z["frames"]; ok = bool(z["success"]); n = len(fr) + for j, k in enumerate((0, n // 2, n - 1)): + tile = Image.fromarray(fr[k]).resize((S, S)) + x, y = 60 + (e * 3 + j) * S, 24 + r * S + im.paste(tile, (x, y)) + dr.rectangle([x, y, x + S - 1, y + S - 1], outline=(0, 170, 0) if ok else (200, 0, 0), width=3) + dr.text((60 + e * 3 * S + 2, 24 + r * S + 2), "OK" if ok else f"fail {int(z['steps'])}", + fill=(0, 120, 0) if ok else (180, 0, 0)) + im.save(out_png) + return len(files), sum(bool(np.load(f, allow_pickle=True)["success"]) for f in files) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--video-root", default="/data/pulkitag/users/rli14/rsm_libero_runs/video") + ap.add_argument("--eval-root", default="/data/pulkitag/users/rli14/rsm_libero_runs/eval") + ap.add_argument("--cells", default="r256_lib,r256_demo,r256_roll,r128_demo,d128_lib,d256_lib") + ap.add_argument("--out", required=True) + args = ap.parse_args() + out = Path(args.out); (out / "mp4").mkdir(parents=True, exist_ok=True) + legend = {"r256_lib": "BC_rollsucc @256, LIBERO stock inits (protocol A)", + "r256_demo": "BC_rollsucc @256, EXACT demo initial states (hdf5 states[0])", + "r256_roll": "BC_rollsucc @256, EXACT rollout initial states (its own training inits)", + "r128_demo": "BC_rollsucc @128 (old evaluator), EXACT demo initial states", + "d128_lib": "BC-on-demos @128 (old evaluator, the 0.584 bar), LIBERO inits", + "d256_lib": "BC-on-demos @256 (new evaluator), LIBERO inits"} + rows = [] + for c in args.cells.split(","): + cd = f"{args.video_root}/{c}" + if not glob.glob(f"{cd}/t*_e*.npz"): + rows.append((c, legend.get(c, c), None, None, None, None)); continue + n, k = collage(cd, out / f"{c}.png", legend.get(c, c)) + links = [] + for f in sorted(glob.glob(f"{cd}/t*_e*.npz")): + z = np.load(f, allow_pickle=True); name = f"{c}_{Path(f).stem}_{'ok' if z['success'] else 'fail'}.mp4" + p = out / "mp4" / name + if not p.exists(): mp4(z["frames"], str(p)) + links.append((name, bool(z["success"]), int(z["task"]))) + js = f"{args.eval_root}/{c}.json" + sr = json.load(open(js)).get("overall", {}) if os.path.exists(js) else {} + rows.append((c, legend.get(c, c), n, k, sr, links)) + html = ["BC on rollout successes: evaluator at 256", + "", + "

BC on rollout successes — does the existing policy work once the evaluator renders at 256?

", + "

Same checkpoints as before; the only change is the evaluator's camera resolution and where the initial state comes from. Green border = success, red = failure (with step count). Videos are the agentview camera, every 2nd step.

", + ""] + for c, what, n, k, sr, links in rows: + if n is None: + html.append(f""); continue + html.append(f"") + html.append("
cellwhatsuccessfrom json
{c}{what}not run yet
{c}{what}{k}/{n} = {k/n:.3f}{sr}
") + for c, what, n, k, sr, links in rows: + if n is None: continue + html.append(f"

{c} — {what}

{k}/{n} succeeded

") + html.append("

" + " · ".join(f"t{t}{'✓' if ok else '✗'}" for nm, ok, t in links) + "

") + html.append("") + (out / "index.html").write_text("\n".join(html)) + print(f"[report] {out}/index.html") + for c, what, n, k, sr, links in rows: + print(f" {c:<10} {('%d/%d' % (k, n)) if n else 'pending':>8} {what}") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/mc_critic.py b/frozen/rsm_libero_freeze_20261002/mc_critic.py new file mode 100644 index 0000000000000000000000000000000000000000..79215fc2a67ef2ef4bb37fbbc7f19192d7d8d5b1 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/mc_critic.py @@ -0,0 +1,72 @@ +"""Scalar Monte-Carlo critic on the frozen RSM latent: Q(z, a_chunk, task) regressed on the +LOGGED discounted return of the offline corpus -- no occupancy, no bootstrap. The matched +scalar comparator for the RSM read-out (same latent, same inputs, same held-out set). + G_sub = (1-g) sum_k g^k r_{t+k} (dense subgoal-fraction reward) -> head 'sub' + G_succ = g^(steps to success) or 0 -> head 'succ' +Saved in the evaluator's --qf-ckpt format (iql_q=True) so it plugs into every selection +arm unchanged; `q` = the G_sub head unless --target succ. +usage: mc_critic.py --cache C --critic ckpt --subgoal-dir D --mask M --out DIR [--steps 60000]""" +import argparse, os, sys, json, numpy as np, torch, torch.nn.functional as F +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from data import LiberoRSMData +from is_ope import load_critic +from iql import QNet +from scipy.stats import spearmanr + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) +ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="") +ap.add_argument("--out", required=True); ap.add_argument("--steps", type=int, default=60000) +ap.add_argument("--batch", type=int, default=1024); ap.add_argument("--lr", type=float, default=3e-4) +ap.add_argument("--gamma", type=float, default=0.99); ap.add_argument("--target", default="sub", choices=["sub", "succ"]) +ap.add_argument("--width", type=int, default=1024); ap.add_argument("--depth", type=int, default=3) +ap.add_argument("--seed", type=int, default=0) +a = ap.parse_args() +torch.manual_seed(a.seed); dev = "cuda" if torch.cuda.is_available() else "cpu" +d = LiberoRSMData(a.cache, chunk=10, seed=a.seed, in_ram=True, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, + success_mask=a.mask, norm_pool="demos") +enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d) +g = a.gamma +# ---- precompute per-frame returns once (both targets), vectorised per episode +G_sub = np.zeros(len(d.r), np.float32); G_succ = np.zeros(len(d.r), np.float32) +for e in range(d.n_ep): + lo, hi = int(d.ep_from[e]), int(d.ep_to[e]); rr = np.asarray(d.r[lo:hi], np.float64) + acc = 0.0 + for i in range(hi - lo - 1, -1, -1): + acc = rr[i] + g * acc; G_sub[lo + i] = (1 - g) * acc + if bool(d.ep_success[e]): + G_succ[lo:hi] = g ** np.arange(hi - lo, 0, -1) +print(f"[mc] returns: mean G_sub={G_sub.mean():.3f} G_succ={G_succ.mean():.3f}", flush=True) +q = QNet(cfg["d_z"], 70, d.n_task, width=a.width, depth=a.depth).to(dev) +opt = torch.optim.AdamW(q.parameters(), lr=a.lr, weight_decay=1e-4) +rng = np.random.default_rng(a.seed) +def batch(split, n): + eps = d.train_eps if split == "train" else d.val_eps + w = d.ep_len[eps].astype(np.float64); w /= w.sum(); e = rng.choice(eps, size=n, p=w) + t = d.ep_from[e] + (rng.random(n) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + act = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(n, -1) + tgt = torch.from_numpy((G_sub if a.target == "sub" else G_succ)[t]).to(dev) + return x, tk, act, tgt, t +os.makedirs(a.out, exist_ok=True); best = -1 +for step in range(1, a.steps + 1): + x, tk, act, tgt, _ = batch("train", a.batch) + with torch.no_grad(): z = enc(x) + pred = q(z, act, tk).squeeze(-1) + loss = F.mse_loss(pred, tgt); opt.zero_grad(); loss.backward(); opt.step() + if step % 5000 == 0 or step == a.steps: + q.eval() + with torch.no_grad(): + x, tk, act, tgt, t = batch("val", 6000); z = enc(x); pv = q(z, act, tk).squeeze(-1).cpu().numpy() + tkn = tk.cpu().numpy(); gs, gc = G_sub[t], G_succ[t] + wt = np.nanmean([spearmanr(pv[tkn == tt], gs[tkn == tt]).correlation for tt in range(d.n_task) if (tkn == tt).sum() > 30]) + sp = spearmanr(pv, gs).correlation; sc = spearmanr(pv, gc).correlation + print(f"[mc] {step} train_mse={float(loss):.4f} | VAL spearman G_sub {sp:+.3f} within-task {wt:+.3f} | G_succ {sc:+.3f}", flush=True) + blob = {"iql_q": True, "q": q.state_dict(), "d_z": cfg["d_z"], "d_act": 70, "n_task": d.n_task, "critic": a.critic, + "config": {"target": a.target, "gamma": g, "width": a.width, "depth": a.depth, "steps": step}, + "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch"), + "val_spearman_within": float(wt), "val_spearman": float(sp)} + torch.save(blob, os.path.join(a.out, f"mc_q_s{step}.pt")); torch.save(blob, os.path.join(a.out, "mc_q.pt")) + if wt > best: best = wt; torch.save(blob, os.path.join(a.out, "mc_q_best.pt")) + q.train() +print("[mc] DONE", flush=True) diff --git a/frozen/rsm_libero_freeze_20261002/merge_and_train.sbatch b/frozen/rsm_libero_freeze_20261002/merge_and_train.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..88c8c9a88bc1dc059d7c5870f99d567d1ed84ca2 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/merge_and_train.sbatch @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=merge_verify +#SBATCH --account=vision-pulkitag +#SBATCH --cpus-per-task=2 --mem=16G +#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 +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +PY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python +$PY $G/merge_verify.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --shards /data/pulkitag/users/rli14/rsm_libero_runs/verify \ + --out /data/pulkitag/users/rli14/rsm_libero_runs/verify/verified_mask.npz diff --git a/frozen/rsm_libero_freeze_20261002/merge_full.sbatch b/frozen/rsm_libero_freeze_20261002/merge_full.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..4149931e4c9e22e27f583db6c5d2ebcfdb202f23 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/merge_full.sbatch @@ -0,0 +1,15 @@ +#!/bin/bash +#SBATCH --job-name=merge_full +#SBATCH --account=vision-pulkitag +#SBATCH --qos=tig-main +#SBATCH --partition=tig-cpu +#SBATCH --cpus-per-task=2 --mem=16G +#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 +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python $G/merge_verify.py \ + --cache /data/pulkitag/scratch/rli14/rsm_libero_cache/full_r256 \ + --shards /data/pulkitag/users/rli14/rsm_libero_runs/verify_full \ + --out /data/pulkitag/users/rli14/rsm_libero_runs/verify_full/verified_mask.npz +echo "[merge] rc=$?" diff --git a/frozen/rsm_libero_freeze_20261002/merge_verify.py b/frozen/rsm_libero_freeze_20261002/merge_verify.py new file mode 100644 index 0000000000000000000000000000000000000000..99447b748fddf5a1c3ed10c1fd01f5218b806cac --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/merge_verify.py @@ -0,0 +1,60 @@ +"""Merge the per-task replay-verification shards into one success mask. + +Output: keep[i] over cache episode indices. An episode stays in the success pool only +if it is a demo (ground truth, never replayed), or a rollout whose logged success +REPRODUCED when its actions were re-executed from the logged sim_state. Episodes that +could not be resolved (source parquet missing) are dropped from the success pool rather +than trusted -- the whole point is that an unverified success is not a success. +""" +import argparse, glob, numpy as np + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True) +ap.add_argument("--shards", required=True, help="REPLAY shards (reproducibility)") +ap.add_argument("--goal-shards", default="", + help="GOAL-AUDIT shards (goal predicate at the logged final state). " + "DIAGNOSTIC ONLY -- do NOT filter on this. It answers 'was the label " + "honest about the state the episode reached', which is not the " + "admissibility question. Admissibility is REPRODUCIBILITY in the eval " + "environment; see --shards.") +ap.add_argument("--out", required=True) +ap.add_argument("--keep-unresolvable", type=int, default=0) +a = ap.parse_args() + +m = np.load(f"{a.cache}/meta.npz", allow_pickle=True) +demo, succ = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) +keep = demo.copy() # demos always kept +seen = np.zeros(len(demo), bool) +rep = unres = 0 +# ADMISSIBILITY RULE: a trajectory may train an offline learner only if its reward +# labels REPRODUCE in the environment we evaluate in. A label that was honest about the +# state its own run reached is still inadmissible if replaying those actions here does +# not get there -- those (s,a,r) tuples describe different dynamics than the ones the +# policy will be scored against, which is exactly what breaks offline RL. +src, mode = a.shards, "REPLAY in the eval environment (admissibility)" +if a.goal_shards: + print("[merge] NOTE: goal-audit shards given but NOT used as the filter; " + "they are diagnostic. Filtering on reproducibility.") +print(f"[merge] filtering on: {mode}") +for f in sorted(glob.glob(f"{src}/task*.npz")): + z = np.load(f, allow_pickle=True) + if a.goal_shards: + r = z["rows"]; idx, ver = r[:, 0], r[:, 1] + else: + idx, ver = z["ep_index"], z["verified"] + for e, v in zip(idx, ver): + seen[e] = True + if v == 1: keep[e] = True; rep += 1 + elif v < 0: + unres += 1 + if a.keep_unresolvable: keep[e] = True +n_succ = int((succ & ~demo).sum()) +missing = int((succ & ~demo & ~seen).sum()) +np.savez(a.out, keep=keep, n_checked=int(seen.sum()), n_reproduced=rep) +print(f"[merge] rollout successes in cache : {n_succ}") +print(f"[merge] checked : {int(seen.sum())} (missing shards: {missing})") +print(f"[merge] reproduced : {rep} ({rep/max(seen.sum(),1):.1%})") +print(f"[merge] unresolvable : {unres} " + f"({'kept' if a.keep_unresolvable else 'DROPPED'})") +print(f"[merge] success pool: {int((succ).sum())} -> {int(keep.sum())} episodes") +print(f"[merge] wrote {a.out}") diff --git a/frozen/rsm_libero_freeze_20261002/mislabel_report.py b/frozen/rsm_libero_freeze_20261002/mislabel_report.py new file mode 100644 index 0000000000000000000000000000000000000000..f27a0ca4e7bfa2b8c0ab16399f9ceefb8c4070a7 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/mislabel_report.py @@ -0,0 +1,41 @@ +"""Per-task mislabelling breakdown: episodes AND reward-frames affected. + +An episode's success bit is one label, but the reward is per-frame and derived from +it, so a single mislabelled episode corrupts every frame it occupies. Both counts are +reported because they answer different questions: how much of the success POOL is +fake (episodes), and how much of the reward SIGNAL is wrong (frames).""" +import glob, sys, numpy as np +V = sys.argv[1] if len(sys.argv) > 1 else "/data/pulkitag/users/rli14/rsm_libero_runs/verify" +C = "/data/pulkitag/users/rli14/rsm_libero_cache/full_demo" +m = np.load(f"{C}/meta.npz", allow_pickle=True) +elen = (m["ep_to"] - m["ep_from"]).astype(int) +tn = [str(t) for t in m["tasks"]] +d, s = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) +rows, TE, TB, TF, TFB = [], 0, 0, 0, 0 +for f in sorted(glob.glob(f"{V}/task*.npz")): + z = np.load(f); t = int(z["task"]) + idx, ver = z["ep_index"], z["verified"] + ok = ver >= 0; idx, ver = idx[ok], ver[ok] + if len(idx) == 0: + rows.append((t, 0, 0, 0, 0)); continue + bad = idx[ver == 0] + nf, nfb = int(elen[idx].sum()), int(elen[bad].sum()) + rows.append((t, len(idx), len(bad), nf, nfb)) + TE += len(idx); TB += len(bad); TF += nf; TFB += nfb +print(f"{'task':4s} {'name':36s} {'checked':>8s} {'MISLAB':>7s} {'rate':>6s} " + f"{'frames':>9s} {'bad frames':>11s} {'%':>6s}") +for t, n, b, nf, nfb in sorted(rows): + if n == 0: + print(f" {t:<3d} {tn[t][:36]:36s} {'--':>8s} {'--':>7s} {'--':>6s}" + f" {'--':>9s} {'--':>11s} {'--':>6s} (no logged successes)") + continue + print(f" {t:<3d} {tn[t][:36]:36s} {n:8d} {b:7d} {b/n:6.1%} " + f"{nf:9,d} {nfb:11,d} {nfb/nf:6.1%}") +nd = sum(1 for r in rows if r[1] > 0) +print(f"\n TOTAL over {nd} tasks with successes: {TE} checked, " + f"{TB} mislabelled ({TB/max(TE,1):.1%})") +print(f" reward frames: {TF:,} in verified episodes, {TFB:,} carry a wrong label " + f"({TFB/max(TF,1):.1%})") +npool = int((s & ~d).sum()) +print(f" rollout successes in cache: {npool}; checked {TE} ({TE/npool:.0%})" + f" -> projected ~{round(npool*TB/max(TE,1))} mislabelled at the pooled rate") diff --git a/frozen/rsm_libero_freeze_20261002/model.py b/frozen/rsm_libero_freeze_20261002/model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c006359c647f7ddc3b9f8700f8f0dc276fdcd34 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/model.py @@ -0,0 +1,525 @@ +"""Nets for RSM on the LIBERO-10 pi0.5 rollout corpus. + +Design follows the unified-RSM recipe on gen_q `main` (ogbench_unified_rsm/RECIPE.md, +notes/COLLAPSE_ANALYSIS.md), adapted from goal-ball OGBench to sparse-success LIBERO: + + * beta BAND training, not a single discount (RECIPE "train beta [0.8,0.98]") + * Fourier features on log(-log beta) (RECIPE "fourier_unit, n_fourier=6") + * residual successor z' = z + delta, with delta divided by the per-dimension + dataset RMS of (z_fut - z_now) (RECIPE v6.1 "horizon-normalize + then per-dimension divide by rms((s'-s)_i)") + * EMA target encoder supplies the future target, stop-grad, plus a per-coordinate + variance floor (RECIPE "variance floor keeps the + embedding from collapsing"; smolvla_rsm METHOD.md) + * action chunk conditions the occupancy on an equal footing with the task + embedding, via concat + FiLM (RECIPE v6 "condition on g and a equally") + +What is deliberately NOT ported: the goal-ball arrival likelihood (`q_readout=lik`, +`p = exp(-d^2/2 tol^2)` on privileged xy/xyz). LIBERO has no privileged success ball +in this latent, so the read-out is a learned reward decoder over the same latent, as +the image branch of CLAUDE.md requires. + +COLLAPSE_ANALYSIS lesson carried over: a value that scores STATES but cannot rank +ACTIONS produces flat batch metrics and a closed-loop cliff. The occupancy here is +action-conditioned for exactly that reason, and action ranking is the headline +diagnostic rather than state ranking. +""" +from __future__ import annotations +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def beta_fourier(beta: torch.Tensor, n: int = 6) -> torch.Tensor: + """Fourier features on the log-horizon of a discount in (0,1).""" + x = torch.log(-torch.log(beta.clamp(1e-6, 1 - 1e-6))) + fr = torch.arange(1, n + 1, device=beta.device, dtype=beta.dtype) + a = x[:, None] * fr[None] + return torch.cat([a.sin(), a.cos(), x[:, None]], -1) # 2n+1 + + +def time_embed(t: torch.Tensor, dim: int = 64) -> torch.Tensor: + half = dim // 2 + fr = torch.exp(-np.log(10000.0) * torch.arange(half, device=t.device, + dtype=t.dtype) / half) + a = t[:, None] * fr[None] * 1000.0 + return torch.cat([a.sin(), a.cos()], -1) + + +def mlp(sizes, act=nn.SiLU, out_act=False, norm=False): + layers = [] + for i in range(len(sizes) - 1): + layers.append(nn.Linear(sizes[i], sizes[i + 1])) + if i < len(sizes) - 2 or out_act: + if norm: + layers.append(nn.LayerNorm(sizes[i + 1])) + layers.append(act()) + return nn.Sequential(*layers) + + + +class TaskCond(nn.Module): + """Task conditioning: a frozen T5 sentence embedding, projected. + + The alternative -- nn.Embedding(n_task, d_task) -- conditions on an INDEX. It carries + nothing about what the task is, cannot transfer to a held-out instruction, and gives + the network a shortcut that removes any pressure on the visual latent to represent + the instruction. Passing t5_path swaps in the frozen sentence embedding; omitting it + keeps the index embedding so old checkpoints still load. + """ + + def __init__(self, n_task: int, d_task: int = 64, t5_path: str = ""): + super().__init__() + self.t5 = bool(t5_path) + if self.t5: + import numpy as _np + emb = _np.load(t5_path)["emb"].astype("float32") + emb = emb / (_np.linalg.norm(emb, axis=1, keepdims=True) + 1e-6) + self.register_buffer("E", torch.tensor(emb), persistent=True) + self.proj = nn.Linear(emb.shape[1], d_task) + else: + # hold the table as `weight` and look it up with F.embedding, so the + # state_dict key stays `.task.weight` -- exactly what + # nn.Embedding produced. Wrapping it as a submodule would rename the + # key and break every checkpoint written before this change. + self.weight = nn.Parameter(torch.randn(n_task, d_task) * 0.02) + + def forward(self, task): + if self.t5: + return self.proj(self.E[task]) + return F.embedding(task, self.weight) + + +class Encoder(nn.Module): + """OGPO 4096-d -> compact reward-predictive latent.""" + + def __init__(self, d_in: int, d_z: int = 256, width: int = 1024, depth: int = 3): + super().__init__() + self.net = mlp([d_in] + [width] * depth + [d_z], norm=True) + self.d_z = d_z + + def forward(self, x): + return self.net(x) + + +class IdentityEncoder(nn.Module): + """`--enc identity`: the (z-scored) input feature IS the latent. No parameters, so the + EMA target, the variance floor and the reward warm-up are all no-ops. Used when the + feature is a frozen foundation-model embedding modelled directly (rsm_rise: DINOv2 + CLS|GeM per camera + proprio, 1545-d), as the OCBench visual recipe did.""" + + def __init__(self, d_in: int): + super().__init__() + self.d_z = int(d_in) + + def forward(self, x): + return x + + +class PCAEncoder(nn.Module): + """`--pca-dim k`: a FIXED linear map fitted once on training frames (not a learned encoder). + z = (x - mean) @ W with W [d_in, k] orthonormal columns (top-k right singular vectors), so the + pseudo-inverse is W^T: back(z) = z @ W^T + mean. mean/W are persistent buffers, saved in the + checkpoint's `enc` state_dict and reloaded by is_ope.load_critic.""" + + def __init__(self, d_in: int, k: int): + super().__init__() + self.d_z = int(k) + self.register_buffer("mean", torch.zeros(int(d_in))) + self.register_buffer("W", torch.zeros(int(d_in), int(k))) + + @torch.no_grad() + def fit(self, X): + """X [n, d_in] float tensor of (z-scored) training states. Returns explained-variance ratio.""" + self.mean.copy_(X.mean(0)) + _u, S, Vh = torch.linalg.svd(X - self.mean, full_matrices=False) + self.W.copy_(Vh[: self.d_z].T) + var = S.pow(2) + return float(var[: self.d_z].sum() / var.sum()) + + def forward(self, x): + return (x - self.mean) @ self.W + + def back(self, z): + return z @ self.W.T + self.mean + + +class RewardHead(nn.Module): + """Goal-conditioned reward decoder R(z, task) -> logit of 'task complete here'.""" + + def __init__(self, d_z: int, n_task: int, d_task: int = 64, width: int = 512, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.net = mlp([d_z + d_task, width, width, 1]) + + def forward(self, z, task): + return self.net(torch.cat([z, self.task(task)], -1)).squeeze(-1) + + +class GoalLikelihood(nn.Module): + """Dense two-tower goal likelihood -- the recipe's `q_readout=lik`. + + `l = sigmoid( / tau)` with phi, psi unit-norm MLPs. Asymmetric + on purpose (phi != psi), because "z is at goal g" is not "g is at goal z". + + Why this replaces a binary success head: the success head is SPARSE -- terminal + labels are ~0.5% of frames, so almost every sampled future reads ~0 and Q is + near-constant in the action, leaving nothing to rank. This gives EVERY (z, g) + pair a probability, which is what makes the read-out able to separate actions. + + Trained by in-batch InfoNCE: positive is (z + eps, z), negatives are the other + goals in the batch. Recipe knobs: goal_feat_dim 256, towers (512,)x3, + goal_nce_tau 0.2, nce_noise 0.1. The scorer is STOP-GRAD in the Q path -- NCE + is the only gradient into the towers. + """ + + def __init__(self, d_z: int, d_feat: int = 256, width: int = 512, depth: int = 3, + tau: float = 0.2, noise: float = 0.1): + super().__init__() + self.phi = mlp([d_z] + [width] * depth + [d_feat], norm=True) + self.psi = mlp([d_z] + [width] * depth + [d_feat], norm=True) + self.tau = tau + self.noise = noise + + def _emb(self, net, z): + e = net(z) + return e / e.norm(dim=-1, keepdim=True).clamp_min(1e-6) + + def logit(self, z, g): + return (self._emb(self.phi, z) * self._emb(self.psi, g)).sum(-1) / self.tau + + def forward(self, z, g): + return torch.sigmoid(self.logit(z, g)) + + def nce_loss(self, z): + """In-batch InfoNCE. Positive (z+eps, z); negatives are other batch rows.""" + zp = z + self.noise * torch.randn_like(z) + a = self._emb(self.phi, zp) + b = self._emb(self.psi, z) + logits = (a @ b.t()) / self.tau + tgt = torch.arange(z.shape[0], device=z.device) + return F.cross_entropy(logits, tgt) + + +class FiLM(nn.Module): + def __init__(self, d_cond, d_h): + super().__init__() + self.to_gb = nn.Linear(d_cond, 2 * d_h) + + def forward(self, h, c): + g, b = self.to_gb(c).chunk(2, -1) + return h * (1 + g) + b + + +class OccFlow(nn.Module): + """Conditional flow-matching velocity for the beta-discounted successor. + + Predicts the velocity of the RESIDUAL delta = (z_fut - z_now) / rms, so the + network never has to re-encode z_now's own coordinates. + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 1024, depth: int = 4, n_fourier: int = 6, t5_path: str = "", + norm: bool = False, dropout: float = 0.0): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + d_cond = d_z + d_act + d_task + (2 * n_fourier + 1) + self.cond = mlp([d_cond, width, width], out_act=True, norm=True) + self.in_proj = nn.Linear(d_z + 128, width) + # norm=True (train_rsm.py --flow-norm 1): LayerNorm inside every residual block and on the + # stream before the output head. rsm_rise measured the un-normalised trunk amplifying + # held-out states (velocity 170 -> 8500 over 8 Euler steps on val rows, 8 -> 11 on train). + # Default False keeps every existing checkpoint loadable (Identity has no parameters). + self.blocks = nn.ModuleList([mlp([width, width], out_act=True, norm=norm) + for _ in range(depth)]) + if dropout > 0: + # appended INSIDE each block's Sequential so the Linear keeps state_dict index 0 + for blk in self.blocks: + blk.append(nn.Dropout(dropout)) + self.films = nn.ModuleList([FiLM(width, width) for _ in range(depth)]) + self.final_norm = nn.LayerNorm(width) if norm else nn.Identity() + self.out = nn.Linear(width, d_z) + self.n_fourier = n_fourier + + def forward(self, z_now, a_chunk, task, beta, x_k, k): + c = self.cond(torch.cat( + [z_now, a_chunk, self.task(task), beta_fourier(beta, self.n_fourier)], -1)) + h = self.in_proj(torch.cat([x_k, time_embed(k, 128)], -1)) + for blk, film in zip(self.blocks, self.films): + h = h + film(blk(h), c) + return self.out(self.final_norm(h)) + + +class RatioNet(nn.Module): + """Per-decision density-ratio classifier. + + Trained to separate a LOGGED action chunk at state z (from the behavior policy + mu) from a chunk freshly SAMPLED from the target policy pi at the same z. On + balanced classes the logit is exactly log pi/mu, so we never need a normalized + density for either policy -- which matters because mu here is a flow model + sampled as an SDE and has no tractable likelihood. This is the substitute for + the notes' w_{t,k} = prod pi(a_j|s_j)/mu(a_j|s_j). + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 512, depth: int = 3, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.net = mlp([d_z + d_act + d_task] + [width] * depth + [1], norm=True) + + def forward(self, z, a_chunk, task): + return self.net(torch.cat([z, a_chunk, self.task(task)], -1)).squeeze(-1) + + +class EndpointRatio(nn.Module): + """Rao-Blackwellized endpoint weight w*(z,a,z') = d^pi_beta / d^mu_beta. + + Regression target is the chunk-level product of per-decision ratios; the + squared-loss minimizer is the conditional expectation given the endpoint, + which is precisely the notes' Section-9 identity. Predicts LOG w for stability. + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 512, depth: int = 3, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.net = mlp([2 * d_z + d_act + d_task] + [width] * depth + [1], norm=True) + # start at w ~= 1: softplus(0.5413) = 1.0 + nn.init.zeros_(self.net[-1].weight); nn.init.constant_(self.net[-1].bias, 0.5413) + + def forward(self, z, a_chunk, z_fut, task): + """Returns w > 0 directly. softplus rather than exp: under squared loss an + exponential head has gradient proportional to w itself, so once it + undershoots it stops learning -- observed as E_mu[w]=0.45 against a target + of 1.0. softplus keeps the gradient alive as w -> 0.""" + o = self.net(torch.cat([z, a_chunk, z_fut, self.task(task)], -1)).squeeze(-1) + return F.softplus(o) + + +class RawFeat(nn.Module): + """Feature map for policy extraction: full observation, CENTERED only. + + Two separate findings drive this. + + (1) The policy must not read the critic's latent. That encoder is trained to + predict REWARD, so its bottleneck keeps what separates success from failure + and discards what an action head needs. Measured: a flow policy on the 264-d + reward latent beat a predict-the-mean action baseline by only 14% in MSE, + with a biased gripper channel. + + (2) It must not read PER-DIM Z-SCORED features either. Whitening gives all + 4104 dimensions equal variance, which amplifies thousands of near-dead + directions up to the scale of the informative ones. Measured on BC-on-demos: + action loss rose 0.158 -> 0.355 and closed-loop success fell from 3/10 to + 0/10 on task 2 when the policy input was whitened. + + What the input actually needed was CENTERING: the mean feature vector has + norm 51.1 against a per-frame deviation of norm 9.0, so 85% of the raw + magnitude is a constant carrying no information. Centering removes that + without touching the relative importance of dimensions. + + The data layer hands over z-scored features (the critic wants those), so this + module rescales them back by `scale` = sd / mean(sd) over the visual block, + recovering (x - mu) / s_global exactly. Proprio keeps its per-dim z-score: + its 8 dims are genuinely different units, spanning std 0.014 to 1.372.""" + + def __init__(self, d, scale=None): + super().__init__() + self.d_out = int(d) + if scale is None: + scale = torch.ones(int(d)) + self.register_buffer("scale", torch.as_tensor(scale, dtype=torch.float32)) + + def forward(self, x): + return x * self.scale + + +class ConcatFlowPolicy(nn.Module): + """Flow-matching action-chunk policy, CONCATENATION-conditioned. + + A faithful port of the head behind this lane's 0.584 bcdemos bar. The + difference from FlowPolicy is not cosmetic: FlowPolicy squeezes the whole + 4104-d observation through a `cond` MLP and injects it only as FiLM scale and + shift, so the action branch never sees the observation directly. Measured + consequence at identical chunk (10), width (1024), depth (4) and demo cache: + held-out ODE-sampled reconstruction MSE was 0.0480 for FiLM against 0.00319 + for the concatenation head that reaches 0.584 -- a 15x gap that no amount of + normalisation or feature choice closed. + + Everything else matches that recipe: SiLU, no normalisation layers, 64-d task + embedding, 128-d sinusoidal flow-time embedding, the noisy chunk fed straight + in, and 10 Euler steps at sampling time. + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 1024, depth: int = 4, steps: int = 10, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + ind = d_z + d_task + 128 + d_act + layers = [] + for i in range(depth): + layers += [nn.Linear(ind if i == 0 else width, width), nn.SiLU()] + layers += [nn.Linear(width, d_act)] + self.net = nn.Sequential(*layers) + self.d_act = d_act + self.steps = steps + + def velocity(self, z, task, a_k, k): + return self.net(torch.cat([z, self.task(task), time_embed(k, 128), a_k], -1)) + + def fm_loss(self, z, task, a, reduce=True): + k = torch.rand(a.shape[0], device=a.device) + noise = torch.randn_like(a) + a_k = (1 - k)[:, None] * a + k[:, None] * noise + per = (self.velocity(z, task, a_k, k) - (a - noise)).pow(2).mean(-1) + return per.mean() if reduce else per + + @torch.no_grad() + def sample(self, z, task, temp: float = 1.0, sde: float = 0.0, + sde_anneal: bool = False): + """temp scales the initial noise; sde injects noise DURING integration. + + sde_anneal scales the injected noise by the remaining noise fraction k, so + the perturbation is large early (where the drift can still re-project it + onto the manifold) and vanishes at the last steps; constant sde leaves an + un-corrected sde*sqrt(dt) kick on the final action. + + These buy diversity in different places and it matters here. temp inflates + the PRIOR the ODE transports, so every sample starts further out and the + map carries it somewhere the data never was -- measured closed-loop 0.550 + at temp 1.0, 0.310 at 1.5, 0.000 at 2.0, with the ranker held fixed. sde + follows the learned drift and perturbs along the way, which keeps samples + near the manifold the drift was fitted on. That is the mechanism that + produced usable candidate diversity in the related lane. + + Flow matching learns a near-deterministic map for a unimodal conditional, + so a trained policy's samples barely differ: measured action std 0.029 at + 120k steps and 0.053 at 20k, against 0.421 in the data. PARL cannot rank + N copies of one action, so temp>1 widens the prior the ODE transports and + gives the critic something to choose between. Candidates further from the + mode are exactly what the value is there to accept or reject. + """ + return self.sample_eps(z, task, torch.randn(z.shape[0], self.d_act, device=z.device), + temp=temp, sde=sde, sde_anneal=sde_anneal) + + def sample_eps(self, z, task, eps, temp: float = 1.0, sde: float = 0.0, + sde_anneal: bool = False): + """sample() with caller-supplied initial noise eps [B, d_act] (common random + numbers across candidates); the SDE perturbations, if any, stay independent.""" + x = eps * temp + dt = 1.0 / self.steps + for s in range(self.steps): + k = torch.full((z.shape[0],), 1 - s / self.steps, device=z.device) + x = x + self.velocity(z, task, x, k) * dt + if sde: + # Euler-Maruyama style: the drift is followed exactly and the + # perturbation scales as sqrt(dt), so total injected variance is + # independent of the number of solver steps. + sc = sde * (dt ** 0.5) + if sde_anneal: + sc = sc * float(k[0]) + x = x + sc * torch.randn_like(x) + return x + + +class BCHead(nn.Module): + """Gaussian action-chunk policy over the frozen latent: pi(A | z, task). + + Deliberately a tractable Gaussian, unlike the flow-SDE behavior policy: the + target policy is the one we must SAMPLE from many times per state (for the + ratio classifier and for AWR), and a closed form keeps that cheap. + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 1024, depth: int = 4, log_std_init: float = -1.0, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.trunk = mlp([d_z + d_task] + [width] * depth, out_act=True, norm=True) + self.mu = nn.Linear(width, d_act) + self.log_std = nn.Parameter(torch.full((d_act,), log_std_init)) + + def forward(self, z, task): + h = self.trunk(torch.cat([z, self.task(task)], -1)) + return self.mu(h), self.log_std.clamp(-5.0, 2.0) + + def sample(self, z, task, n: int = 1): + mu, ls = self(z, task) + if n == 1: + return mu + torch.randn_like(mu) * ls.exp() + mu = mu[:, None].expand(-1, n, -1) + return mu + torch.randn_like(mu) * ls.exp() + + def sample_eps(self, z, task, eps): + """Sample with caller-supplied standard-normal noise (common random numbers).""" + mu, ls = self(z, task) + return mu + eps * ls.exp() + + def log_prob(self, z, task, a): + mu, ls = self(z, task) + var = (2 * ls).exp() + return (-0.5 * ((a - mu) ** 2 / var + 2 * ls + np.log(2 * np.pi))).sum(-1) + + +class FlowPolicy(nn.Module): + """Flow-matching action-chunk policy pi(A | z, task). + + Replaces the Gaussian head because of a measured failure: with a Gaussian + target and a flow-SDE behaviour policy, the density-ratio classifier hit + 99.9-100% accuracy. It was not separating good actions from bad, it was + separating "Gaussian sample" from "flow sample" -- a parametric-family + artifact -- which drove E_mu[W] to 0.18 against a required 1.0 and made the + importance weights meaningless. Matching the family removes that shortcut. + + No tractable density, which is fine: the classifier supplies the ratio, and + AWR weights the per-sample flow-matching loss instead of a log-likelihood + (the same substitution the smolvla AWR run used). + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 1024, depth: int = 4, steps: int = 8, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.cond = mlp([d_z + d_task, width, width], out_act=True, norm=True) + self.in_proj = nn.Linear(d_act + 128, width) + self.blocks = nn.ModuleList([mlp([width, width], out_act=True) + for _ in range(depth)]) + self.films = nn.ModuleList([FiLM(width, width) for _ in range(depth)]) + self.out = nn.Linear(width, d_act) + self.d_act = d_act + self.steps = steps + + def velocity(self, z, task, a_k, k): + c = self.cond(torch.cat([z, self.task(task)], -1)) + h = self.in_proj(torch.cat([a_k, time_embed(k, 128)], -1)) + for blk, film in zip(self.blocks, self.films): + h = h + film(blk(h), c) + return self.out(h) + + def fm_loss(self, z, task, a, reduce=True): + """Per-sample flow-matching loss; stands in for -log pi(a|z).""" + k = torch.rand(a.shape[0], device=a.device) + noise = torch.randn_like(a) + a_k = (1 - k)[:, None] * a + k[:, None] * noise + v = self.velocity(z, task, a_k, k) + per = (v - (a - noise)).pow(2).mean(-1) + return per.mean() if reduce else per + + @torch.no_grad() + def sample(self, z, task, n: int = 1): + if n > 1: + z = z.repeat_interleave(n, 0) + task = task.repeat_interleave(n, 0) + a = torch.randn(z.shape[0], self.d_act, device=z.device) + for s in range(self.steps): + k = torch.full((z.shape[0],), 1.0 - s / self.steps, device=z.device) + a = a + self.velocity(z, task, a, k) / self.steps + return a + + +@torch.no_grad() +def ema_update(target: nn.Module, online: nn.Module, m: float = 0.995): + for pt, po in zip(target.parameters(), online.parameters()): + pt.mul_(m).add_(po.detach(), alpha=1 - m) + for bt, bo in zip(target.buffers(), online.buffers()): + bt.copy_(bo) diff --git a/frozen/rsm_libero_freeze_20261002/notes/action_contrast.pdf b/frozen/rsm_libero_freeze_20261002/notes/action_contrast.pdf new file mode 100644 index 0000000000000000000000000000000000000000..ee49476a9e88e8a40fb4c00a0f06f26b39901ee5 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/notes/action_contrast.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65c4330748f098ef6fcd6fbf42b24807b9bfb2dd2146e0ad8851b75d8e29cea3 +size 187852 diff --git a/frozen/rsm_libero_freeze_20261002/notes/action_contrast.tex b/frozen/rsm_libero_freeze_20261002/notes/action_contrast.tex new file mode 100644 index 0000000000000000000000000000000000000000..bbdc28c13a9a74693660ca02a5e8adbbd9a386e1 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/notes/action_contrast.tex @@ -0,0 +1,182 @@ +\documentclass[11pt]{article} +\usepackage[margin=1in]{geometry} +\usepackage{amsmath,amssymb,booktabs,microtype} +\title{\vspace{-2em}The action-contrast term: same intent, opposite sign,\\opposite conclusion} +\author{gen\_q, branch \texttt{rsm-libero10-ope}} +\date{2026-09-11} +\begin{document}\maketitle\vspace{-1.5em} + +\section{Why this needs writing down} + +\texttt{origin/main}'s campaign concludes that its action-contrast term is +\emph{wrong-signed}, a ``flat standing tax on correct behaviour'', and ablates it. +Ours is superficially the same idea. It would be easy --- and wrong --- to copy +that conclusion across. The two terms have opposite signs, and measured on this +corpus ours is load-bearing: removing it makes the critic worse. + +\section{The two terms} + +Write $e_{\text{true}}$ for the flow's reconstruction error of the true future +when conditioned on the action actually taken, and $e_{\text{shuf}}$ for the same +error when conditioned on another action from the batch. The \emph{desired} +state of affairs is $e_{\text{true}} < e_{\text{shuf}}$: the real action should +explain the real future better. Define the gap as main does, +\begin{equation} +\mathrm{gap} \;=\; e_{\text{true}} - e_{\text{shuf}}, +\qquad\text{so desired}\;\Longleftrightarrow\; \mathrm{gap} < 0 . +\end{equation} + +\paragraph{main's hinge.} +$\mathcal{L} = \mathrm{relu}\!\left(e_{\text{shuf}} - e_{\text{true}} + m\right) + = \mathrm{relu}(-\mathrm{gap} + m)$, with margin $m = 0.02$. This is +\emph{large} exactly when the gap is most negative, i.e. when the model is +behaving best. Their own reproduction pins it: + +\begin{center}\small +\begin{tabular}{lrrrrr} +\toprule +cell & $e_{\text{true}}$ & $e_{\text{shuf}}$ & gap & logged term & corrected hinge \\ +\midrule +cube-single & 0.3017 & 0.3675 & $-0.0658$ & \textbf{0.0858} & 0.0000 \\ +cube-double & 0.2670 & 0.3319 & $-0.0649$ & \textbf{0.0849} & 0.0000 \\ +cube-triple & 0.2419 & 0.3002 & $-0.0583$ & \textbf{0.0783} & 0.0000 \\ +cube-quadruple & 0.2240 & 0.2788 & $-0.0548$ & \textbf{0.0748} & 0.0000 \\ +\bottomrule +\end{tabular} +\end{center} + +The logged value equals $\mathrm{relu}(-\mathrm{gap}+m)$ to four decimals on every +cell, which is what confirms the sign. The true action \emph{already} reconstructs +better everywhere, and the hinge penalises that by $\approx 0.085$ on every step +of every run. The corrected hinge, $\mathrm{relu}(\mathrm{gap}+m)$, evaluates to +exactly $0$ on all four cells --- so on state their ``fix'' is an \textbf{ablation} +of the term, not a re-aiming of it. On pixels the same term is steeply +cell-dependent rather than uniform: $0.4069 \pm 0.0630$ on visual-single against +$0.0278 \pm 0.0075$ on quadruple, a ${\sim}15\times$ spread, falling hardest on +the cell that works best. + +\paragraph{Ours.} +$\mathcal{L} = \mathrm{softplus}\!\left(e_{\text{true}} - e_{\text{shuf}}\right) + = \mathrm{softplus}(\mathrm{gap})$. Minimising it drives the gap \emph{more} +negative, which is the desired direction. The sign is right. + +It is not, however, inert once the gap goes negative, and that is worth stating +because it is the natural assumption. At a gap of $-0.065$, +\begin{equation} +\mathrm{softplus}(-0.065) = \ln\!\left(1 + e^{-0.065}\right) \approx 0.661, +\qquad +\frac{\partial}{\partial\,\mathrm{gap}}\,\mathrm{softplus} = \sigma(-0.065) \approx 0.484 . +\end{equation} +So it still contributes a substantial loss and, more importantly, a gradient of +roughly $0.48$ --- it keeps pushing long after the ordering is correct. That is the +sense in which it resembles a tax; the difference from main's is that it pushes in +the \emph{right} direction. + +\section{Which negative? Measured, not argued} + +The natural reading of the term is ``the error on $(s,a,s')$ should beat the error +on $(s,a_{\text{rand}},s'_{\text{rand}})$'' --- shuffle the action \emph{and} the +target. What we implement holds $s'$ fixed and shuffles only the action. The +worry about the first form is that it confounds two effects: its error is large +partly because the action is wrong and partly because the target is an unrelated +future, and a successor that ignored the action entirely would still score well on +it. + +Measured on the deployed critic (\texttt{probe\_actcon.py}, 4 batches of 2048, +$\beta=0.9$, held-out): + +\begin{center}\small +\begin{tabular}{lrr} +\toprule +negative & flow-matching error & gap vs true \\ +\midrule +(true action, true target) & 0.5989 & --- \\ +shuffled ACTION, true target & \textbf{14.1241} & $+13.5251$ \\ +true action, shuffled target & 0.7378 & $+0.1389$ \\ +shuffled action AND target & 13.4020 & $+12.8031$ \\ +\bottomrule +\end{tabular} +\end{center} + +The action accounts for \textbf{105.6\%} of the both-shuffled gap and the target +for \textbf{1.1\%}. So the confound is negligible here: the intuitive form and the +implemented form measure essentially the same thing, because on this model +essentially all of the difficulty comes from the conditioning action. Holding +$s'$ fixed is still the cleaner instrument --- it is a paired comparison, same +target, same noise, same flow time --- but the two are not in practical conflict. + +(What one would \emph{ideally} contrast against is +$(s, a_{\text{rand}}, s'\!\mid\! a_{\text{rand}})$, the future that the random +action would actually have produced. That is unobtainable offline: the dataset +never shows where $a_{\text{rand}}$ leads from $s$. This is the same missing +counterfactual that makes the value's action direction arbitrary.) + +\section{The number that reframes everything} + +Shuffling the action multiplies the flow-matching error by \textbf{23.6$\times$} +($0.599 \to 14.12$). The successor is not remotely action-blind: it keys on the +action extremely strongly. Give it an action that did not produce this future and +its velocity prediction falls apart. + +That sits beside a fact established separately (\texttt{probe\_crn.py}): the +\emph{value} read off this same flow does not rank actions --- perturbing an +expert chunk raises $Q$ as often as it lowers it. Both are true, and together they +say something sharper than either alone. The model has learned a strong, +confident mapping from action to future. For actions it never saw at that state +that mapping produces a \emph{wildly} different prediction, and a wildly different +latent earns an essentially arbitrary reward. The failure is not indifference to +the action; it is confident nonsense off the data. + +\paragraph{A correction to this document.} An earlier version argued our term is +``not inert'' once the gap goes negative, computing +$\mathrm{softplus}(-0.065)\approx0.661$ with gradient $\approx0.48$. That used +\emph{main's} measured gap. Ours is $-13.53$, where +$\mathrm{softplus}(-13.53)\approx 1.3\times10^{-6}$ and the gradient is +$\sigma(-13.53)\approx 1.3\times10^{-6}$. On the trained model our term is +\textbf{numerically inert}. It is active only early, while the gap is still +small --- which is precisely where the action win rate peaks (steps 1000--2000) +before decaying. That is a better explanation of the ablation result below than +``a standing force'': the term shapes the successor early and then switches off. + +\section{What it is worth here} + +Held-out within-task action win rate of the critic, everything else fixed: + +\begin{center}\small +\begin{tabular}{lcc} +\toprule +$w_{\text{actcon}}$ & label & best action win rate \\ +\midrule +0.0 & dense (outcome) & 0.522 \\ +0.0 & terminal (arrival) & 0.478 \\ +\textbf{0.5} & dense & \textbf{0.568} \\ +1.0 (with $d_z{=}512$) & dense & 0.532 \\ +2.0 & dense & 0.533 \\ +\bottomrule +\end{tabular} +\end{center} + +Removing the term costs $0.046$ of win rate; doubling it past $0.5$ costs about as +much again. There is an optimum near $0.5$ and we are at it. \textbf{main's +ablation conclusion does not transfer}, and the reason is simply that their term +had the opposite sign: ablating a penalty on correct behaviour helps, ablating a +reward for it does not. + +\section{The caveat that limits all of this} + +The win rates above live in $0.52$--$0.57$, barely above chance, and the term +moves them by $0.05$. It is a real effect on a critic that is weak in a way this +term does not address. Separate measurement (\texttt{probe\_crn.py}) shows the +counterfactual-conditioned $Q$ responds to an action with roughly the right +magnitude and an \emph{arbitrary sign}, because it is trained only on the action +actually taken. The action-contrast term sharpens how much the successor depends +on the action; it does nothing to make that dependence point the right way. The +reader that does rank actions correctly here is the supervised student $Q$, fit by +regression onto real $(s,a,s')$ transitions --- expert-versus-perturbation wins +rising $0.515 \to 0.614$ with perturbation size, against flat chance for the +counterfactual read-out. + +So: keep the term at $0.5$, do not copy the ablation, and do not expect it to fix +the direction problem. + +\end{document} diff --git a/frozen/rsm_libero_freeze_20261002/notes/is_successor_tutorial.pdf b/frozen/rsm_libero_freeze_20261002/notes/is_successor_tutorial.pdf new file mode 100644 index 0000000000000000000000000000000000000000..946ace6a82e814ea79427765dbbe6ed26d5e0fcd Binary files /dev/null and b/frozen/rsm_libero_freeze_20261002/notes/is_successor_tutorial.pdf differ diff --git a/frozen/rsm_libero_freeze_20261002/notes/is_successor_tutorial.tex b/frozen/rsm_libero_freeze_20261002/notes/is_successor_tutorial.tex new file mode 100644 index 0000000000000000000000000000000000000000..ea8d0759076cdf13a835efff4d8c62964ec2e0df --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/notes/is_successor_tutorial.tex @@ -0,0 +1,104 @@ +\documentclass[9pt]{extarticle} +\usepackage[margin=0.4in]{geometry} +\usepackage{amsmath,amssymb,amsthm} +\usepackage{bm} +\usepackage{enumitem} +\usepackage[colorlinks=true,linkcolor=blue!60!black,urlcolor=blue!60!black]{hyperref} +\usepackage{xcolor} +\usepackage{tcolorbox} +\usepackage{parskip} +\setlength{\parskip}{2pt}\setlength{\abovedisplayskip}{3pt}\setlength{\belowdisplayskip}{3pt}\setlength{\abovedisplayshortskip}{2pt}\setlength{\belowdisplayshortskip}{2pt} + +\newcommand{\E}{\mathbb{E}} +\newcommand{\ind}{\mathbf{1}} +\newcommand{\dpi}{d^{\pi}_{\lambda}} +\newcommand{\dmu}{d^{\mu}_{\lambda}} + + +\linespread{0.92}\pagestyle{empty} +\begin{document} +\begin{center}{\large\bfseries Importance Sampling for Successor Distributions}\\[1pt]{\small How to turn a behavior-policy occupancy into a target-policy occupancy, and why the same weight reweights $Q$}\end{center}\vspace{-4pt} + +\paragraph{Short answer.} The note uses importance sampling to do \emph{both}: Sections~7--8 reweight to change the +\emph{distribution} ($\dmu \to \dpi$), and Section~9 pushes the identical weight through to the $Q$ readout, where +it becomes a per-particle multiplier. They are the same identity applied at different points. + + +\paragraph{Setup.} +The successor model $\hat d_\lambda(z\mid s,a)$ predicts a \emph{single} future state $z$. In the dataset that +state was produced by a logged sub-trajectory $\tau = (s_0, a_0, s_1, a_1, \dots, s_K)$ with $K\sim \mathrm{Geom}(1-\lambda)$ +and $z := s_K$. Call $\tau$ the chunk; it lives only in the data and in this derivation, never as a model output. +Conditioning on the first state--action pair, the chunk probability under a policy $\rho$ factorizes into dynamics, +the stopping clock, and the policy's own action choices: +\[ +p_\rho(\tau\mid s_0,a_0) \;=\; P(K)\prod_{j=0}^{K-1} P(s_{j+1}\mid s_j,a_j)\prod_{j=1}^{K-1}\rho(a_j\mid s_j). +\] +The dataset gives chunks from $p_\mu$ (behavior). We want the occupancy of the target policy $\pi$. + +\paragraph{Step 1: the trajectory ratio.} +Dynamics and the stopping clock do not depend on the policy, so they cancel in the ratio, leaving only the +intervening actions: +$w(\tau) := p_\pi(\tau\mid s_0,a_0)/p_\mu(\tau\mid s_0,a_0) = \prod_{j=1}^{K-1}\pi(a_j\mid s_j)/\mu(a_j\mid s_j)$. +The first action is excluded because both sides condition on it. This is the $w_{t,k}$ of Section~7 of the note. + +\paragraph{Step 2: the change of measure.} +For any function $f$ of the chunk, assuming $\mu>0$ wherever $\pi>0$, +\[ +\E_{\tau\sim p_\pi}[f(\tau)] \;=\; \sum_\tau p_\pi(\tau)\, f(\tau) \;=\; \sum_\tau p_\mu(\tau)\,\frac{p_\pi(\tau)}{p_\mu(\tau)}\, f(\tau) \;=\; \E_{\tau\sim p_\mu}\big[w(\tau)\, f(\tau)\big]. +\] +This one line is the whole method; everything else is choosing $f$. + +\paragraph{Step 3: from trajectories to the endpoint occupancy.} +Take $f(\tau)=\ind[s_K = z]$. The left side is $\dpi(z\mid s_0,a_0)$. Splitting the right side by endpoint, +\[ +\dpi(z\mid s,a) \;=\; \E_\mu\big[w(\tau)\,\ind[s_K=z]\big] \;=\; \dmu(z\mid s,a)\cdot\underbrace{\E_\mu\big[w(\tau)\mid s,a,s_K=z\big]}_{=:\;w^*(s,a,z)}. +\] +So the endpoint density ratio is the \emph{conditional average} of the trajectory ratio over all logged chunks that +share the same endpoint: +\[ +w^*(s,a,z) \;=\; \frac{\dpi(z\mid s,a)}{\dmu(z\mid s,a)} \;=\; \E_\mu\!\left[\prod_{j=1}^{K-1}\frac{\pi(a_j\mid s_j)}{\mu(a_j\mid s_j)}\;\middle|\; s,a,\,s_K=z\right]. +\] +This is the boxed identity in Section~9, and it is the key step: because the model emits only $z$, the only +weight usable at inference is a function of $(s,a,z)$, and $w^*$ is that function. Regressing $w(\tau)$ onto $(s,a,z)$ +with squared loss recovers it exactly, since the squared-loss minimizer is the conditional expectation. Averaging over +the hidden trajectories is Rao--Blackwellization, so $w^*$ has lower variance than $w(\tau)$. + +\paragraph{Step 4: three places to apply the weight.} +All three are Step~2 with a different $f$. +\begin{enumerate}[leftmargin=1.5em,itemsep=1pt,topsep=1pt] +\item \textbf{Training-time reweighting} (Sec.~7). Take $f=\ell_\theta(z\mid s,a)$, the endpoint flow-matching loss. Then +$\E_\mu[w\,\ell_\theta]=\E_\pi[\ell_\theta]$, so weighting each logged $(s,a,z)$ tuple by $w(\tau)$, computed from the +logged intervening actions, fits the endpoint model to $\dpi$ directly. The model still predicts only $z$. +\item \textbf{Test-time resampling} (Sec.~8). Sample chunks $\tau_i$ from the behavior model, compute $w_i$, normalize +$\tilde w_i = w_i/\sum_j w_j$, resample. Sampling--importance--resampling converts behavior samples into approximate +target samples. This is the one variant that needs the model to generate the whole chunk with its actions, i.e.\ a truncated trajectory/video model rather than a successor model. +\item \textbf{$Q$ reweighting} (Sec.~9). Take $f=r(z)$. Then +$Q^\pi(s,a) = \frac{1}{1-\gamma}\,\E_{z\sim d^\pi_\gamma}[r(z)] = \frac{1}{1-\gamma}\,\E_{z\sim d^\mu_\gamma}\big[w^*(s,a,z)\,r(z)\big]$. +The occupancy model stays fixed at $d^\mu$. Only a small learned $\hat w_\omega\approx w^*$ changes with $\pi$. +\end{enumerate} + +\paragraph{Step 5: through the recursion.} +With restart probability $p=\frac{\gamma-\lambda}{\gamma(1-\lambda)}$, a particle makes jumps $\ell=0,1,\dots$ and +draws each boundary action $a^{(\ell+1)}\sim\pi(\cdot\mid s^{(\ell+1)})$ itself. The boundary is already on-policy, +so only the \emph{inside} of each chunk needs correcting, and the corrections multiply: +\[ +C_i \;=\; \prod_{\ell}\hat w_\omega\big(s^{(\ell)},a^{(\ell)},z^{(\ell)}\big),\qquad +\hat Q^\pi(s,a) \;=\; \frac{1}{(1-\gamma)N}\sum_{i=1}^N C_i\, r(z_i). +\] +The self-normalized form $\frac{1}{1-\gamma}\,\sum_i C_i r(z_i)\big/\sum_i C_i$ trades a small bias for much lower +variance; resampling by $\hat w$ after every jump instead of carrying the product is the sequential Monte Carlo variant and avoids weight collapse. + +\paragraph{What it costs.} +Normalized action likelihoods for both policies ($\mu$ needs a fitted density; diffusion/flow policies have no tractable one); +variance of $w$ growing roughly like $\exp\!\big(K\cdot\mathrm{KL}(\pi\|\mu)\big)$, which is the argument for short chunks; and the +weight corrects policy mismatch only, never error in the learned proposal $\hat d^\mu_\lambda$. + +\begin{tcolorbox}[colback=orange!5,colframe=orange!60!black,boxrule=0.5pt,boxsep=1pt,top=2pt,bottom=2pt,left=4pt,right=4pt] +\textbf{Why this bears on the stitching result.} Boundary-only stitching swaps the policy at one action per chunk. +At $\lambda=0.98$ a chunk averages $\lambda/(1-\lambda)\approx 49$ steps, so the composed process follows $\pi$ on +roughly $2\%$ of steps and $\mu$ on the rest. The $Q$ estimate is then mostly evaluating the behavior policy, which +would make an improvement signal at the boundaries hard to see. Importance weighting is what makes the inside of each +chunk follow $\pi$ too. +\end{tcolorbox} + +\end{document} diff --git a/frozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.pdf b/frozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.pdf new file mode 100644 index 0000000000000000000000000000000000000000..5063b2d9ed3f9529a3e1f790fb506377d2f49481 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4df1f5ceef4984acf8b865afd0c510f854c61c91e3214a49ad86f239e8302ebc +size 202537 diff --git a/frozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.tex b/frozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.tex new file mode 100644 index 0000000000000000000000000000000000000000..2bc0c33d83005d1370867682304a0e526d5d5402 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.tex @@ -0,0 +1,141 @@ +\documentclass[11pt]{article} +\usepackage[margin=1in]{geometry} +\usepackage{amsmath,amssymb,booktabs,microtype} +\usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref} +\title{\vspace{-2em}RSM on LIBERO-10 rollouts: how our value differs from +\texttt{origin/main}} +\author{gen\_q, branch \texttt{rsm-libero10-ope}} +\date{2026-09-11} +\begin{document}\maketitle\vspace{-1.5em} + +\section{Why this document} + +Our RSM recipe does not improve on behaviour cloning for LIBERO-10 +(BC-on-demos $0.630$; best value-guided arm $0.510$), while the same family of +method works on \texttt{origin/main}'s benchmarks. This compares the two value +definitions term by term. The conclusion is that they are \emph{not the same +estimator}: three differences are structural, and one of them is a variance +problem that \texttt{main} explicitly documents and fixes and we did not. + +\section{The two definitions} + +Both start from the same object, the discounted successor occupancy +\begin{equation} +d^{\pi}_{\beta}(x\mid s,a,\cdot)=(1-\beta)\sum_{k\ge0}\beta^{k} +P^{\pi}\!\big(s_{t+k}=x\mid s_t=s,a_t=a\big), +\end{equation} +fitted by conditional flow matching on the residual +$\tilde x=(E(x)-E(s))/\eta(\beta)$ with $E(s)$ stop-gradient. Up to here the two +implementations agree, including the per-dimension residual normalisation and the +EMA target encoder. They diverge at the read-out. + +\paragraph{\texttt{origin/main}: a survival product over hops.} +A two-tower InfoNCE arrival likelihood +$\ell(x,g)=\sigma\!\big(\varphi(x)\!\cdot\!\psi_g(g)/\tau_q\big)$ is folded +backwards along a $K$-hop chain, giving +\begin{equation} +Q_{\text{main}}(s,a,g)\;=\;-\frac{\gamma^{K}}{1-\gamma} +\prod_{k=1}^{K}\big(1-\ell(h_k,g)\big), +\qquad +\arg\max_a Q \;=\; \arg\max_a \sum_{k=1}^{K}\operatorname{softplus}(f_k), +\label{eq:main} +\end{equation} +where $\ell=\sigma(f)$. Each factor is the modelled probability of \emph{not} +having arrived by hop $k$. + +\paragraph{Ours: an expectation of reward at one endpoint.} +A reward head $r$ is trained by BCE against a dense success label, and +\begin{equation} +Q_{\text{ours}}(z,a)\;=\;\frac{1}{1-\gamma}\, +\mathbb{E}_{z'\sim d^{\mu}_{\beta}}\big[\sigma(r(z'))\big], +\label{eq:ours} +\end{equation} +estimated as a self-normalised importance-weighted mean over $N$ particles, where +$z'$ is the endpoint of a geometrically-truncated recursion with restart +probability $p=(\gamma-\beta)/(\gamma(1-\beta))$. + +\section{The three structural differences} + +\begin{enumerate} +\item \textbf{Product over hops versus a single endpoint.} +\eqref{eq:main} accumulates arrival evidence at \emph{every} hop; \eqref{eq:ours} +reads the reward head \emph{once}, at the final endpoint, and discards the +intermediate hops. With a dense per-frame success label this throws away most of +the signal the chain generates and makes the estimate depend on one noisy draw +rather than $K$. + +\item \textbf{Unsaturating versus saturating.} +In log space \eqref{eq:main} is a \emph{sum of softplus}, whose derivative +$\sigma(f)\in(0,1)$ never vanishes. Ours is a mean of $\sigma$, whose gradient +vanishes at both ends. Our reward head reaches AUC $0.96$, so it is routinely +saturated, precisely where it stops discriminating. + +\item \textbf{Contrastive arrival versus a BCE reward head.} +$\ell$ is normalised against in-batch negatives, so it is a \emph{relative} +quantity and cannot collapse to a base rate. $\sigma(r(z'))$ is absolute: an +off-support $z'$ that drifts toward the dataset mean returns roughly the corpus +success rate, which is $0.545$ here and outranks a confident low score on a +genuinely failing action. +\end{enumerate} + +\section{The variance difference, which is the one that bites} + +\texttt{main} reports that the per-state estimator has +$\mathrm{sd}(\hat Q)\approx 4.51$ against a policy-improvement signal +$\mathbb{E}[Q(a_\pi)-Q(a_{\text{data}})]\approx 0.82$, a ratio of $5.5$, and +concludes that ``a maximising actor ascends estimator noise as readily as +signal''. Its fix is clipped double-$Q$ built from \emph{flow noise rather than +twin networks}: split the $N$ draws, take the minimum of the two half-means, +\begin{equation} +\hat Q_{\min2}=\min\Big\{\tfrac{2}{N}\textstyle\sum_{i\le N/2}Q^{(i)},\; +\tfrac{2}{N}\textstyle\sum_{i>N/2}Q^{(i)}\Big\}. +\label{eq:min2} +\end{equation} + +We measured the same regime independently on LIBERO-10 with +\texttt{probe\_crn.py}: repeat noise (same action, independent draws) $2.246$ +against a paired action effect of $0.399$ at the smallest perturbation, a ratio of +$5.6$. \textbf{The numbers agree almost exactly, and we did not implement +\eqref{eq:min2}.} We used the plain mean, optionally minus a particle standard +deviation. Those are not the same estimator: subtracting a spread penalises +disagreement symmetrically, whereas \eqref{eq:min2} is a one-sided pessimistic +bias that specifically stops an argmax from selecting a draw that was lucky. + +\begin{table}[h]\centering\small +\begin{tabular}{lll} +\toprule +& \texttt{origin/main} & ours \\ +\midrule +conditioning & goal $g$, reward-free & task id, dense success label \\ +arrival signal & two-tower InfoNCE $\ell(x,g)$ & $\sigma$ of a BCE reward head \\ +value form & survival product over $K$ hops & mean reward at one endpoint \\ +composition & fixed $K$, policy acts after hop 1 & geometric restart $p$, truncated \\ +estimator & $\min$ of two half-means & mean ($\pm$ std penalty) \\ +actor & $\max Q$ + BC anchor, scale-normalised & AWR exponential weights \\ +deployment & Polyak--Ruppert tail average & last / best checkpoint \\ +off-policy term & none & importance sampling (interior + endpoint) \\ +\bottomrule +\end{tabular} +\end{table} + +\section{What this predicts, and what it does not excuse} + +The differences above are enough to explain a weak value, and \eqref{eq:min2} +plus the product form are directly portable. They do \emph{not} by themselves +explain our sharper finding: with common random numbers cancelling the shared +noise, perturbing an expert action raises our $Q$ exactly as often as it lowers +it, at every perturbation size. That is a statement about \emph{direction}, not +variance, and no estimator applied after the fact repairs it. Its likely cause is +upstream of both formulas: the occupancy model is trained only on the action that +was actually taken, so its counterfactual response is unsupervised, and our +mean-pooled PaliGemma latent barely resolves what a 10-frame chunk does (action +versus proprio-delta correlation $0.98$, versus visual-latent delta $0.49$). + +Ordered by expected value: (i) adopt \eqref{eq:min2}; (ii) adopt the +product-over-hops read-out, which uses every hop and is unsaturating; +(iii) adopt the contrastive arrival likelihood, which cannot collapse to a base +rate. Items (i) and (ii) are small changes to \texttt{q\_recursive}; (iii) needs +the \texttt{GoalLikelihood} module already present but unused in +\texttt{model.py}. + +\end{document} diff --git a/frozen/rsm_libero_freeze_20261002/pack.py b/frozen/rsm_libero_freeze_20261002/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..dc899ff8fb29c3fb0408514dc528de8ffb203541 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/pack.py @@ -0,0 +1,278 @@ +"""Pack the LIBERO-10 pi0.5 OGPO rollout corpus into a flat memmap cache. + +Source layout (one npz per episode, 43,135 episodes over 10 task dirs): + /ep_t{T}_b{B}_i{id}_{epidx:06d}.npz + z [F,4096] float16 OGPO latent (agentview | wrist) + (task_index is NOT read -- see the guard in main()) + proprio [F,8] float32 + actions [F,7] float32 + success () bool + prompt () str + +Cache layout (written atomically into /): + z.f16 memmap [N,D] latents, frame-major, episodes contiguous + act.f32 memmap [N,7] executed action at that frame + meta.npz ep_from/ep_to/ep_len/ep_task/ep_success/ep_src, tasks, dim + +LEAKAGE NOTE recorded here because it shapes every downstream label choice: +failed episodes are ALL exactly 520 frames (the timeout) while successful ones +terminate early (mean ~263). Episode LENGTH therefore predicts success almost +perfectly. Any label built from "frames remaining" leaks the outcome, so the +reward label is defined on terminal states of successful episodes only, and the +headline diagnostic is action ranking at a FIXED state, never state ranking. +""" +from __future__ import annotations +import argparse, io, json, os, time, zipfile +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np + + +def read_header(path, assume_success=None): + """(n_frames, success) without reading the arrays. + + `np.load(f)["z"].shape` materialises the whole 2.3 MB latent block, which for + 43k episodes is ~99 GB of pointless NFS traffic. npz is a zip of .npy members, + so the shape lives in the member's own header: parse that and stop. + """ + with zipfile.ZipFile(path) as zf: + with zf.open("z.npy") as f: + ver = np.lib.format.read_magic(f) + shape, _fortran, _dt = np.lib.format._read_array_header(f, ver) + if assume_success is None or "success.npy" in zf.namelist(): + # rollouts always carry it; REPLAYED demo caches (rerender_rollouts.py + # --pool demos_replay) carry it too, and a demo whose live replay did not + # end in success is inadmissible exactly like a non-reproducing rollout + with zf.open("success.npy") as f: + succ = bool(np.load(io.BytesIO(f.read()), allow_pickle=False)) + else: + succ = assume_success # legacy demo caches carry no success field + return int(shape[0]), succ + + +def episode_files(root: Path): + """-> list of (task_name, path, is_demo). Task id comes from the directory name. + + Rollout dirs hold ep_*.npz and carry a `success` flag. The demo cache uses the + same task name with a `_demo` suffix, holds demo_*.npz, and has no success + field because every demonstration succeeds.""" + out = [] + for d in sorted(p for p in root.iterdir() if p.is_dir()): + demo = d.name.endswith("_demo") + name = d.name[:-5] if demo else d.name + for f in sorted(d.glob("demo_*.npz" if demo else "ep_*.npz")): + out.append((name, f, demo)) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--demos", default="", help="optional demo cache root to union in") + ap.add_argument("--max-eps", type=int, default=0, help="0 = all") + ap.add_argument("--stride", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--workers", type=int, default=32, + help="threads for the header scan (NFS latency-bound)") + ap.add_argument("--header-cache", default="", + help="npz to cache/reuse the (success,length) scan") + ap.add_argument("--tasks-file", default="/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation/logs/09052026_lib10_tasks.txt", + help="canonical LIBERO benchmark-id task order; task ids are " + "assigned from THIS list, never from directory sort order " + "and never from the npz `task_index` field.") + ap.add_argument("--keep-all-demos", action="store_true", + help="always include EVERY demo episode, then fill the rest " + "with rollouts. Balanced sampling kept only 94 of 500 " + "demos, which starves a BC-on-demos baseline.") + ap.add_argument("--episode-list", default="", + help="text file, one '/.npz' per line: pack EXACTLY these " + "rollouts in this order. Two clusters packing from the same list produce " + "index-identical caches, so per-episode artefacts (subgoal labels, " + "admissibility mask) transfer by index.") + ap.add_argument("--encoder", default="pi05_base_pytorch", + help="feature-encoder tag (basename of OGPO_PI05_BASE the latents were encoded " + "with). Written to PACK.json/RENDER.json; the evaluator refuses a mismatch.") + ap.add_argument("--cam-res", default="", + help="render resolution the SOURCE latents were encoded from (e.g. 256). " + "Written to PACK.json and RENDER.json; the evaluator refuses a cache " + "whose cam_res is undeclared or differs from its own --cam-res.") + ap.add_argument("--balance", action="store_true", + help="equalize success/failure count within each task") + args = ap.parse_args() + + rng = np.random.default_rng(args.seed) + src, out = Path(args.src), Path(args.out) + out.mkdir(parents=True, exist_ok=True) + files = episode_files(src) + if args.episode_list: + _want = [l.strip() for l in open(args.episode_list) if l.strip()] + _by = {f"{f.parent.name}/{f.name}": (n, f, dm) for n, f, dm in files if not dm} + _missing = [w for w in _want if w not in _by] + if _missing: + raise SystemExit(f"--episode-list: {len(_missing)} listed episodes absent under --src, e.g. {_missing[:3]}") + files = [_by[w] for w in _want] + [t for t in files if t[2]] # rollouts in list order, then demos + print(f"[pack] episode list: {len(_want)} rollouts pinned from {args.episode_list}", flush=True) + if args.demos: + files += episode_files(Path(args.demos)) + print(f"[pack] found {len(files)} episodes in {len(set(t for t, *_ in files))} tasks", + flush=True) + + # ---- pass 1: read headers (success + length), pick the subset ---- + hc = Path(args.header_cache) if args.header_cache else out / "headers.npz" + if hc.exists(): + c = np.load(hc, allow_pickle=True) + if len(c["paths"]) == len(files) and set(map(str, c["paths"])) == {str(f[1]) for f in files}: + dm_col = c["demo"] if "demo" in c.files else np.zeros(len(c["paths"]), bool) + hdr = [(t, Path(p), bool(s), int(L), bool(dm)) for t, p, s, L, dm in + zip(c["tasknames"], c["paths"], c["succ"], c["lens"], dm_col)] + print(f"[pack] header scan reused from {hc}", flush=True) + else: + hc.unlink() + if not hc.exists(): + def rd(tf): + task, f, demo = tf + L, succ = read_header(f, assume_success=True if demo else None) + return (task, f, succ, L, demo) + t_scan = time.time() + with ThreadPoolExecutor(max_workers=args.workers) as ex: + hdr = list(ex.map(rd, files, chunksize=16)) + print(f"[pack] header scan {len(hdr)} files in {time.time()-t_scan:.0f}s", + flush=True) + hc.parent.mkdir(parents=True, exist_ok=True) + np.savez(hc, tasknames=np.array([h[0] for h in hdr]), + paths=np.array([str(h[1]) for h in hdr]), + succ=np.array([h[2] for h in hdr]), + lens=np.array([h[3] for h in hdr]), + demo=np.array([h[4] for h in hdr])) + + # Task ids come from the canonical benchmark-id list so they agree with every + # other trainer in this lane. Two things are deliberately NOT used: directory + # sort order (incidental, and disagrees with benchmark id), and the npz + # `task_index` field (0 in every episode of this corpus). + canon = [n.strip() for n in + Path(args.tasks_file).read_text().replace("\n", ",").split(",") if n.strip()] + tid = {t: i for i, t in enumerate(canon)} + present = sorted(set(t for t, *_ in hdr)) + unknown = [t for t in present if t not in tid] + if unknown: + raise SystemExit(f"[pack] refusing: task dir(s) not in {args.tasks_file}: {unknown}") + tasks = canon + chosen = [] + unbalanced = [] + forced = [] + if args.keep_all_demos: + forced = [h for h in hdr if h[4]] + hdr = [h for h in hdr if not h[4]] + print(f"[pack] forcing all {len(forced)} demo episodes into the cache", flush=True) + if args.max_eps and args.max_eps < len(hdr): + per_task = args.max_eps // len(tasks) + for t in tasks: + pool = [h for h in hdr if h[0] == t] + if args.balance: + s = [h for h in pool if h[2]] + f_ = [h for h in pool if not h[2]] + k = min(per_task // 2, len(s), len(f_)) + pick = ([s[i] for i in rng.choice(len(s), k, replace=False)] + + [f_[i] for i in rng.choice(len(f_), k, replace=False)]) + if k == 0 and pool: + # A task can be entirely one-sided: STUDY_SCENE1 has 0 + # successes in 2,962 rollouts, so 50/50 balancing would drop + # it silently. Keep it at natural composition and record that + # it could not be balanced -- a task the behaviour policy + # never solves is a result, not a reason to hide the task. + kk = min(per_task, len(pool)) + pick = [pool[i] for i in rng.choice(len(pool), kk, replace=False)] + unbalanced.append((t, len(s), len(f_))) + else: + k = min(per_task, len(pool)) + pick = [pool[i] for i in rng.choice(len(pool), k, replace=False)] + chosen += pick + else: + chosen = hdr + chosen = forced + chosen + rng.shuffle(chosen) + sel_task = np.array([tid[h[0]] for h in chosen]) + n_per = np.bincount(sel_task, minlength=len(tasks)) + missing = [tasks[i] for i, n in enumerate(n_per) if n == 0 and + any(h[0] == tasks[i] for h in hdr)] + if missing: + raise SystemExit(f"[pack] refusing: task(s) present in source but absent " + f"from the selection: {missing}") + print(f"[pack] packing {len(chosen)} episodes " + f"(success {np.mean([h[2] for h in chosen]):.3f}) " + f"per-task {n_per.tolist()}", flush=True) + if unbalanced: + print(f"[pack] NOT balanceable (kept at natural composition): " + f"{[(u[0][:28], u[1], u[2]) for u in unbalanced]}", flush=True) + + # ---- pass 2: sizes, allocate, fill ---- + lens = np.array([1 + (h[3] - 1) // args.stride for h in chosen], dtype=np.int64) + ep_demo = np.array([h[4] for h in chosen], bool) + ep_to = np.cumsum(lens); ep_from = ep_to - lens + N = int(ep_to[-1]) + with np.load(chosen[0][1], allow_pickle=True) as n: + D = int(n["z"].shape[1]); A = int(n["actions"].shape[1]) + print(f"[pack] N={N} frames D={D} A={A} " + f"({N*D*2/1e9:.1f} GB latents)", flush=True) + + zmm = np.lib.format.open_memmap(out / "z.f16.npy", mode="w+", + dtype=np.float16, shape=(N, D)) + # proprio is cheap (8 floats/frame) and the lane's closed-loop policy head + # consumes it alongside the latent, so pack it for interoperability even + # though the occupancy critic here does not use it. + pmm = np.lib.format.open_memmap(out / "proprio.f32.npy", mode="w+", + dtype=np.float32, shape=(N, 8)) + amm = np.lib.format.open_memmap(out / "act.f32.npy", mode="w+", + dtype=np.float32, shape=(N, A)) + ep_task = np.zeros(len(chosen), np.int64) + ep_succ = np.zeros(len(chosen), bool) + ep_src = [] + for i, (task, f, succ, _L, _dm) in enumerate(chosen): + with np.load(f, allow_pickle=True) as n: + z = n["z"][::args.stride] + a = n["actions"][::args.stride] + pr = n["proprio"][::args.stride] if "proprio" in n.files else None + s, e = int(ep_from[i]), int(ep_to[i]) + zmm[s:e] = z[: e - s] + amm[s:e] = a[: e - s] + if pr is not None: + pmm[s:e] = pr[: e - s] + ep_task[i] = tid[task]; ep_succ[i] = succ + ep_src.append(str(f)) + if (i + 1) % 250 == 0: + # Bound dirty-page accumulation: without periodic flushes the whole + # written cache sits dirty in page cache and the box is reported as + # out of memory (it killed this job and the concurrent upload once). + zmm.flush(); amm.flush(); pmm.flush() + print(f"[pack] {i+1}/{len(chosen)} episodes", flush=True) + zmm.flush(); amm.flush(); pmm.flush() + + np.savez(out / "meta.npz", ep_from=ep_from, ep_to=ep_to, ep_len=lens, + ep_task=ep_task, ep_success=ep_succ, ep_demo=ep_demo, + tasks=np.array(tasks), + dim=D, adim=A, stride=args.stride, n_frames=N, + ep_src=np.array(ep_src)) + _cam = int(args.cam_res) if str(args.cam_res).isdigit() else (args.cam_res or "UNKNOWN") + (out / "RENDER.json").write_text(json.dumps({ + "cam_res": _cam, "encoder": args.encoder, "flip": "[::-1,::-1] to serving orientation", + "resize": "-> 224 bilinear, uint8", + "encoder": "08312026_1110pm_ogpo_latent_cache.py PaliGemma base||wrist", + "proprio": "eef_pos(3)+axis_angle(3)+gripper(2)"}, indent=1)) + (out / "PACK.json").write_text(json.dumps({ + "cam_res": _cam, "encoder": args.encoder, + "src": str(src), "episodes": len(chosen), "frames": N, "dim": D, + "adim": A, "stride": args.stride, + "success_rate": float(ep_succ.mean()), + "n_demo": int(ep_demo.sum()), + "tasks": tasks, + "task_id_source": f"canonical benchmark order from {args.tasks_file} " + f"(dir sort order and the npz task_index field are both ignored)", + "episodes_per_task": n_per.tolist(), + "tasks_not_balanceable": [[u[0], int(u[1]), int(u[2])] for u in unbalanced], + }, indent=2)) + print(f"[pack] DONE -> {out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/pack_full.sbatch b/frozen/rsm_libero_freeze_20261002/pack_full.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..31eecaec479efb777ccb45f70233834b688e2f4f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/pack_full.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=pack_full +#SBATCH --account=vision-pulkitag +#SBATCH --cpus-per-task=32 --mem=200G +#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 +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +PY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python +export PYTHONUNBUFFERED=1 +# --max-eps 0 = ALL 43,135 rollouts (the existing cache capped at 4,500 to fit a +# 110G --mem request; the a100/h200 nodes have 1-2 TB, so the cap is not binding) +$PY $G/pack.py \ + --src /data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1 \ + --demos /data/pulkitag/users/rli14/libero10_demo_ogpo_cache_srv \ + --out /data/pulkitag/scratch/rli14/rsm_libero_cache_full \ + --max-eps 0 --stride 1 --keep-all-demos --workers 32 +RC=$?; echo "[pack] rc=$RC $(date -u +%T)"; exit $RC diff --git a/frozen/rsm_libero_freeze_20261002/pack_full_r256.sbatch b/frozen/rsm_libero_freeze_20261002/pack_full_r256.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..b187808db5120af93bbb1a49360b0094694f2730 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/pack_full_r256.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=pack_full_r256 +#SBATCH --account=vision-pulkitag +#SBATCH --cpus-per-task=32 --mem=200G +#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 +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +PY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python +export PYTHONUNBUFFERED=1 +# ALL 43,135 rollouts (256-encoded, as the collector produced them) + the 500 demos +# re-rendered at 256. One latent space, the evaluator's. +$PY $G/pack.py \ + --src /data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1 \ + --demos /data/pulkitag/users/rli14/libero10_demo_ogpo_cache_r256 \ + --out /data/pulkitag/scratch/rli14/rsm_libero_cache/full_r256 \ + --max-eps 0 --stride 1 --keep-all-demos --workers 32 --cam-res 256 --episode-list /data/pulkitag/users/rli14/rsm_libero_cache/full_r256_episodes.txt +RC=$?; echo "[pack] rc=$RC $(date -u +%T)"; exit $RC diff --git a/frozen/rsm_libero_freeze_20261002/pack_r256.sbatch b/frozen/rsm_libero_freeze_20261002/pack_r256.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..190dd1d187299f0d504914e734af5790c981531e --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/pack_r256.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=pack_r256 +#SBATCH --account=vision-pulkitag +#SBATCH --cpus-per-task=32 --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.err +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +PY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python +export PYTHONUNBUFFERED=1 +# Same 4,500-rollout subset as full_demo (same seed + header cache) so per-episode +# artefacts (subgoal labels, verified mask) stay aligned by index; demos at 256. +$PY $G/pack.py \ + --src /data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1 \ + --demos /data/pulkitag/users/rli14/libero10_demo_ogpo_cache_r256 \ + --out /data/pulkitag/users/rli14/rsm_libero_cache/full_demo_r256 \ + --max-eps 4500 --stride 1 --keep-all-demos --workers 32 --cam-res 256 --seed 0 --header-cache /data/pulkitag/users/rli14/rsm_libero_cache/headers_v2.npz +RC=$?; echo "[pack] rc=$RC $(date -u +%T)"; exit $RC diff --git a/frozen/rsm_libero_freeze_20261002/paired_test.py b/frozen/rsm_libero_freeze_20261002/paired_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b441c5581e64006461e0c581f253bb9b3664c8 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/paired_test.py @@ -0,0 +1,55 @@ +"""Paired comparison of two closed-loop evals. + +Arms are paired by construction: the env seed depends only on (seed, tid, k), so two +arms run at the same SEED see identical initial conditions. This verifies that from the +recorded init_sha256 and then runs McNemar's exact test on the discordant pairs, which +is the correct test for paired binary outcomes. The unpaired two-proportion z-test used +elsewhere is conservative here and understates real differences. +""" +import json, sys +from math import comb + +def load(p): + """Key on (task, episode index), NOT on init_sha256. + + The env seed is a pure function of (seed, tid, k), so episode k is the same + initial condition in every arm run at the same SEED. init_sha256 hashes raw + float64 sim-state bytes and therefore differs between compute nodes for a + logically identical state, which made it useless as a join key.""" + r = json.load(open(p)) + out, sha = {}, {} + for task, eps in r["episodes_detail"].items(): + for e in eps: + out[(task, e["episode"])] = bool(e["success"]) + sha[(task, e["episode"])] = e.get("init_sha256") + return out, r["pooled_SR"], sha + +def mcnemar(b, c): + """two-sided exact binomial on the discordant pairs""" + n = b + c + if n == 0: + return 1.0 + k = min(b, c) + tail = sum(comb(n, i) for i in range(0, k + 1)) / (2 ** n) + return min(1.0, 2 * tail) + +A, srA, shA = load(sys.argv[1]) +B, srB, shB = load(sys.argv[2]) +shared = set(A) & set(B) +print(f" {sys.argv[1].split('/')[-1][:-5]:26s} SR {srA:.3f} n={len(A)}") +print(f" {sys.argv[2].split('/')[-1][:-5]:26s} SR {srB:.3f} n={len(B)}") +nsha = sum(1 for k in shared if shA.get(k) and shA[k] == shB.get(k)) +print(f" matched episodes: {len(shared)}/{min(len(A),len(B))}" + f" ({'PAIRED' if len(shared)==min(len(A),len(B)) else 'PARTIAL'})" + f" [identical init hash on {nsha}/{len(shared)}" + f"{'' if nsha==len(shared) else ' — rest differ only in float bits across nodes'}]") +if not shared: + print(" no shared inits; arms used different seeds"); raise SystemExit +b = sum(1 for k in shared if A[k] and not B[k]) +c = sum(1 for k in shared if B[k] and not A[k]) +agree = len(shared) - b - c +p = mcnemar(b, c) +d = srA - srB +print(f" concordant {agree} A-only {b} B-only {c}") +print(f" diff {d:+.3f} McNemar exact p = {p:.4g}" + f" {'SIGNIFICANT' if p < 0.05 else 'not significant'} at 0.05") diff --git a/frozen/rsm_libero_freeze_20261002/parl_rsm.py b/frozen/rsm_libero_freeze_20261002/parl_rsm.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb1a34c8995c9acbf5d00fb91e0404d42f98a42 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/parl_rsm.py @@ -0,0 +1,305 @@ +"""PARL with the RSM occupancy value: rank proposal samples by Q, distill the argmax. + +Faithful to the lane's PARL recipe (MaxSobolMark/PolicyAgnosticRL action +optimisation): sample N action chunks from a base proposal policy, rank them by +Q, keep the best, and distill those into a fresh head with the ordinary flow +loss. Our Q is the RSM occupancy read-out rather than a TD value. + +Why this is different from the Q-filtering already tried, and why that one was +handicapped: PARL's own note is that it "only helps if the proposal policy's N +samples are DIVERSE -- an overtrained flow collapses to the mean, so there is +nothing to rank". Our behaviour clones are trained 120k steps and then the +checkpoint is selected by BEST held-out sampled reconstruction MSE, which selects +precisely the most mean-collapsed checkpoint. Measured here as `proposal_std`, +which is reported before any distillation so a collapsed proposal is visible +rather than silently wasting the run. + +Selection uses depth 1 by default so the recursion never has to re-draw an action +in a latent the flow only imagined, which a raw-feature policy cannot be queried +for. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, make_policy, policy_nll, policy_features, \ + q_recursive, sampled_action_mse +from awr import offline_score + + +@torch.no_grad() +def proposal_diversity(pol, pfeat, d, rng, device, n_states=256, n_samp=16, + temp=1.0, sde=0.0): + """Mean per-dimension std across N samples at a FIXED state. + + This is the quantity PARL lives or dies on. A collapsed proposal gives the + ranker N copies of the same action and the argmax is then meaningless. + """ + b = d.sample_frames(n_states, rng, "val", device) + z = pfeat(b["x"]) + acts = torch.stack([pol.sample(z, b["task"], temp=temp, sde=sde) + for _ in range(n_samp)]) + return float(acts.std(0).mean()), float(b["a"].std()) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--proposal", required=True, help="base policy checkpoint") + ap.add_argument("--out", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--proposal-sde", type=float, default=0.0, + help="noise injected during integration. Unlike temp it " + "follows the learned drift, so candidates stay near " + "the manifold instead of being thrown off it.") + ap.add_argument("--proposal-temp", type=float, default=1.0, + help="scales the proposal's initial noise; >1 widens the " + "candidate set the value ranks over") + ap.add_argument("--n-actions", type=int, default=32, + help="candidates per state (PARL repo default 32)") + ap.add_argument("--select-pool", default="demos", + choices=["demos", "succ", "demos_succ", "all"], + help="states the distillation set is drawn from") + ap.add_argument("--qf-ckpt", default="", + help="rank with the SUPERVISED student Q from rsm_main.py " + "instead of the counterfactual-conditioned occupancy " + "read-out. The student is fit on real (s,a,s') " + "transitions and is the only reader measured to rank " + "actions correctly on this corpus.") + ap.add_argument("--num-keep", type=int, default=4, + help="keep the top-k candidates, not only the arg-max. " + "Distilling a single arg-max concentrates all of the " + "estimator's error into the target.") + ap.add_argument("--margin-quantile", type=float, default=0.7, + help="confidence GATE. Keep only states whose critic margin " + "(best minus median candidate) is above this quantile; " + "apply selection only where the value actually separates " + "candidates, and leave the rest to the anchor. 0 = off.") + ap.add_argument("--include-demos", type=int, default=1, + help="anchor the distillation set on (state, LOGGED demo " + "action) pairs alongside the selected ones. PA-RL's " + "distil set is selected pairs PLUS demonstrations; " + "without the anchor the student has nothing holding it " + "on the demonstration manifold.") + ap.add_argument("--distill-states", type=int, default=200000) + ap.add_argument("--distill-steps", type=int, default=60000) + ap.add_argument("--batch", type=int, default=1024) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=1) + ap.add_argument("--particles", type=int, default=8) + ap.add_argument("--q-pessimism", type=float, default=2.0) + ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"]) + ap.add_argument("--feat-scale", default="center", choices=["zscore", "center"]) + ap.add_argument("--policy-family", default="concat", + choices=["concat", "flow", "gauss"]) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--reward-mode", default="dense", choices=["dense", "terminal", "subgoal", "soft"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--proposal-sde-anneal", type=int, default=0, + help="1 = anneal --proposal-sde to zero by the last integration step") + ap.add_argument("--rank", default="critic", choices=["critic", "random"], + help="random = keep --num-keep random candidates (critic-free control)") + ap.add_argument("--hop-policy", default="", + help="latent-feature BC checkpoint for hops >= 2 (required if --depth > 1)") + ap.add_argument("--crn", type=int, default=1, + help="common random numbers across candidates when scoring") + ap.add_argument("--save-every", type=int, default=10000, + help="save policy_s.pt during distillation; policy_last.pt is always saved") + args = ap.parse_args() + + 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, + 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"] + qstud = qenc = None + if args.qf_ckpt: + 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(d.feat_dim, _c["d_z"], _c["enc_width"]).to(dev) + qenc.load_state_dict(_ck["enc"]); qenc.eval() + qstud = QStudent(_c["d_z"], _ck["d_act"], d.n_task).to(dev) + qstud.load_state_dict(_ck["qf"]); qstud.eval() + print(f"[parl] ranking with the SUPERVISED student Q " + f"(arrival AUC {_ck.get('arrival_auc', float('nan')):.4f})", flush=True) + pfeat, d_pol = policy_features(args, enc, d, cfg, dev) + hop = None + if args.depth > 1: + if not args.hop_policy: + raise SystemExit("--depth > 1 needs --hop-policy") + _hk = torch.load(args.hop_policy, map_location=dev, weights_only=False) + class _HA: pass + _ha = _HA(); [setattr(_ha, k, v) for k, v in _hk["config"].items()] + hop = make_policy(_ha, d, dev, d_z=cfg["d_z"]); hop.load_state_dict(_hk["pol"]); hop.eval() + print(f"[parl] hop policy loaded for depth {args.depth}", flush=True) + + pk = torch.load(args.proposal, map_location=dev, weights_only=False) + # the distilled head inherits the proposal's architecture (width/depth) + args.pol_width = int(pk["config"].get("pol_width", 1024) or 1024) + args.pol_depth = int(pk["config"].get("pol_depth", 4) or 4) + base = make_policy(args, d, dev, d_z=d_pol) + base.load_state_dict(pk["pol"]); base.eval() + + rng = np.random.default_rng(args.seed + 31) + std_a, std_data = proposal_diversity(base, pfeat, d, rng, dev, + temp=args.proposal_temp, + sde=args.proposal_sde) + print(f"[parl] proposal action std {std_a:.5f} vs data action std {std_data:.5f} " + f"(ratio {std_a / max(std_data, 1e-9):.3f})", flush=True) + if std_a < 0.02 * std_data: + print("[parl] WARNING: the proposal has collapsed to the mean; ranking " + "N copies of one action cannot improve anything", flush=True) + + ok = {"demos": d.ep_demo, "succ": d.ep_success, + "demos_succ": d.ep_demo | d.ep_success, + "all": np.ones(d.n_ep, bool)}[args.select_pool] + pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) + + # ---- build the distillation set: argmax_a Q(z, a) over N proposal draws ---- + xs, acts, tasks, margins = [], [], [], [] + got, bs = 0, 256 + sel = np.random.default_rng(args.seed + 41) + t_report = 0 + while got < args.distill_states: + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = sel.choice(pool, size=bs, p=w) + t = d.ep_from[e] + (sel.random(bs) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + with torch.no_grad(): + zc = enc(x) # critic latent for scoring + zp = pfeat(x) # policy features for proposing + cand = torch.stack([base.sample(zp, tk, temp=args.proposal_temp, + sde=args.proposal_sde, + sde_anneal=bool(args.proposal_sde_anneal)) + for _ in range(args.n_actions)]) + N, B, A = cand.shape + qs = [] + zq = qenc(x) if qstud is not None else None + _seed_i = int(args.seed * 1000003 + got) + for i in range(N): + if args.crn: + torch.manual_seed(_seed_i) # same MC noise for every candidate of this batch + if qstud is not None: + q = qstud(zq, cand[i], tk) + else: + q, _ = q_recursive(zc, cand[i], tk, rew=rew, flow=flow, rms=rms, + pol=hop, wend=None, beta=args.beta_q, + gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, + pessimism=args.q_pessimism) + qs.append(q) + Q = torch.stack(qs) # [N, B] + k = max(1, min(args.num_keep, Q.shape[0])) + if args.rank == "random": + topk = torch.stack([torch.randperm(N, device=dev)[:k] for _ in range(B)], 1) # [k, B] + else: + topk = Q.topk(k, dim=0).indices # [k, B] + # margin: how far the best candidate stands above the typical one. + # Small margin means the value does not separate the candidates here. + margin = Q.max(0).values - Q.median(0).values # [B] + ar = torch.arange(B, device=dev) + for j in range(k): + xs.append(x.cpu()); acts.append(cand[topk[j], ar].cpu()) + tasks.append(tk.cpu()); margins.append(margin.cpu()) + got += bs + if got - t_report >= 25600: + t_report = got + print(f"[parl] selected {got}/{args.distill_states}", flush=True) + X = torch.cat(xs); A_ = torch.cat(acts); T = torch.cat(tasks) + Mg = torch.cat(margins) + if args.margin_quantile > 0: + thr = torch.quantile(Mg, args.margin_quantile) + keep = Mg >= thr + print(f"[parl] margin gate q={args.margin_quantile} thr={float(thr):.4f} " + f"keeps {int(keep.sum())}/{len(keep)}", flush=True) + X, A_, T = X[keep], A_[keep], T[keep] + n_sel = len(X) + if args.include_demos: + # the anchor: raw (state, LOGGED action) pairs from demonstrations + dm = np.array([e for e in d.train_eps if d.ep_demo[e]], dtype=np.int64) + ax, aa, at = [], [], [] + need, dr = max(n_sel, 1), np.random.default_rng(args.seed + 51) + while sum(len(t) for t in ax) < need: + w = d.ep_len[dm].astype(np.float64); w /= w.sum() + e = dr.choice(dm, size=1024, p=w) + t = d.ep_from[e] + (dr.random(1024) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + ax.append(torch.from_numpy(d._feat(t))) + aa.append(torch.from_numpy(d._chunk_at(t, e))) + at.append(torch.from_numpy(d.ep_task[e]).long()) + X = torch.cat([X] + ax); A_ = torch.cat([A_] + aa); T = torch.cat([T] + at) + print(f"[parl] demo anchor: {len(X) - n_sel} demo pairs + {n_sel} selected " + f"= {len(X)} ({100.0 * (len(X) - n_sel) / len(X):.1f}% demo share)", + flush=True) + print(f"[parl] distillation set {tuple(X.shape)} from {args.select_pool}", flush=True) + + # ---- distill a FRESH head onto the selected actions ---- + new = make_policy(args, d, dev, d_z=d_pol) + opt = torch.optim.Adam(new.parameters(), lr=args.lr) + ev = np.random.default_rng(args.seed + 77) + best_mse, best_sd, best_step = float("inf"), None, 0 + for step in range(1, args.distill_steps + 1): + idx = torch.randint(0, len(X), (args.batch,)) + xb = X[idx].to(dev); ab = A_[idx].to(dev); tb = T[idx].to(dev) + loss = policy_nll(new, pfeat(xb), tb, ab) + opt.zero_grad(); loss.backward() + torch.nn.utils.clip_grad_norm_(new.parameters(), 1.0); opt.step() + if step % max(1, args.distill_steps // 20) == 0 or step == args.distill_steps: + new.eval() + m = sampled_action_mse(new, d, pfeat, ev, dev, ok) + new.train() + tag = "" + if m == m and m < best_mse: + best_mse, best_step = m, step + best_sd = {k: v.detach().clone() for k, v in new.state_dict().items()} + tag = " <- best" + print(f"[parl] distill {step} loss={float(loss):.4f} " + f"sampled_mse_vs_LOGGED={m:.5f}{tag}", flush=True) + if args.save_every and step % args.save_every == 0: + torch.save({"pol": new.state_dict(), "round": 1, "step": step, "config": vars(args), + "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")}, out / f"policy_s{step}.pt") + # The LAST distilled head is the deployable one: the logged-action MSE proxy selects + # AGAINST the Q-preferred actions PARL is supposed to move toward (and picked a + # checkpoint 0.10 SR below the last one for plain BC). policy_r1.pt keeps the + # proxy-best for comparison; select between them on validation inits. + torch.save({"pol": new.state_dict(), "round": 1, "step": args.distill_steps, "config": vars(args), + "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch"), + "note": "LAST distilled checkpoint"}, out / "policy_last.pt") + if best_sd is not None: + new.load_state_dict(best_sd) + new.eval() + + torch.save({"pol": new.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") + sc = offline_score(d, enc, new, np.random.default_rng(args.seed + 23), dev, + pfeat=pfeat) + sc["proposal_action_std"] = std_a + sc["data_action_std"] = std_data + # NOTE: sampled_mse against the LOGGED action is not the objective here -- a + # working PARL run should move AWAY from the logged action toward the + # Q-preferred one, so a higher value is expected and is not a failure. + (out / "parl.json").write_text(json.dumps( + {"config": vars(args), "score": sc, "best_distill_step": best_step}, + indent=2)) + print(f"[parl] {sc}", flush=True) + print("[parl] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/pooled_test.py b/frozen/rsm_libero_freeze_20261002/pooled_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d065243928d079355e8e9c12b1f8c7406992d23b --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/pooled_test.py @@ -0,0 +1,25 @@ +"""Pool paired McNemar counts across seeds. Each seed is an independent draw of +500 initial conditions on protocol B, so discordant pairs add.""" +import json, sys +from math import comb, sqrt, erfc +def counts(pa, pb): + def load(p): + r=json.load(open(p)); o={} + for t,eps in r["episodes_detail"].items(): + for e in eps: o[(t,e["episode"])]=bool(e["success"]) + return o, r["pooled_SR"] + A,sa=load(pa); B,sb=load(pb); sh=set(A)&set(B) + return (sum(1 for k in sh if A[k] and not B[k]), + sum(1 for k in sh if B[k] and not A[k]), len(sh), sa, sb) +B=C=N=0; srs=[] +for i in range(1,len(sys.argv),2): + b,c,n,sa,sb = counts(sys.argv[i], sys.argv[i+1]) + B+=b; C+=c; N+=n; srs.append((sa,sb)) + print(f" seed pair {i//2}: SR {sa:.3f} vs {sb:.3f} b={b} c={c} diff {sa-sb:+.3f}") +z=(B-C)/sqrt(B+C) if B+C else 0.0 +p=erfc(abs(z)/sqrt(2)) +msr=sum(a for a,_ in srs)/len(srs); mbs=sum(b for _,b in srs)/len(srs) +print(f"\n POOLED over {len(srs)} seeds, {N} paired episodes") +print(f" mean SR {msr:.3f} vs {mbs:.3f} diff {msr-mbs:+.3f}") +print(f" discordant b={B} c={C} z={z:.2f} p={p:.4f} " + f"{'SIGNIFICANT' if p<0.05 else 'NOT significant'} at 0.05") diff --git a/frozen/rsm_libero_freeze_20261002/probe_actcon.py b/frozen/rsm_libero_freeze_20261002/probe_actcon.py new file mode 100644 index 0000000000000000000000000000000000000000..f355db89470063931af07e049ed7548d0204881e --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_actcon.py @@ -0,0 +1,95 @@ +"""Which negative does the action-contrast term actually need? + +Two candidate negatives for the flow-matching error at a state z: + (A) shuffle the ACTION only (s, a_rand, s') <- what we implement + (B) shuffle the action AND the target (s, a_rand, s'_rand) + +(B) is the intuitive reading, but it confounds two effects. Its error is large +partly because the conditioning action is wrong and partly because the TARGET is +an unrelated future. A successor that ignores the action entirely still scores +well on (B), because predicting the true future from z is easy and predicting an +unrelated one is hard -- which is exactly the failure the term exists to prevent. + +This measures the decomposition on a trained critic: + e_pos true action, true target + e_act shuffled action, TRUE target -> isolates the action + e_both shuffled action, shuffled target -> action + target confounded + e_tgt TRUE action, shuffled target -> isolates the target +If (e_both - e_pos) is dominated by (e_tgt - e_pos), then (B) is mostly a +target-mismatch test and says little about action sensitivity. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta", type=float, default=0.90) + ap.add_argument("--batch", type=int, default=4096) + ap.add_argument("--reps", type=int, default=8) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + rng = np.random.default_rng(args.seed + 13) + acc = {k: 0.0 for k in ("pos", "act", "both", "tgt")} + with torch.no_grad(): + for _ in range(args.reps): + b = d.sample(args.batch, rng, args.beta, args.beta, "val", dev) + z = enc(b["x_now"]); zf = enc(b["x_fut"]) + y = (zf - z) / rms # true normalised residual + k = torch.rand(args.batch, device=dev) + noise = torch.randn_like(y) + x_k = (1 - k)[:, None] * y + k[:, None] * noise + u = y - noise + p = torch.randperm(args.batch, device=dev) + a_t, a_r = b["a_now"], b["a_now"][p] + # shuffled TARGET: rebuild the path from the permuted residual + y_r = y[p]; n_r = noise[p] + x_k_r = (1 - k)[:, None] * y_r + k[:, None] * n_r + u_r = y_r - n_r + + def err(a, xk, tgt): + return (flow(z, a, b["task"], b["beta"], xk, k) + - tgt).pow(2).mean(-1).mean() + acc["pos"] += float(err(a_t, x_k, u)) + acc["act"] += float(err(a_r, x_k, u)) # action only + acc["both"] += float(err(a_r, x_k_r, u_r)) # action + target + acc["tgt"] += float(err(a_t, x_k_r, u_r)) # target only + for kk in acc: + acc[kk] /= args.reps + print(f"\n{'negative':<34s} {'flow-matching error':>20s} {'gap vs true':>13s}") + print(f"{'(true action, true target)':<34s} {acc['pos']:20.5f} {0.0:13.5f}") + print(f"{'A: shuffled ACTION, true target':<34s} {acc['act']:20.5f} " + f"{acc['act'] - acc['pos']:+13.5f}") + print(f"{' true action, shuffled target':<34s} {acc['tgt']:20.5f} " + f"{acc['tgt'] - acc['pos']:+13.5f}") + print(f"{'B: shuffled action AND target':<34s} {acc['both']:20.5f} " + f"{acc['both'] - acc['pos']:+13.5f}") + ga, gb = acc["act"] - acc["pos"], acc["both"] - acc["pos"] + gt = acc["tgt"] - acc["pos"] + print(f"\naction-only gap as a share of the both-shuffled gap: " + f"{100.0 * ga / gb:.1f}%" if gb else "") + print(f"target-only gap as a share of the both-shuffled gap: " + f"{100.0 * gt / gb:.1f}%" if gb else "") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/probe_action_info.py b/frozen/rsm_libero_freeze_20261002/probe_action_info.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ed7896cb7a8e9a74f36919134390950265a6f4 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_action_info.py @@ -0,0 +1,97 @@ +"""Does the ACTION carry outcome information beyond the state, in this corpus? + +Everything in this lane hinges on it. The RSM Q takes its action dependence from +the occupancy model extrapolating to actions never observed at that state, which +is unsupervised in the action direction, and was measured to have arbitrary sign. +A directly supervised head has that dependence SUPERVISED by real outcomes. + +Two heads, same latent, same data, same budget, held-out AUC against episode +success: + V(z) state only + Q(z, a) state and the logged action chunk +If Q does not beat V, the action carries nothing beyond the state at this +granularity and NO critic of any kind can rank actions here -- the ceiling is the +data, not the model. If Q does beat V, the action signal exists and the defect is +the occupancy model's extrapolation, which is fixable. + +Reported on rollouts (which contain failures); demonstrations alone are almost +all successes and cannot answer the question. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch +import torch.nn.functional as F + +from data import LiberoRSMData +from is_ope import load_critic +from model import mlp +from train_rsm import auc + + +def train_head(d, enc, dev, use_action, steps, batch, lr, seed, tag): + torch.manual_seed(seed) + d_act = d.chunk * d.adim + din = 264 + (d_act if use_action else 0) + net = mlp([din, 1024, 1024, 1], norm=True).to(dev) + emb = torch.nn.Embedding(d.n_task, 0).to(dev) # task enters via the latent + opt = torch.optim.Adam(net.parameters(), lr=lr) + rng = np.random.default_rng(seed + 3) + for step in range(1, steps + 1): + b = d.sample_frames(batch, rng, "train", dev) + with torch.no_grad(): + z = enc(b["x"]) + x = torch.cat([z, b["a"]], -1) if use_action else z + loss = F.binary_cross_entropy_with_logits(net(x).squeeze(-1), b["succ"]) + opt.zero_grad(); loss.backward(); opt.step() + if step % max(1, steps // 5) == 0: + print(f" [{tag}] {step} bce={float(loss):.4f}", flush=True) + # held-out AUC against EPISODE success + net.eval() + ev = np.random.default_rng(seed + 77) + P, Y = [], [] + with torch.no_grad(): + for _ in range(8): + b = d.sample_frames(2048, ev, "val", dev) + z = enc(b["x"]) + x = torch.cat([z, b["a"]], -1) if use_action else z + P.append(torch.sigmoid(net(x).squeeze(-1)).cpu().numpy()) + Y.append(b["succ"].cpu().numpy()) + return float(auc(np.concatenate(P), np.concatenate(Y))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--steps", type=int, default=20000) + ap.add_argument("--batch", type=int, default=1024) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, _r, _f, _rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + print(f"[probe] corpus success rate {float(d.ep_success.mean()):.3f}", flush=True) + a_v = train_head(d, enc, dev, False, args.steps, args.batch, args.lr, + args.seed, "V(z)") + a_q = train_head(d, enc, dev, True, args.steps, args.batch, args.lr, + args.seed, "Q(z,a)") + print(f"\nheld-out AUC vs episode success") + print(f" V(z) state only {a_v:.4f}") + print(f" Q(z,a) state and action {a_q:.4f}") + print(f" delta {a_q - a_v:+.4f}") + print("\ndelta ~ 0 means the action adds nothing beyond the state at this " + "granularity, and no critic can rank actions on this corpus.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/probe_crn.py b/frozen/rsm_libero_freeze_20261002/probe_crn.py new file mode 100644 index 0000000000000000000000000000000000000000..085b28516f2b3b3b5f36c991953ae86653062de2 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_crn.py @@ -0,0 +1,105 @@ +"""Is Q blind to the action, or is its ESTIMATOR too noisy to see the action? + +q_recursive draws fresh flow noise on every call, so comparing Q(a1) with Q(a2) +compares two noisy Monte-Carlo estimates. If the per-call noise is larger than the +effect an action has, the comparison is pure coin-flip -- which is exactly what +probe_perturb saw (expert wins 0.483-0.508, mean Q moving 1% when the action is +destroyed). That is equally consistent with "Q ignores the action" and with "the +estimator cannot resolve the action". + +This separates them: + repeat noise |Q(a) - Q'(a)| same action, INDEPENDENT noise + paired effect |Q(a) - Q(a+e)| different action, COMMON noise (CRN) +If the paired effect is comparable to or larger than the repeat noise, the signal +is there and was being drowned; common random numbers recover it. If the paired +effect is ~0 under CRN, the model genuinely ignores the action. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic +from train_rsm import sample_future + + +def q_fixed_noise(enc_z, a, tk, *, rew, flow, rms, beta, gamma, n_particles, + flow_steps, noise): + """Q with the flow's initial noise SUPPLIED, so candidates share it.""" + B, D = enc_z.shape + z = enc_z.repeat_interleave(n_particles, 0) + aa = a.repeat_interleave(n_particles, 0) + t = tk.repeat_interleave(n_particles, 0) + bq = torch.full((z.shape[0],), beta, device=z.device) + x = noise.clone() + for s in range(flow_steps): + k = torch.full((z.shape[0],), 1.0 - s / flow_steps, device=z.device) + x = x + flow(z, aa, t, bq, x, k) / flow_steps + z_end = z + x * rms + r = torch.sigmoid(rew(z_end, t)).view(B, n_particles) + return r.mean(1) / (1 - gamma) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--flow-steps", type=int, default=8) + ap.add_argument("--n", type=int, default=1024) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + pool = np.array([e for e in d.val_eps if d.ep_demo[e]], dtype=np.int64) + if not len(pool): + pool = np.array([e for e in d.train_eps if d.ep_demo[e]], dtype=np.int64) + rng = np.random.default_rng(args.seed + 9) + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = rng.choice(pool, size=args.n, p=w) + t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + + with torch.no_grad(): + z = enc(x) + D = z.shape[1] + kw = dict(rew=rew, flow=flow, rms=rms, beta=args.beta_q, gamma=args.gamma, + n_particles=args.particles, flow_steps=args.flow_steps) + n1 = torch.randn(args.n * args.particles, D, device=dev) + n2 = torch.randn(args.n * args.particles, D, device=dev) + q_a = q_fixed_noise(z, a0, tk, noise=n1, **kw) + q_b = q_fixed_noise(z, a0, tk, noise=n2, **kw) + repeat = (q_a - q_b).abs().mean() + print(f"repeat noise, same action different noise : {float(repeat):.5f}") + print(f"{'noise':>7s} {'|dQ| CRN':>10s} {'expert wins CRN':>16s} " + f"{'|dQ|/repeat':>12s}") + for sig in (0.1, 0.2, 0.4, 0.8): + q_p = q_fixed_noise(z, a0 + sig * torch.randn_like(a0), tk, + noise=n1, **kw) # COMMON noise + dq = (q_a - q_p) + win = float((dq > 0).float().mean()) + print(f"{sig:7.2f} {float(dq.abs().mean()):10.5f} {win:16.3f} " + f"{float(dq.abs().mean() / repeat.clamp_min(1e-9)):12.2f}", + flush=True) + print("\nexpert wins CRN > 0.5 means the model DOES prefer the expert action " + "once the shared noise is removed.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/probe_inits.py b/frozen/rsm_libero_freeze_20261002/probe_inits.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf86c1210f2a7a2f284d115f6b748adcb17496c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_inits.py @@ -0,0 +1,46 @@ +"""Characterise the two initial-condition distributions the evaluator can use. + +Protocol A replays LIBERO's 50 stored init states; protocol B lets the task's BDDL +placement region resample. Both are full sim-state vectors, so they are directly +comparable. Reports, per task, how much each distribution actually spreads and +whether A's 50 states are a subset of B's support. +""" +import os, sys, numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from libero.libero import benchmark, get_libero_path +from libero.libero.envs import OffScreenRenderEnv +from pathlib import Path + +bench = benchmark.get_benchmark_dict()["libero_10"]() +rows = [] +for tid in range(10): + task = bench.get_task(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) + inits = np.asarray(bench.get_task_init_states(tid)) # protocol A + fresh = [] + for k in range(50): # protocol B, eval seeds + env.seed(0 * 100003 + tid * 1009 + k) + env.reset() + fresh.append(np.asarray(env.env.sim.get_state().flatten())) + fresh = np.stack(fresh) + n = min(inits.shape[1], fresh.shape[1]) + A, B = inits[:, :n], fresh[:, :n] + # dims that actually vary in either protocol = the randomised object DoF + var = (A.std(0) > 1e-6) | (B.std(0) > 1e-6) + sa, sb = A[:, var].std(0), B[:, var].std(0) + # is every stock state inside the fresh support? + lo, hi = B[:, var].min(0), B[:, var].max(0) + inside = ((A[:, var] >= lo - 1e-6) & (A[:, var] <= hi + 1e-6)).all(1).mean() + rows.append((tid, task.name[:34], int(var.sum()), sa.mean(), sb.mean(), inside)) + print(f"t{tid} {task.name[:34]:34s} varying_dof={int(var.sum()):3d} " + f"std_stock={sa.mean():.4f} std_fresh={sb.mean():.4f} " + f"stock_inside_fresh_support={inside:.2f}", flush=True) + env.close() +print() +print(f"MEAN std_stock={np.mean([r[3] for r in rows]):.4f} " + f"std_fresh={np.mean([r[4] for r in rows]):.4f} " + f"ratio={np.mean([r[4] for r in rows])/max(np.mean([r[3] for r in rows]),1e-9):.2f}x " + f"stock_inside={np.mean([r[5] for r in rows]):.2f}") diff --git a/frozen/rsm_libero_freeze_20261002/probe_inits.sbatch b/frozen/rsm_libero_freeze_20261002/probe_inits.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..8f380172f6aceae582026565487b28ee2bf5598c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_inits.sbatch @@ -0,0 +1,17 @@ +#!/bin/bash +#SBATCH --job-name=probe_inits +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=4 +#SBATCH --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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +PY=$B/venvs/rlinf-libero-eval-venv/bin/python +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl PYTHONUNBUFFERED=1 +_G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)" +export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G" +$PY /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/probe_inits.py diff --git a/frozen/rsm_libero_freeze_20261002/probe_inits2.py b/frozen/rsm_libero_freeze_20261002/probe_inits2.py new file mode 100644 index 0000000000000000000000000000000000000000..a75d29fe0353eb974d93872c4bd35f92ff6135d6 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_inits2.py @@ -0,0 +1,39 @@ +"""Exactly what each protocol randomises: per-DoF comparison + the sampler ranges.""" +import os, sys, numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from libero.libero import benchmark, get_libero_path +from libero.libero.envs import OffScreenRenderEnv +from pathlib import Path + +bench = benchmark.get_benchmark_dict()["libero_10"]() +for tid in [0, 3]: + task = bench.get_task(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) + print(f"\n===== t{tid} {task.name} =====") + pi = env.env.placement_initializer + for smp in getattr(pi, "samplers", {}).values() if hasattr(pi, "samplers") else []: + xr = getattr(smp, "x_range", None); yr = getattr(smp, "y_range", None) + rot = getattr(smp, "rotation", None) + if xr is None: continue + xs = float(np.ptp(np.asarray(xr))); ys = float(np.ptp(np.asarray(yr))) + print(f" sampler {smp.name[:38]:38s} x-span {xs*100:6.2f} cm y-span {ys*100:6.2f} cm rot {rot}") + inits = np.asarray(bench.get_task_init_states(tid)) + fresh = [] + for k in range(50): + env.seed(tid*1009 + k); env.reset() + fresh.append(np.asarray(env.env.sim.get_state().flatten())) + fresh = np.stack(fresh) + n = min(inits.shape[1], fresh.shape[1]); A, B = inits[:, :n], fresh[:, :n] + va, vb = A.std(0) > 1e-6, B.std(0) > 1e-6 + both, only_a, only_b = va & vb, va & ~vb, vb & ~va + print(f" DoF varying in BOTH: {both.sum():3d} stdA {A[:,both].std(0).mean():.4f} " + f"stdB {B[:,both].std(0).mean():.4f}") + print(f" DoF varying in STOCK ONLY (A randomises, B holds fixed): {only_a.sum():3d}" + f" stdA {A[:,only_a].std(0).mean() if only_a.any() else 0:.4f}") + print(f" DoF varying in FRESH ONLY: {only_b.sum():3d}") + nq = env.env.sim.model.nq + print(f" (nq={nq}; robot joints are the first ~7-9 dims, objects are free joints after)") + env.close() diff --git a/frozen/rsm_libero_freeze_20261002/probe_inits2.sbatch b/frozen/rsm_libero_freeze_20261002/probe_inits2.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..449ab30216af74856425de93022034bb35c9246b --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_inits2.sbatch @@ -0,0 +1,15 @@ +#!/bin/bash +#SBATCH --job-name=probe_inits2 +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 --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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl PYTHONUNBUFFERED=1 +_G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)" +export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G" +$B/venvs/rlinf-libero-eval-venv/bin/python \ + /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/probe_inits2.py diff --git a/frozen/rsm_libero_freeze_20261002/probe_perturb.py b/frozen/rsm_libero_freeze_20261002/probe_perturb.py new file mode 100644 index 0000000000000000000000000000000000000000..cc8552cafa865f8bb464f69f537cacbd8654bbbb --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_perturb.py @@ -0,0 +1,81 @@ +"""Does Q prefer the EXPERT action over noisy perturbations of it? + +This is the question PARL actually asks, and it has unambiguous ground truth: on +a demonstration frame the logged chunk IS the good action, and adding noise can +only make it worse. The earlier action-gap probe compared the logged action +against a DIFFERENT episode's action, which is dominated by on-support versus +off-support and says little about ranking candidates near the mode. + +Reports, per noise scale: the fraction of states where Q ranks the expert action +above the perturbed one, and mean Q as a function of noise. If mean Q RISES with +noise the critic is inverted, and the fix is a sign, not more training. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, q_recursive + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=1) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--n", type=int, default=1024) + ap.add_argument("--pool", default="demos", choices=["demos", "succ", "all"]) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--pessimism", type=float, default=0.0) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + ok = {"demos": d.ep_demo, "succ": d.ep_success, + "all": np.ones(d.n_ep, bool)}[args.pool] + pool = np.array([e for e in d.val_eps if ok[e]], dtype=np.int64) + if not len(pool): + pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) + rng = np.random.default_rng(args.seed + 9) + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = rng.choice(pool, size=args.n, p=w) + t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + + def Q(a): + q, _ = q_recursive(enc(x), a, tk, rew=rew, flow=flow, rms=rms, pol=None, + wend=None, beta=args.beta_q, gamma=args.gamma, + depth=args.depth, n_particles=args.particles, + use_is=False, pessimism=args.pessimism) + return q + + with torch.no_grad(): + q0 = Q(a0) + print(f"expert action: mean Q {float(q0.mean()):+.5f}", flush=True) + print(f"{'noise':>7s} {'mean Q':>10s} {'expert wins':>12s}") + for sig in (0.05, 0.1, 0.2, 0.4, 0.8): + qn = Q(a0 + sig * torch.randn_like(a0)) + win = float((q0 > qn).float().mean()) + print(f"{sig:7.2f} {float(qn.mean()):+10.5f} {win:12.3f}", flush=True) + print("\nexpert wins > 0.5 = the critic prefers the expert action.", flush=True) + print("mean Q RISING with noise = the critic is inverted.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/probe_pessimism.py b/frozen/rsm_libero_freeze_20261002/probe_pessimism.py new file mode 100644 index 0000000000000000000000000000000000000000..13a8593b4e34a92bacaea1502954a2f7fda91059 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_pessimism.py @@ -0,0 +1,73 @@ +"""Does a disagreement penalty fix the critic's inverted action ranking? + +Measures the held-out action win rate -- how often Q ranks the action actually +taken above a different action taken in the SAME task -- as a function of the +pessimism coefficient. Within-task negatives on purpose: cross-task negatives +measure support violation, not preference. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, train_bc, policy_features + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=3) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--n", type=int, default=1024) + ap.add_argument("--batch", type=int, default=256) + ap.add_argument("--bc-steps", type=int, default=4000) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--policy-family", default="concat") + args = ap.parse_args() + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense") + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + args.d_z = cfg["d_z"] + # continuation policy in the critic's latent space, as the recursion needs + cont = train_bc(d, enc, args, dev, only_success=True, steps=args.bc_steps) + + rng = np.random.default_rng(args.seed + 5) + b = d.sample_frames(args.n, rng, "val", dev) + # within-task negative: another frame's action chunk from the SAME task + task = b["task"].cpu().numpy() + perm = np.arange(len(task)) + for t in np.unique(task): + idx = np.where(task == t)[0] + perm[idx] = rng.permutation(idx) + a_neg = b["a"][torch.from_numpy(perm).to(dev)] + + with torch.no_grad(): + z = enc(b["x"]) + print(f"{'pessimism':>10s} {'win rate':>9s} {'gap':>10s}") + for pe in (0.0, 0.5, 1.0, 2.0, 4.0): + qp, _ = q_recursive(z, b["a"], b["task"], rew=rew, flow=flow, rms=rms, + pol=cont, wend=None, beta=args.beta_q, + gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, + pessimism=pe) + qn, _ = q_recursive(z, a_neg, b["task"], rew=rew, flow=flow, rms=rms, + pol=cont, wend=None, beta=args.beta_q, + gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, + pessimism=pe) + win = float((qp > qn).float().mean()) + print(f"{pe:10.1f} {win:9.3f} {float((qp - qn).mean()):+10.5f}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/probe_qf.py b/frozen/rsm_libero_freeze_20261002/probe_qf.py new file mode 100644 index 0000000000000000000000000000000000000000..a8dc50e5a32e27c176decf45a7882b480d8707e5 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/probe_qf.py @@ -0,0 +1,76 @@ +"""Does main's SUPERVISED student Q rank actions where our counterfactual Q cannot? + +Same test as probe_perturb/probe_crn, applied to qf(z,a) from rsm_main.py. qf is +fit by regression onto r + gamma(1-done)V(s') using the REAL logged s', so its +action dependence is supervised rather than extrapolated. It is also +deterministic, so there is no sampling noise to cancel -- the comparison is exact. + +expert wins > 0.5 means it prefers the expert chunk over a perturbation of it. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from model import Encoder +from rsm_main import QStudent + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--ckpt", required=True) + ap.add_argument("--n", type=int, default=2048) + ap.add_argument("--pool", default="demos", choices=["demos", "succ", "all"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + dev = "cuda" + ck = torch.load(args.ckpt, map_location=dev, weights_only=False) + c = ck["config"] + d = LiberoRSMData(args.cache, chunk=c["chunk"], k_success=c["k_success"], + seed=args.seed, in_ram=bool(args.in_ram), + reward_mode="terminal", norm_pool=c["norm_pool"]) + enc = Encoder(d.feat_dim, c["d_z"], c["enc_width"]).to(dev) + enc.load_state_dict(ck["enc"]); enc.eval() + qf = QStudent(c["d_z"], ck["d_act"], d.n_task).to(dev) + qf.load_state_dict(ck["qf"]); qf.eval() + + ok = {"demos": d.ep_demo, "succ": d.ep_success, + "all": np.ones(d.n_ep, bool)}[args.pool] + pool = np.array([e for e in d.val_eps if ok[e]], dtype=np.int64) + if not len(pool): + pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) + rng = np.random.default_rng(args.seed + 9) + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = rng.choice(pool, size=args.n, p=w) + t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + + with torch.no_grad(): + z = enc(x) + q0 = qf(z, a0, tk) + print(f"expert chunk: mean Q {float(q0.mean()):+.4f} sd {float(q0.std()):.4f}") + print(f"{'noise':>7s} {'mean Q':>10s} {'expert wins':>12s} {'mean dQ':>10s}") + for sig in (0.05, 0.1, 0.2, 0.4, 0.8): + qn = qf(z, a0 + sig * torch.randn_like(a0), tk) + print(f"{sig:7.2f} {float(qn.mean()):+10.4f} " + f"{float((q0 > qn).float().mean()):12.3f} " + f"{float((q0 - qn).mean()):+10.4f}", flush=True) + # in-support control: a real chunk from a DIFFERENT frame of the same task + tt = tk.cpu().numpy(); perm = np.arange(len(tt)) + for task in np.unique(tt): + idx = np.where(tt == task)[0] + perm[idx] = rng.permutation(idx) + qo = qf(z, a0[torch.from_numpy(perm).to(dev)], tk) + print(f"\nwithin-task other real chunk: expert wins " + f"{float((q0 > qo).float().mean()):.3f}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/proposer_bias_diag.py b/frozen/rsm_libero_freeze_20261002/proposer_bias_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..b1a52ecbfa1ec085e54a8bf0e78f470754e547b0 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/proposer_bias_diag.py @@ -0,0 +1,105 @@ +"""Does the critic prefer one PROPOSER's action style regardless of state? + +At held-out frames, grouped by where they come from (demo episodes, successful +rollouts, failed rollouts), draw N chunks from the BC-demos policy and N from the +BC-successes policy and score every chunk with the same recursive Q the closed-loop +mixed arms use. Reports, per frame source: mean Q by proposer, how often the +arg-max over the 2N pool lands on a successes chunk, and the Q of the logged action. + +A critic that evaluates ACTIONS should prefer neither proposer on the demo frames +(where the demos policy is at home) in particular. A critic that identifies the +POLICY from the action style prefers the successes proposer everywhere, because the +demos are <1% of the frames it was fit on. + +usage: proposer_bias_diag.py --cache ... --critic ... --hop-policy ... --pol1 + --pol2 [--n 8 --frames 512 --beta 0.95 --depth 3 --particles 16] +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +import numpy as np +import torch +from data import LiberoRSMData +from is_ope import load_critic, make_policy, policy_features, q_recursive + + +def load_pol(path, d, dev, d_pol): + pk = torch.load(path, map_location=dev, weights_only=False) + class _A: pass + a = _A(); [setattr(a, k, v) for k, v in pk["config"].items()] + a.pol_width = int(pk["config"].get("pol_width", 1024) or 1024) + a.pol_depth = int(pk["config"].get("pol_depth", 4) or 4) + pol = make_policy(a, d, dev, d_z=d_pol); pol.load_state_dict(pk["pol"]); pol.eval() + return pol + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) + ap.add_argument("--hop-policy", default=""); ap.add_argument("--pol1", required=True) + ap.add_argument("--pol2", required=True); ap.add_argument("--out", required=True) + ap.add_argument("--n", type=int, default=8); ap.add_argument("--frames", type=int, default=512) + ap.add_argument("--beta", type=float, default=0.95); ap.add_argument("--gamma", type=float, default=0.98) + ap.add_argument("--depth", type=int, default=3); ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--norm-pool", default="all"); ap.add_argument("--reward-mode", default="dense") + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=10, seed=0, in_ram=False, reward_mode=args.reward_mode, + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + enc.eval() + class _P: pass + _p = _P(); _p.policy_features = "raw" + pfeat, d_pol = policy_features(_p, enc, d, cfg, dev) + hop = None + if args.hop_policy: + hop = load_pol(args.hop_policy, d, dev, cfg["d_z"]) + pol1 = load_pol(args.pol1, d, dev, d_pol); pol2 = load_pol(args.pol2, d, dev, d_pol) + rng = np.random.default_rng(args.seed) + val = d.val_eps + groups = {"demo": val[d.ep_demo[val]], + "roll_succ": val[d.ep_success[val] & ~d.ep_demo[val]], + "roll_fail": val[~d.ep_success[val] & ~d.ep_demo[val]]} + res = {} + for g, eps in groups.items(): + if len(eps) == 0: + continue + e = rng.choice(eps, size=args.frames, replace=True) + t = d.ep_from[e] + (rng.random(args.frames) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + a_log = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(args.frames, -1) + with torch.no_grad(): + zc = enc(x); zp = pfeat(x) + c1 = torch.stack([pol1.sample(zp, tk) for _ in range(args.n)]) + c2 = torch.stack([pol2.sample(zp, tk) for _ in range(args.n)]) + cand = torch.cat([c1, c2, a_log[None]], 0) # [2N+1, B, A] + qs = [] + for i in range(cand.shape[0]): + torch.manual_seed(args.seed * 7919 + 1) # CRN across candidates + q, _ = q_recursive(zc, cand[i], tk, rew=rew, flow=flow, rms=rms, pol=hop, + wend=None, beta=args.beta, gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, pessimism=0.0) + qs.append(q) + Q = torch.stack(qs).cpu().numpy() # [2N+1, B] + q1, q2, ql = Q[:args.n], Q[args.n:2 * args.n], Q[-1] + am = Q[:2 * args.n].argmax(0) + # action-style distance: how far each proposer's chunks sit from the logged one + d1 = (c1 - a_log[None]).pow(2).mean(-1).sqrt().mean().item() + d2 = (c2 - a_log[None]).pow(2).mean(-1).sqrt().mean().item() + r = {"frames": int(args.frames), "mean_q_demoBC": float(q1.mean()), "mean_q_succBC": float(q2.mean()), + "mean_q_logged": float(ql.mean()), "argmax_is_succBC": float((am >= args.n).mean()), + "frac_frames_succ_mean_higher": float((q2.mean(0) > q1.mean(0)).mean()), + "within_demoBC_std": float(q1.std(0).mean()), "within_succBC_std": float(q2.std(0).mean()), + "rms_dist_to_logged_demoBC": d1, "rms_dist_to_logged_succBC": d2, + "mean_r_at_frame": float(d.r[t].mean())} + res[g] = r + print(f"[bias] {g:10s} " + " ".join(f"{k}={v:.3f}" for k, v in r.items() if isinstance(v, float)), flush=True) + json.dump({"args": vars(args), "res": res}, open(args.out, "w"), indent=1) + print("[bias] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/q_vs_return_diag.py b/frozen/rsm_libero_freeze_20261002/q_vs_return_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..0c6ade5b3d36fb8c578d79b66bd86c85367d5a33 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/q_vs_return_diag.py @@ -0,0 +1,85 @@ +"""Policy-evaluation quality of the critics on HELD-OUT logged (state, action) pairs: +Spearman / Pearson between each estimated Q(s,a) and the logged discounted return G_t. + G_sub = (1-g) * sum_k g^k r_{t+k} r = per-frame BDDL subgoal fraction (dense) + G_succ = g^(steps to success) if the episode succeeds else 0 (sparse, terminal) +Arms: RSM restart-Q at depth 1 and 3 (16 particles, shared noise), RSM depth 1 with 256 +particles, the IQL Q trained on the same latent, the reward head alone r_hat(z_t) (no +future), and the per-task constant (the null every pooled correlation has to beat). +Pooled AND within-task (mean of per-task Spearman) are reported: pooled rank correlation +is dominated by task identity (tasks differ in mean subgoal fraction). +usage: q_vs_return_diag.py --cache C --critic ckpt --subgoal-dir D --mask M [--iql iql_q.pt] [--hop hop.pt]""" +import argparse, os, sys, numpy as np, torch +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, make_policy +from scipy.stats import spearmanr, pearsonr + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) +ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="") +ap.add_argument("--iql", default=""); ap.add_argument("--hop", default="") +ap.add_argument("--n", type=int, default=6000); ap.add_argument("--gamma", type=float, default=0.99) +ap.add_argument("--beta", type=float, default=0.98) +a = ap.parse_args() +dev = "cuda" if torch.cuda.is_available() else "cpu" +d = LiberoRSMData(a.cache, chunk=10, seed=0, in_ram=False, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, + success_mask=a.mask, norm_pool="demos") +enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d) +hop = None +if a.hop: + hk = torch.load(a.hop, map_location=dev, weights_only=False) + class _A: pass + ha = _A(); [setattr(ha, k, v) for k, v in hk["config"].items()] + hop = make_policy(ha, d, dev, d_z=cfg["d_z"]); hop.load_state_dict(hk["pol"]); hop.eval() +qnet = None +if a.iql: + from iql import QNet + ck = torch.load(a.iql, map_location=dev, weights_only=False) + qnet = QNet(ck["d_z"], ck["d_act"], ck["n_task"]).to(dev); qnet.load_state_dict(ck["q"]); qnet.eval() +rng = np.random.default_rng(0) +g = a.gamma +# ---- sample held-out frames with their logged action chunk and compute logged returns +eps = d.val_eps; w = d.ep_len[eps].astype(np.float64); w /= w.sum() +e = rng.choice(eps, size=a.n, p=w) +t = d.ep_from[e] + (rng.random(a.n) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64) +G_sub = np.zeros(a.n); G_succ = np.zeros(a.n); to_end = np.zeros(a.n) +for i in range(a.n): + lo, hi = int(t[i]), int(d.ep_to[e[i]]) + rr = np.asarray(d.r[lo:hi], np.float64); k = np.arange(len(rr)) + G_sub[i] = (1 - g) * float((g ** k * rr).sum()) + G_succ[i] = (g ** (hi - lo)) if bool(d.ep_success[e[i]]) else 0.0 + to_end[i] = hi - lo +x = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev) +act = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(a.n, -1) +res = {} +with torch.no_grad(): + z = enc(x) + res["reward head r_hat(z_t) (no future)"] = torch.sigmoid(rew(z, tk)).cpu().numpy() + def rsm(depth, part, crn=True): + out = [] + for i in range(0, a.n, 256): + q, _ = q_recursive(z[i:i+256], act[i:i+256], tk[i:i+256], rew=rew, flow=flow, rms=rms, pol=hop, wend=None, + beta=a.beta, gamma=g, depth=depth, n_particles=part, use_is=False, crn=crn) + out.append(q.cpu()) + return torch.cat(out).numpy() + res["RSM depth 1, 16 particles"] = rsm(1, 16) + res["RSM depth 1, 256 particles"] = rsm(1, 256) + if hop is not None: + res["RSM depth 3, 16 particles"] = rsm(3, 16) + res["RSM depth 3, 256 particles"] = rsm(3, 256) + if qnet is not None: + res["IQL Q(z,a)"] = qnet(z, act, tk).squeeze(-1).cpu().numpy() +tk_np = tk.cpu().numpy() +res["per-task constant (null)"] = np.array([G_sub[tk_np == tt].mean() for tt in tk_np]) +def report(name, q): + rows = [] + for gname, G in (("G_sub", G_sub), ("G_succ", G_succ)): + sp = spearmanr(q, G).correlation; pe = pearsonr(q, G)[0] + wt = [spearmanr(q[tk_np == tt], G[tk_np == tt]).correlation for tt in range(d.n_task) if (tk_np == tt).sum() > 30] + wt = [v for v in wt if v == v] + rows.append(f"{gname}: spearman {sp:+.3f} pearson {pe:+.3f} within-task spearman {np.mean(wt):+.3f}") + print(f"{name:36} | " + " | ".join(rows), flush=True) +print(f"held-out frames n={a.n} from {len(eps)} val episodes; mean G_sub={G_sub.mean():.3f} mean G_succ={G_succ.mean():.3f}") +for k, v in res.items(): + report(k, np.asarray(v, np.float64)) +print("[diag] DONE") diff --git a/frozen/rsm_libero_freeze_20261002/recheck128_cpu.sbatch b/frozen/rsm_libero_freeze_20261002/recheck128_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f7ad1280f16c095baf2ca5d548765e99e191f872 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/recheck128_cpu.sbatch @@ -0,0 +1,32 @@ +#!/bin/bash +#SBATCH --job-name=recheck128 +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export 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=osmesa +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export 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/recheck_encoding.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --n-ep 6 --frames 4 --pool rollsucc --src-res 128 --flips none + +echo "[cap] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_freeze_20261002/recheckD_cpu.sbatch b/frozen/rsm_libero_freeze_20261002/recheckD_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..6c16f87851322228a6b5fcb2c7cba2ad91747774 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/recheckD_cpu.sbatch @@ -0,0 +1,32 @@ +#!/bin/bash +#SBATCH --job-name=recheckD +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export 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=osmesa +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export 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/recheck_encoding.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --n-ep 6 --frames 4 --pool demos + +echo "[cap] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_freeze_20261002/recheck_cpu.sbatch b/frozen/rsm_libero_freeze_20261002/recheck_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f44b969cbb26f1766f0bec36775f8fe7c8ccb3df --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/recheck_cpu.sbatch @@ -0,0 +1,32 @@ +#!/bin/bash +#SBATCH --job-name=recheck +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export 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=osmesa +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export 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/recheck_encoding.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --n-ep 6 --frames 4 + +echo "[cap] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_freeze_20261002/recheck_encoding.py b/frozen/rsm_libero_freeze_20261002/recheck_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..80d1cb52af890616d1ea25d6a38b82afb8816021 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/recheck_encoding.py @@ -0,0 +1,157 @@ +"""Was the ROLLOUT cache built with the same image preprocessing as the evaluator? + +Hypothesis 2 of williamd4112/gen_q#251. The demo cache and the rollout cache have +different producers, and demo frames sit 48.7-61.5 from the nearest rollout frame +against 7.5-9.2 within the rollout cloud. `to224`'s own docstring records that uint8 +quantisation alone moves the latent 3 sigma on the dimensions that matter and cost a +working policy 0.46 -> 0/50, with cosine similarity 0.999898 hiding it completely. + +So: take a rollout episode's OWN raw frames (the parquets carry `image` and +`wrist_image`), push them through the EVALUATOR's exact path, and compare against that +frame's cached latent. Agreement means the rollout cache matches the evaluator and the +support gap is real scene difference. Disagreement means every rollout latent is in a +space the evaluator never produces, and no policy or critic trained on them can be read +online. + +Reports L2 in z-scored feature units, so the numbers are directly comparable to the +48.7-61.5 / 7.5-9.2 gap measured in #251 -- cosine similarity is deliberately NOT the +headline for the reason above. +""" +from __future__ import annotations +import argparse, importlib.util, io, os, re, sys +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from eval_closed_loop import to224, BUILDER + +_spec = importlib.util.spec_from_file_location("ogpo_rc", BUILDER) +ogpo = importlib.util.module_from_spec(_spec) +sys.modules["ogpo_rc"] = ogpo +_spec.loader.exec_module(ogpo) + +PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$") +PQ_ROOT = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1" + + +def decode(cell): + """Parquet image cell -> HxWx3 uint8. LeRobot stores either raw bytes (PNG/JPEG) + or a nested list; handle both rather than guessing.""" + v = cell.as_py() if hasattr(cell, "as_py") else cell + if isinstance(v, dict) and "bytes" in v: + v = v["bytes"] + if isinstance(v, (bytes, bytearray)): + from PIL import Image + return np.asarray(Image.open(io.BytesIO(v)).convert("RGB"), np.uint8) + a = np.asarray(v) + if a.dtype != np.uint8: + a = (a * 255).round().clip(0, 255).astype(np.uint8) if a.max() <= 1.001 else a.astype(np.uint8) + if a.ndim == 1: + n = int(round((a.size / 3) ** 0.5)); a = a.reshape(n, n, 3) + if a.ndim == 3 and a.shape[0] == 3: + a = a.transpose(1, 2, 0) + return a + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--n-ep", type=int, default=6) + ap.add_argument("--frames", type=int, default=4, help="frames checked per episode") + ap.add_argument("--pool", default="rollsucc", choices=["rollsucc", "demos"], + help="demos re-encodes from the LIBERO hdf5 (agentview_rgb / " + "eye_in_hand_rgb); the demo cache's npz holds no images") + ap.add_argument("--src-res", type=int, default=0, + help="resize the source image to this square resolution BEFORE " + "to224, emulating a camera that renders at that size. The " + "rollout parquets are 256x256; the evaluator renders at 128.") + ap.add_argument("--flips", default="both,none,ud,lr", + help="flip conventions to try; the evaluator uses img[::-1,::-1] = both") + args = ap.parse_args() + + import pyarrow.parquet as pq + dev = "cuda" if torch.cuda.is_available() else "cpu" + print(f"[rc] device {dev}", flush=True) + tower = ogpo.build_paligemma(dev) + from libero.libero import benchmark + bench = benchmark.get_benchmark_dict()["libero_10"]() + + C = Path(args.cache) + m = np.load(C / "meta.npz", allow_pickle=True) + fr, to = m["ep_from"].astype(int), m["ep_to"].astype(int) + dem = m["ep_demo"].astype(bool); suc = m["ep_success"].astype(bool) + tk = m["ep_task"]; dim = int(m["dim"]) + Z = np.load(C / "z.f16.npy", mmap_mode="r").reshape(-1, dim) + st = np.load(C / "feat_stats_demos.npz") + sd_vis = st["sd"][:dim] # visual block only + + flips = {"both": (slice(None, None, -1), slice(None, None, -1)), + "none": (slice(None), slice(None)), + "ud": (slice(None, None, -1), slice(None)), + "lr": (slice(None), slice(None, None, -1))} + want = [f for f in args.flips.split(",") if f in flips] + + def frames_of(e): + """(n_frames, getter(r) -> (agentview, wrist)) for episode e, from the raw + image source that produced its cached latents.""" + if args.pool == "rollsucc": + g = PAT.search(str(m["ep_src"][e])) + t, b, i, idx = g.groups() + p = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + if not os.path.exists(p): + return 0, None + tb = pq.read_table(p, columns=["image", "wrist_image"]) + return tb.num_rows, (lambda r: (decode(tb["image"][int(r)]), + decode(tb["wrist_image"][int(r)]))) + import h5py + sp = str(m["ep_src"][e]) # .../_demo/demo_7.npz + tdir = Path(sp).parent.name # _demo + k = Path(sp).stem # demo_7 + H = h5py.File(f"/data/pulkitag/users/rli14/libero_datasets/libero_10/{tdir}.hdf5", "r") + ob = H["data"][k]["obs"] + return ob["agentview_rgb"].shape[0], (lambda r: (np.asarray(ob["agentview_rgb"][int(r)]), + np.asarray(ob["eye_in_hand_rgb"][int(r)]))) + + eps = np.where((suc & ~dem) if args.pool == "rollsucc" else dem)[0][:args.n_ep] + print(f"[rc] pool={args.pool}: {len(eps)} episodes, {args.frames} frames each\n", flush=True) + agg = {f: [] for f in want} + for e in eps: + t = int(tk[e]) + n_src, get = frames_of(e) + if get is None: + print(f" ep {e}: source missing"); continue + ids = ogpo.tokenize_prompt(bench.get_task(t).language) + n = min(n_src, int(to[e] - fr[e])) + rows = np.linspace(0, n - 1, args.frames).astype(int) + for r in rows: + im0, im1 = get(r) + if args.src_res and im0.shape[0] != args.src_res: + from PIL import Image + _rs = lambda a: np.asarray(Image.fromarray(a).resize( + (args.src_res, args.src_res), Image.BILINEAR), np.uint8) + im0, im1 = _rs(im0), _rs(im1) + z_cache = np.asarray(Z[fr[e] + int(r)], np.float32) + for f in want: + a, bb = flips[f] + cams = [to224(im0[a, bb])[None], to224(im1[a, bb])[None]] + z = np.concatenate( + [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0] + # L2 in z-scored units: comparable to the #251 support-gap numbers + agg[f].append(float(np.linalg.norm((z - z_cache) / sd_vis))) + print(f" ep {e} t{t} done " + " ".join( + f"{f}={np.mean(agg[f][-args.frames:]):.2f}" for f in want), flush=True) + + print(f"\n=== pool={args.pool}: re-encode vs cached latent, L2 in z-scored units ===") + print("(reference from #251: rollout->nearest rollout 7.5-9.2, demo->nearest rollout 48.7-61.5)") + for f in want: + v = np.array(agg[f]) + print(f" flip={f:<5} n={len(v):<4} mean={v.mean():>8.2f} min={v.min():>8.2f} max={v.max():>8.2f}") + best = min(want, key=lambda f: np.mean(agg[f])) + print(f"\nbest convention: {best} (evaluator uses 'both')") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/reencode.sbatch b/frozen/rsm_libero_freeze_20261002/reencode.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f2c96c460c5510608d788af4f4a698d55e357514 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/reencode.sbatch @@ -0,0 +1,28 @@ +#!/bin/bash +#SBATCH --job-name=reenc +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=64G +#SBATCH --time=6: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 +# Re-encode rollout latents at the evaluator's 128 camera resolution (i251). +# Same venv + env as eval_slurm.sbatch so the encoder is the evaluator's encoder. +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export REPO_PATH=$B/external/rlinf PYTHONPATH="$B/external/rlinf:${PYTHONPATH:-}" +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')" +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +OUT=${OUT:-/data/pulkitag/scratch/rli14/pi05_lib10_ogpo_fl15_v1_r128} +$B/venvs/rlinf-libero-eval-venv/bin/python $G/reencode_rollouts.py \ + --out "$OUT" --cam-res "${CAMRES:-128}" --shard "${SHARD:-0}" --num-shards "${NSHARDS:-1}" \ + ${ONLYCACHE:+--only-cache "$ONLYCACHE"} ${LIMIT:+--limit "$LIMIT"} +echo "[re] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_freeze_20261002/reencode_rollouts.py b/frozen/rsm_libero_freeze_20261002/reencode_rollouts.py new file mode 100644 index 0000000000000000000000000000000000000000..32b31d495e4fb47d84528ba37d581a35876404d7 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/reencode_rollouts.py @@ -0,0 +1,121 @@ +"""Re-encode the rollout corpus at the resolution the evaluator actually renders. + +Finding (williamd4112/gen_q#251): the rollout latents in `pi05_lib10_ogpo_fl15_v1` +were encoded from the collector's 256x256 renders. The closed-loop evaluator renders +at 128x128 (`camera_heights=128`), and so does the demo hdf5. Re-encoding a rollout +frame through the evaluator's own path puts it 74.97 z-scored units from its cached +latent (within-cloud scale 7.5-9.2; demo cache re-encoded the same way: 4.27). Every +rollout latent is therefore off the manifold the evaluator produces -- which is why +BC on rollout successes is 0/500 with held-out action MSE 0.0008, and why a critic +trained on a 90%-rollout corpus is read off-support online. + +This rebuilds the rollout npz tree with latents from: parquet image (256, stored +upright) -> 128 (PIL bilinear, emulating the 128 camera) -> 224 (PIL bilinear, the +builder's own step) -> the SAME encoder. No flip: the parquet images are already in +the serving orientation (verified visually and by L2: flip=none matches at 4.26). +proprio / actions / success / prompt / task_index are copied from the original npz, +which are bit-identical to the parquet fields. + +Output tree mirrors the input so pack.py runs unchanged with --src . +""" +from __future__ import annotations +import argparse, importlib.util, io, os, re, sys, time +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from eval_closed_loop import BUILDER +from recheck_encoding import decode, PAT, PQ_ROOT + +_spec = importlib.util.spec_from_file_location("ogpo_re", BUILDER) +ogpo = importlib.util.module_from_spec(_spec) +sys.modules["ogpo_re"] = ogpo +_spec.loader.exec_module(ogpo) + + +def prep(img, cam_res): + """uint8 HxWx3 (upright) -> uint8 224x224x3 via the camera resolution.""" + from PIL import Image + im = Image.fromarray(img) + if im.size != (cam_res, cam_res): + im = im.resize((cam_res, cam_res), Image.BILINEAR) + if im.size != (224, 224): + im = im.resize((224, 224), Image.BILINEAR) # builder's own step + return np.asarray(im, np.uint8) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", default="/data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1") + ap.add_argument("--out", required=True) + ap.add_argument("--cam-res", type=int, default=128) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--num-shards", type=int, default=1) + ap.add_argument("--only-cache", default="", + help="meta.npz of a cache: re-encode only the episodes it uses " + "(the 4,500-rollout subset first, the full corpus after)") + ap.add_argument("--batch", type=int, default=128) + ap.add_argument("--limit", type=int, default=0, help="smoke: stop after N episodes") + args = ap.parse_args() + + import pyarrow.parquet as pq + dev = "cuda" if torch.cuda.is_available() else "cpu" + tower = ogpo.build_paligemma(dev) + + if args.only_cache: + m = np.load(args.only_cache, allow_pickle=True) + srcs = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] + else: + srcs = sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) + srcs = srcs[args.shard::args.num_shards] + if args.limit: + srcs = srcs[:args.limit] + print(f"[re] shard {args.shard}/{args.num_shards}: {len(srcs)} episodes -> {args.out} " + f"(cam_res={args.cam_res}, device={dev})", flush=True) + + t0 = time.time(); n_done = n_skip = 0 + for k, sp in enumerate(srcs): + rel = Path(sp).relative_to(args.src) + op = Path(args.out) / rel + if op.exists(): + n_skip += 1; continue + g = PAT.search(sp) + t, b, i, idx = g.groups() + pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + if not os.path.exists(pp): + print(f"[re] MISSING parquet for {rel}", flush=True); continue + z0 = np.load(sp, allow_pickle=True) + T = int(z0["z"].shape[0]) + tb = pq.read_table(pp, columns=["image", "wrist_image"]) + if tb.num_rows < T: + print(f"[re] {rel}: parquet has {tb.num_rows} rows < npz {T}; truncating", + flush=True); T = tb.num_rows + ids = ogpo.tokenize_prompt(str(z0["prompt"])) + zs = [] + for cam in ("image", "wrist_image"): + frames = np.stack([prep(decode(tb[cam][j]), args.cam_res) for j in range(T)]) + outs = [] + for s in range(0, T, args.batch): + outs.append(ogpo.encode_frames(tower, frames[s:s + args.batch], ids, dev, + args.batch)) + zs.append(np.concatenate(outs, 0)) + z = np.concatenate(zs, 1).astype(np.float16) # [T, 4096] base||wrist + assert z.shape == (T, z0["z"].shape[1]), (z.shape, z0["z"].shape) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=z0["proprio"][:T], actions=z0["actions"][:T], + success=z0["success"], prompt=z0["prompt"], task_index=z0["task_index"]) + os.replace(tmp, op) + n_done += 1 + if n_done % 25 == 0: + el = time.time() - t0 + print(f"[re] {k+1}/{len(srcs)} done={n_done} skip={n_skip} " + f"{el/n_done:.1f}s/ep eta {(len(srcs)-k-1)*el/n_done/60:.0f} min", flush=True) + print(f"[re] DONE shard {args.shard}: {n_done} written, {n_skip} existed", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/report.py b/frozen/rsm_libero_freeze_20261002/report.py new file mode 100644 index 0000000000000000000000000000000000000000..e3beba245705a8fdeaaa97408d4bdeb020329fd2 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/report.py @@ -0,0 +1,96 @@ +"""Collect run artifacts into one honest table. + +Reports what was actually measured and labels what was NOT. In particular the +offline metrics here are NOT closed-loop LIBERO success, so they cannot by +themselves support a claim of beating behaviour cloning; that requires the lane's +per-task closed-loop eval. This script prints the distinction rather than hiding it. +""" +from __future__ import annotations +import argparse, json +from pathlib import Path + + +def row(k, v, w=34): + print(f" {k:<{w}} {v}") + + +def winrate_ci(win, n, z=1.96): + """Wilson interval for a win rate. The action gap is a heavy-tailed mean and + swings between evals (+0.045 / +0.063 / +0.018 on consecutive checkpoints); + the win rate over the same pairs is the stable statistic, so report it with + an interval rather than quoting a point estimate.""" + if not n: + return (float("nan"), float("nan")) + p = win + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / d + return (c - h, c + h) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--critic", default="") + ap.add_argument("--ope-signal", default="") + ap.add_argument("--ope-null", default="") + ap.add_argument("--awr", default="") + a = ap.parse_args() + + if a.critic: + h = json.loads((Path(a.critic) / "history.json").read_text()) + last, best = h[-1], max(h, key=lambda r: r["q_action_gap"]) + print("\n== CRITIC (occupancy + reward latent) ==") + row("reward AUC (held-out)", f"{last['reward_auc']:.4f}") + row("occupancy CFM val loss", f"{last['cfm_val']:.4f}") + row("latent std min (collapse guard)", f"{last['latent_std_min']:.4f}") + lo, hi = winrate_ci(last["q_action_winrate"], 1024) + row("ACTION gap (headline)", f"{last['q_action_gap']:+.5f} " + f"(win {last['q_action_winrate']:.3f}, 95% CI [{lo:.3f},{hi:.3f}])") + bh = last.get("by_horizon", {}) + for k, v in bh.items(): + blo, bhi = winrate_ci(v["action_winrate"], v["n"]) + sig = "" if blo <= 0.5 <= bhi else " <-- excludes chance" + row(f" frames-to-end {k}", + f"gap {v['action_gap']:+.5f} win {v['action_winrate']:.3f} " + f"[{blo:.3f},{bhi:.3f}] n={v['n']}{sig}") + row(" best over training", f"{best['q_action_gap']:+.5f} @ step {best['step']}") + row("state success AUC", f"{last['q_success_auc']:.4f}") + print(" NOTE action gap is the metric that matters: COLLAPSE_ANALYSIS shows a") + print(" state-ranking value with a flat action gap dies in closed loop.") + + for tag, path in (("SIGNAL pi=BC(successes)", a.ope_signal), + ("NULL pi=BC(all)~mu", a.ope_null)): + if not path: + continue + r = json.loads((Path(path) / "report.json").read_text()) + c, v = r["calibration"], r["value"] + print(f"\n== OPE GATE :: {tag} ==") + row("E_mu[w] after calibration", f"{c['E_mu[w_endpoint]']:.4f} (target 1.000)") + row("calibration factor applied", f"{c['calib_scale']:.3f}") + row("E_mu[W] raw chunk product", f"{c['E_mu[W_chunk]']:.4f} (target 1.000)") + row("corr(endpoint w, chunk W)", f"{c['corr_w_vs_W']:.4f}") + row("weight ESS fraction", f"{c['ess_frac']:.3f}") + row("particle ESS fraction", f"{v['ess_particles']:.3f}") + row("success AUC with IS", f"{v['auc_success_IS']:.4f}") + row("success AUC without IS", f"{v['auc_success_noIS']:.4f}") + row("relative |dQ| from IS", f"{v['rel_shift_IS_vs_noIS']:.4f}") + row("expectation", v["gate_expectation"]) + + if a.awr: + L = json.loads((Path(a.awr) / "loop.json").read_text()) + print("\n== AWR LOOP ==") + row("pi_0 offline score", json.dumps(L["pi_0"])) + for r in L["rounds"]: + adv = r["awr"][-1] if r["awr"] else {} + row(f"round {r['round']} mean|adv|", + f"{adv.get('mean_abs_adv', float('nan')):.4f} " + f"(smolvla null result was 0.0190)") + row(f"round {r['round']} score", json.dumps(r["score"])) + + print("\nNOT MEASURED HERE: closed-loop LIBERO success. Every number above is") + print("offline. Beating BC on demos (0.584 +- 0.025 step-matched in this lane)") + print("requires the per-task closed-loop harness and is not claimed by this table.") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/report_arms.py b/frozen/rsm_libero_freeze_20261002/report_arms.py new file mode 100644 index 0000000000000000000000000000000000000000..5dcd3bdd892113d594ffe67080fcee9a606002f8 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/report_arms.py @@ -0,0 +1,95 @@ +"""The headline table: closed-loop LIBERO-10 success and throughput, four arms. + +Throughput = pooled_SR * max_steps / mean_steps, reported two ways because they +answer different questions: + succ : mean steps over SUCCESSFUL episodes -- how fast it is when it works + all : mean steps over ALL episodes -- a failure burns the full horizon, so + this penalises failing twice (once in SR, once in wasted time) + +Success rates are pooled over all task-episodes and carry a Wilson interval. +Arms are compared against A_bc_demos, the BC-on-demonstrations bar an RSM recipe +has to clear; a difference is only called a win when the intervals separate. +""" +from __future__ import annotations +import argparse, json +from pathlib import Path + +ARMS = [("LANE_CONTROL", "lane bcdemos (reference bar)"), + ("A_bc_demos", "BC on demos, our pipeline"), + ("B_bc_succ", "behaviour-policy extraction"), + ("C_iql", "IQL critic + AWR"), + ("D_rsm", "RSM critic + AWR (ours)")] + + +def wilson(k, n, z=1.96): + if not n: + return float("nan"), float("nan") + p = k / n + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / d + return c - h, c + h + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--eval-dir", default="/data/pulkitag/users/rli14/rsm_libero_runs/eval") + a = ap.parse_args() + d = Path(a.eval_dir) + + got = {} + for tag, _ in ARMS: + f = d / f"{tag}.json" + if f.exists(): + got[tag] = json.loads(f.read_text()) + + print("\n== CLOSED-LOOP LIBERO-10 (10 tasks x 10 inits, max 520 steps) ==") + print(f" {'arm':<12} {'what it is':<30} {'succ/n':>9} {'pooled SR':>10} " + f"{'95% CI':>16} {'thr_succ':>9} {'thr_all':>8}") + for tag, what in ARMS: + r = got.get(tag) + if r is None: + print(f" {tag:<12} {what:<30} {'--':>9} {'not yet run':>10}") + continue + k, n = r["successes"], r["episodes"] + lo, hi = wilson(k, n) + print(f" {tag:<12} {what:<30} {f'{k}/{n}':>9} {r['pooled_SR']:>10.3f} " + f"{f'[{lo:.3f},{hi:.3f}]':>16} {r['throughput_succ']:>9.3f} " + f"{r['throughput_all']:>8.3f}") + + # The bar is the REFERENCE policy when we have it: comparing our arms + # against our own broken BC would let a 0.02 arm look like a "win". + base = got.get("LANE_CONTROL") or got.get("A_bc_demos") + if base: + blo, bhi = wilson(base["successes"], base["episodes"]) + print(f"\n== vs the BC-on-demos bar ({base['pooled_SR']:.3f}) ==") + for tag, what in ARMS: + if got.get(tag) is base: + continue + r = got.get(tag) + if r is None: + continue + lo, hi = wilson(r["successes"], r["episodes"]) + if lo > bhi: + v = "WIN (intervals separate)" + elif hi < blo: + v = "LOSS (intervals separate)" + else: + v = "no separation at 95%" + print(f" {tag:<12} {r['pooled_SR'] - base['pooled_SR']:+.3f} {v}") + + if got: + print("\n== per-task pooled SR ==") + tasks = sorted({t for r in got.values() for t in r["per_task"]}) + print(f" {'task':<52}" + "".join(f"{t:>12}" for t, _ in ARMS if t in got)) + for tk in tasks: + print(f" {tk[:50]:<52}" + + "".join(f"{got[t]['per_task'].get(tk, float('nan')):>12.2f}" + for t, _ in ARMS if t in got)) + missing = [t for t, _ in ARMS if t not in got] + if missing: + print(f"\n NOT YET MEASURED: {', '.join(missing)} -- the table above is incomplete.") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/rerender.sbatch b/frozen/rsm_libero_freeze_20261002/rerender.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7033c7b65baa2ecf815376047760da2e9a447ee9 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/rerender.sbatch @@ -0,0 +1,28 @@ +#!/bin/bash +#SBATCH --job-name=rerender +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=64G +#SBATCH --time=6: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 +# Re-encode rollout latents at the evaluator's 128 camera resolution (i251). +# Same venv + env as eval_slurm.sbatch so the encoder is the evaluator's encoder. +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export REPO_PATH=$B/external/rlinf PYTHONPATH="$B/external/rlinf:${PYTHONPATH:-}" +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')" +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +OUT=${OUT:-/data/pulkitag/scratch/rli14/pi05_lib10_ogpo_fl15_v1_rr} +$B/venvs/rlinf-libero-eval-venv/bin/python $G/rerender_rollouts.py \ + --out "$OUT" --shard "${SHARD:-0}" --num-shards "${NSHARDS:-1}" \ + ${ONLYCACHE:+--only-cache "$ONLYCACHE"} ${LIMIT:+--limit "$LIMIT"} ${VALDEMOS:+--validate-demos "$VALDEMOS"} ${VALROLL:+--validate-rollouts "$VALROLL"} --cam-res "${CAMRES:-256}" --pool "${POOL:-rollouts}" ${DEMOCACHE:+--demo-cache "$DEMOCACHE"} +echo "[re] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_freeze_20261002/rerender_rollouts.py b/frozen/rsm_libero_freeze_20261002/rerender_rollouts.py new file mode 100644 index 0000000000000000000000000000000000000000..0b752e30d6a1025e0356829db4739fb70798fbae --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/rerender_rollouts.py @@ -0,0 +1,318 @@ +"""Re-render every rollout frame INSIDE the evaluator's environment, then encode. + +Why not resize the collector's 256x256 pixels (reencode_rollouts.py)? Measured: a +256->128 bilinear downsample lands in a THIRD region -- 63.7 from the live evaluator +feature, 71.5 from the demo cloud, 81.5 from the old rollout cloud -- no closer to the +evaluator than the cache it was meant to fix. SigLIP features do not survive an +approximate raster (to224's docstring: uint8 rounding alone is 3 sigma). + +So do the only thing that is evaluator-consistent BY CONSTRUCTION: the parquets log +`sim_state` for every frame; set it in the evaluator's own OffScreenRenderEnv +(camera_heights=128, EGL), read both cameras exactly as eval_closed_loop does +([::-1, ::-1], to224), encode with the evaluator's encoder. This is the admissibility +rule applied to features: a latent is admissible only if the eval environment can +produce it. + +Built-in validation (--validate-demos N): the demo hdf5 stores `states`; re-rendering +those through this path must land ~4 z-scored units from the demo cache (which was +built from the hdf5's own recorded images). If it does not, the path is wrong and no +rollout output should be trusted. + +Output mirrors the input npz tree so pack.py runs unchanged. Idempotent (skips +existing), atomic writes, requeue-safe. +""" +from __future__ import annotations +import argparse, importlib.util, os, re, sys, time +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from eval_closed_loop import BUILDER, to224, _eef_ori +from recheck_encoding import PAT, PQ_ROOT + +_spec = importlib.util.spec_from_file_location("ogpo_rr", BUILDER) +ogpo = importlib.util.module_from_spec(_spec) +sys.modules["ogpo_rr"] = ogpo +_spec.loader.exec_module(ogpo) + +DEMO_H5 = os.environ.get("RSM_DEMO_H5", "/data/pulkitag/users/rli14/libero_datasets/libero_10") + + +class Renderer: + """One evaluator env per task, reused across episodes.""" + def __init__(self, cam_res=128): + self.cam_res = cam_res + from libero.libero import benchmark, get_libero_path + from libero.libero.envs import OffScreenRenderEnv + self.bench = benchmark.get_benchmark_dict()["libero_10"]() + self.get_libero_path = get_libero_path; self.Env = OffScreenRenderEnv + self.envs, self.ids = {}, {} + + def env(self, tid): + # ONE live env at a time. robosuite's offscreen EGL context is shared across + # OffScreenRenderEnv instances in a process: with several alive, a render can + # come from whichever model last touched the context (measured: a task-0 state + # rendered as task-4's mugs and plates; one frame came back black). The + # evaluator builds one env per task and closes it; do the same. + if tid not in self.envs: + for _k in list(self.envs): + try: + self.envs[_k].close() + except Exception: + pass + self.envs.pop(_k, None) + t = self.bench.get_task(tid) + e = self.Env(bddl_file_name=str(Path(self.get_libero_path("bddl_files")) + / t.problem_folder / t.bddl_file), + camera_heights=self.cam_res, camera_widths=self.cam_res) + e.reset(); e.step(np.zeros(7)) + self.envs[tid] = e; self.ids[tid] = ogpo.tokenize_prompt(t.language) + return self.envs[tid], self.ids[tid] + + def frames(self, tid, states): + """states [T, nq+nv] -> (agent [T,224,224,3], wrist [T,224,224,3], proprio [T,8])""" + env, _ = self.env(tid) + sim = env.env.sim + A, W, P = [], [], [] + for st in states: + sim.set_state_from_flattened(np.asarray(st, np.float64)); sim.forward() + # Python-side visuals are NOT in the MuJoCo state: the stove burner is a + # site_rgba alpha in sim.model toggled by set_visualization() from + # turn_on(qpos), which the env runs inside step() via _check_success -> + # _post_process. Replay that update or a mid-episode kitchen frame renders + # with the burner off while the logged image has it on (measured: kitchen + # tasks drift 10-37, living-room tasks 3-4). + try: + env.env._check_success() + except Exception: + pass + if hasattr(env.env, "set_visualization"): + env.env.set_visualization() + sim.forward() + obs = env.env._get_observations(force_update=True) + A.append(to224(obs["agentview_image"][::-1, ::-1])) + W.append(to224(obs["robot0_eye_in_hand_image"][::-1, ::-1])) + P.append(np.concatenate([obs["robot0_eef_pos"], _eef_ori(obs), + obs["robot0_gripper_qpos"]]).astype(np.float32)) + return np.stack(A), np.stack(W), np.stack(P) + + +def encode(tower, ids, A, W, dev, bs): + za = ogpo.encode_frames(tower, A, ids, dev, bs) + zw = ogpo.encode_frames(tower, W, ids, dev, bs) + return np.concatenate([za, zw], 1).astype(np.float16) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", default="/data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1") + 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("--only-cache", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--batch", type=int, default=128) + ap.add_argument("--cam-res", type=int, default=256, + help="256 = RLinf libero_10 env (lane evaluator + collector); 128 = demo hdf5") + ap.add_argument("--pool", default="rollouts", choices=["rollouts", "demos", "demos_replay"], + help="demos: re-render the 500 demo episodes from hdf5 `states` into a " + "new demo cache tree (/_demo/demo_k.npz)") + ap.add_argument("--validate-rollouts", type=int, default=0, + help="re-render N rollout episodes (4 frames each) and report L2 to the " + "CACHED rollout latent. ~4 at --cam-res 256 means our evaluator at 256 " + "reproduces the collector, and the 43k latents are on-manifold as-is.") + ap.add_argument("--validate-demos", type=int, default=0, + help="re-render N demo episodes' hdf5 states and report L2 to the " + "demo cache (z-scored, demo stats). Run BEFORE trusting output.") + ap.add_argument("--demo-cache", default="/data/pulkitag/users/rli14/libero10_demo_ogpo_cache_cam128") + ap.add_argument("--stats", default="/data/pulkitag/users/rli14/rsm_libero_cache/full_demo_cam256/feat_stats_demos.npz") + args = ap.parse_args() + + dev = "cuda" if torch.cuda.is_available() else "cpu" + tower = ogpo.build_paligemma(dev) + R = Renderer(args.cam_res) + print(f"[rr] cam_res={args.cam_res} pool={args.pool}", flush=True) + + if args.validate_demos: + import h5py, glob + st = np.load(args.stats); mu, sd = st["mu"][:4096], st["sd"][:4096] + dists = [] + h5s = sorted(glob.glob(f"{DEMO_H5}/*.hdf5")) + for tid, h5 in enumerate(h5s[:args.validate_demos]): + tname = Path(h5).stem[:-5] # strip _demo + tids = [i for i in range(10) if R.bench.get_task(i).name == tname] + if not tids: print(f"[rr] validate: no task for {tname}"); continue + tid = tids[0] + with h5py.File(h5, "r") as H: + states = np.asarray(H["data"]["demo_0"]["states"][:]) + rows = np.linspace(0, len(states) - 1, 4).astype(int) + A, W, _ = R.frames(tid, states[rows]) + _, ids = R.env(tid) + z = encode(tower, ids, A, W, dev, args.batch).astype(np.float32) + zc = np.load(f"{args.demo_cache}/{tname}_demo/demo_0.npz")["z"][rows].astype(np.float32) + print(f"[rr] validate demo task {tid}: comparing against {args.demo_cache}", flush=True) + dd = np.linalg.norm((z - zc) / sd, axis=1) + dists += dd.tolist() + print(f"[rr] validate demo task {tid} ({tname[:30]}): L2 to demo cache " + f"{np.round(dd, 2).tolist()}", flush=True) + print(f"[rr] VALIDATE demos: mean {np.mean(dists):.2f} max {np.max(dists):.2f} " + f"(demo cache re-encoded from its own hdf5 images: 3.7-4.3; " + f"anything >10 means this path is NOT the evaluator's)", flush=True) + + import pyarrow.parquet as pq + if args.validate_rollouts: + st = np.load(args.stats); sd = st["sd"][:4096] + m = np.load(args.only_cache, allow_pickle=True) if args.only_cache else None + cand = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] if m is not None \ + else sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) + dists = [] + for sp in cand[:args.validate_rollouts]: + g = PAT.search(sp); t, b, i, idx = g.groups() + pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + z0 = np.load(sp, allow_pickle=True); T = int(z0["z"].shape[0]) + tb = pq.read_table(pp, columns=["sim_state"]) + rows = np.linspace(0, min(T, tb.num_rows) - 1, 4).astype(int) + states = np.stack([np.asarray(tb["sim_state"][int(r)].as_py(), np.float64) for r in rows]) + tid = int(t) # from the FILENAME: the npz task_index field is wrong in the raw corpus (#234) + A, W, P = R.frames(tid, states); _, ids = R.env(tid) + z = encode(tower, ids, A, W, dev, args.batch).astype(np.float32) + dd = np.linalg.norm((z - z0["z"][rows].astype(np.float32)) / sd, axis=1) + dists += dd.tolist() + # Is the LOGGED image the same scene as the LOGGED sim_state? Compare the + # re-rendered proprio to the logged proprio (consistency of sim_state with + # state/actions), and save frame-0 side by side for the eye. + dp = float(np.abs(P - z0["proprio"][rows]).mean()) + print(f"[rr] validate rollout t{t} {Path(sp).name}: L2 to cached " + f"{np.round(dd, 2).tolist()} |rerendered proprio - logged| = {dp:.4f}", flush=True) + try: + from PIL import Image + from recheck_encoding import decode + tbi = pq.read_table(pp, columns=["image"]) + logged = Image.fromarray(decode(tbi["image"][int(rows[0])])).resize((224, 224)) + pair = Image.new("RGB", (448, 224)); pair.paste(logged, (0, 0)); pair.paste(Image.fromarray(A[0]), (224, 0)) + od = Path(args.out) / "validate_pairs"; od.mkdir(parents=True, exist_ok=True) + pair.save(od / f"{Path(sp).stem}_L2_{dd[0]:.0f}.png") + except Exception as e: + print(f"[rr] (pair save failed: {e})", flush=True) + print(f"[rr] VALIDATE rollouts @{args.cam_res}: mean {np.mean(dists):.2f} " + f"max {np.max(dists):.2f} (cache re-encoded from its own 256 pixels: 4.0-4.3)", + flush=True) + + if args.pool == "demos_replay": + # REPLAY the demonstration's logged actions live in the evaluator env from its + # logged initial state, recording what the env actually renders. Re-rendering + # from per-frame sim_state cannot reproduce a live render on the kitchen/study + # scenes (two fresh renders of the same state differ by 10-37 z-scored units; + # living rooms 3-4), so the only demo frames that are guaranteed to be in the + # evaluator's space are ones the evaluator itself produced along a trajectory. + # A demo whose replay does not end in success is inadmissible (same rule as + # rollouts) and is written with success=False so pack/BC can drop it. + import h5py, glob + n_done = n_ok = 0 + for h5 in sorted(glob.glob(f"{DEMO_H5}/*.hdf5")): + tname = Path(h5).stem[:-5] + tids = [i for i in range(10) if R.bench.get_task(i).name == tname] + if not tids: print(f"[rr] no task for {tname}"); continue + tid = tids[0]; env, ids = R.env(tid) + src_npz = sorted(glob.glob(f"{args.demo_cache}/{tname}_demo/demo_*.npz")) + with h5py.File(h5, "r") as H: + for sp in src_npz: + k = Path(sp).stem; op = Path(args.out) / f"{tname}_demo" / f"{k}.npz" + if op.exists(): continue + z0 = np.load(sp, allow_pickle=True) + acts = np.asarray(H["data"][k]["actions"][:], np.float32) + st0 = np.asarray(H["data"][k]["states"][0], np.float64) + env.reset(); env.env.sim.set_state_from_flattened(st0); env.env.sim.forward() + obs, _, _, _ = env.step(np.zeros(7)) + A, W, P = [], [], []; done = False + for a in acts: + A.append(to224(obs["agentview_image"][::-1, ::-1])) + W.append(to224(obs["robot0_eye_in_hand_image"][::-1, ::-1])) + P.append(np.concatenate([obs["robot0_eef_pos"], _eef_ori(obs), + obs["robot0_gripper_qpos"]]).astype(np.float32)) + obs, _, done, _ = env.step(a) + if done: break + T = len(A) + z = encode(tower, ids, np.stack(A), np.stack(W), dev, args.batch) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=np.stack(P), actions=acts[:T], prompt=z0["prompt"], + success=bool(done), replayed=True) + os.replace(tmp, op); n_done += 1; n_ok += int(bool(done)) + print(f"[rr] demos_replay task {tid}: {len(src_npz)} episodes, replay success so far " + f"{n_ok}/{n_done}", flush=True) + print(f"[rr] DONE demos_replay: {n_done} episodes, {n_ok} reproduce success " + f"({n_ok / max(n_done, 1):.3f}) at cam_res={args.cam_res}", flush=True) + return + + if args.pool == "demos": + import h5py, glob + n_done = 0 + for h5 in sorted(glob.glob(f"{DEMO_H5}/*.hdf5")): + tname = Path(h5).stem[:-5] + tids = [i for i in range(10) if R.bench.get_task(i).name == tname] + if not tids: print(f"[rr] no task for {tname}"); continue + tid = tids[0]; _, ids = R.env(tid) + src_npz = sorted(glob.glob(f"{args.demo_cache}/{tname}_demo/demo_*.npz")) + with h5py.File(h5, "r") as H: + for sp in src_npz: + k = Path(sp).stem; op = Path(args.out) / f"{tname}_demo" / f"{k}.npz" + if op.exists(): continue + z0 = np.load(sp, allow_pickle=True) + states = np.asarray(H["data"][k]["states"][:]) + T = min(len(states), int(z0["z"].shape[0])) + A, W, P = R.frames(tid, states[:T]) + z = encode(tower, ids, A, W, dev, args.batch) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=P, actions=z0["actions"][:T], prompt=z0["prompt"]) + os.replace(tmp, op); n_done += 1 + print(f"[rr] demos task {tid}: {len(src_npz)} episodes -> {args.out}/{tname}_demo " + f"(total written {n_done})", flush=True) + print(f"[rr] DONE demos: {n_done} episodes at cam_res={args.cam_res}", flush=True) + return + + if args.only_cache: + m = np.load(args.only_cache, allow_pickle=True) + srcs = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] + else: + srcs = sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) + srcs = srcs[args.shard::args.num_shards] + if args.limit: srcs = srcs[:args.limit] + print(f"[rr] shard {args.shard}/{args.num_shards}: {len(srcs)} episodes -> {args.out}", flush=True) + + t0 = time.time(); n_done = n_skip = 0 + for k, sp in enumerate(srcs): + rel = Path(sp).relative_to(args.src); op = Path(args.out) / rel + if op.exists(): n_skip += 1; continue + g = PAT.search(sp); t, b, i, idx = g.groups() + pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + if not os.path.exists(pp): print(f"[rr] MISSING parquet {rel}", flush=True); continue + z0 = np.load(sp, allow_pickle=True); T = int(z0["z"].shape[0]) + tb = pq.read_table(pp, columns=["sim_state"]) + T = min(T, tb.num_rows) + states = np.stack([np.asarray(tb["sim_state"][j].as_py(), np.float64) for j in range(T)]) + tid = int(t) # from the FILENAME: the npz task_index field is wrong in the raw corpus (#234) + A, W, P = R.frames(tid, states) + _, ids = R.env(tid) + z = encode(tower, ids, A, W, dev, args.batch) + # proprio: the re-rendered observation, which is what the evaluator would feed; + # agrees with the logged `state` to float precision (checked: mean |d| = 0.0) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=P, actions=z0["actions"][:T], success=z0["success"], + prompt=z0["prompt"], task_index=z0["task_index"]) + os.replace(tmp, op); n_done += 1 + if n_done % 25 == 0: + el = time.time() - t0 + print(f"[rr] {k+1}/{len(srcs)} done={n_done} skip={n_skip} {el/n_done:.1f}s/ep " + f"eta {(len(srcs)-k-1)*el/n_done/60:.0f} min", flush=True) + print(f"[rr] DONE shard {args.shard}: {n_done} written, {n_skip} existed", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/results/awr_is.json b/frozen/rsm_libero_freeze_20261002/results/awr_is.json new file mode 100644 index 0000000000000000000000000000000000000000..e0e2edacbd8d7e92f9f78c0a8400a977dd1ecb25 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/awr_is.json @@ -0,0 +1,108 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/awr_is", + "rounds": 2, + "batch": 256, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "awr_beta": 3.0, + "w_max": 20.0, + "awr_steps": 2000, + "bc_steps": 6000, + "ratio_steps": 3000, + "wend_steps": 3000, + "use_is": true, + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "ratio_smooth": 0.0, + "d_z": 256 + }, + "rounds": [ + { + "round": 1, + "awr": [ + { + "step": 500, + "loss": 0.16257646679878235, + "mean_abs_adv": 1.6013294458389282, + "adv_std": 4.7013840675354, + "w_max_batch": 9.430573463439941 + }, + { + "step": 1000, + "loss": 0.1544513702392578, + "mean_abs_adv": 1.835625171661377, + "adv_std": 5.795838832855225, + "w_max_batch": 6.571922302246094 + }, + { + "step": 1500, + "loss": 0.15181061625480652, + "mean_abs_adv": 2.207453727722168, + "adv_std": 6.558887004852295, + "w_max_batch": 11.571876525878906 + }, + { + "step": 2000, + "loss": 0.15949973464012146, + "mean_abs_adv": 1.663811445236206, + "adv_std": 4.831233024597168, + "w_max_batch": 10.90399169921875 + } + ], + "score": { + "bc_nll_success": 0.17084458470344543, + "bc_nll_failure": 0.17130279541015625, + "act_gap": 0.00045821070671081543 + } + }, + { + "round": 2, + "awr": [ + { + "step": 500, + "loss": 0.15983301401138306, + "mean_abs_adv": 1.0695834159851074, + "adv_std": 3.722569704055786, + "w_max_batch": 9.685918807983398 + }, + { + "step": 1000, + "loss": 0.15429604053497314, + "mean_abs_adv": 0.7141176462173462, + "adv_std": 2.485543966293335, + "w_max_batch": 11.612875938415527 + }, + { + "step": 1500, + "loss": 0.20286273956298828, + "mean_abs_adv": 1.0271759033203125, + "adv_std": 3.73201847076416, + "w_max_batch": 11.328639030456543 + }, + { + "step": 2000, + "loss": 0.13324297964572906, + "mean_abs_adv": 0.9385720491409302, + "adv_std": 3.4402856826782227, + "w_max_batch": 11.071598052978516 + } + ], + "score": { + "bc_nll_success": 0.17699238657951355, + "bc_nll_failure": 0.1672143042087555, + "act_gap": -0.009778082370758057 + } + } + ], + "pi_0": { + "bc_nll_success": 0.17064538598060608, + "bc_nll_failure": 0.1876475065946579, + "act_gap": 0.01700212061405182 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/awr_nois.json b/frozen/rsm_libero_freeze_20261002/results/awr_nois.json new file mode 100644 index 0000000000000000000000000000000000000000..be7c798a4a449d5411a50204727d4988c3d4c535 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/awr_nois.json @@ -0,0 +1,109 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/awr_nois", + "rounds": 2, + "batch": 256, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "awr_beta": 3.0, + "w_max": 20.0, + "awr_steps": 2000, + "bc_steps": 6000, + "ratio_steps": 3000, + "wend_steps": 3000, + "use_is": false, + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "awr_pool": "all", + "ratio_smooth": 0.0, + "d_z": 256 + }, + "rounds": [ + { + "round": 1, + "awr": [ + { + "step": 500, + "loss": 0.195926696062088, + "mean_abs_adv": 1.5207128524780273, + "adv_std": 3.9703404903411865, + "w_max_batch": 9.167509078979492 + }, + { + "step": 1000, + "loss": 0.1670464277267456, + "mean_abs_adv": 1.6043593883514404, + "adv_std": 3.9212582111358643, + "w_max_batch": 10.829105377197266 + }, + { + "step": 1500, + "loss": 0.15901966392993927, + "mean_abs_adv": 1.8362610340118408, + "adv_std": 5.85999870300293, + "w_max_batch": 10.425881385803223 + }, + { + "step": 2000, + "loss": 0.1412782222032547, + "mean_abs_adv": 1.9440784454345703, + "adv_std": 6.391367435455322, + "w_max_batch": 8.848503112792969 + } + ], + "score": { + "bc_nll_success": 0.17096398770809174, + "bc_nll_failure": 0.17207448184490204, + "act_gap": 0.0011104941368103027 + } + }, + { + "round": 2, + "awr": [ + { + "step": 500, + "loss": 0.1808767318725586, + "mean_abs_adv": 1.7913116216659546, + "adv_std": 5.498270034790039, + "w_max_batch": 8.57076644897461 + }, + { + "step": 1000, + "loss": 0.18697738647460938, + "mean_abs_adv": 1.5218538045883179, + "adv_std": 3.9496538639068604, + "w_max_batch": 6.969772815704346 + }, + { + "step": 1500, + "loss": 0.13867154717445374, + "mean_abs_adv": 2.0528721809387207, + "adv_std": 5.918031692504883, + "w_max_batch": 8.451258659362793 + }, + { + "step": 2000, + "loss": 0.19296662509441376, + "mean_abs_adv": 2.0750231742858887, + "adv_std": 6.377630710601807, + "w_max_batch": 6.74656867980957 + } + ], + "score": { + "bc_nll_success": 0.17648011445999146, + "bc_nll_failure": 0.16832603514194489, + "act_gap": -0.00815407931804657 + } + } + ], + "pi_0": { + "bc_nll_success": 0.17538213729858398, + "bc_nll_failure": 0.18425589799880981, + "act_gap": 0.00887376070022583 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/awr_pool_succ.json b/frozen/rsm_libero_freeze_20261002/results/awr_pool_succ.json new file mode 100644 index 0000000000000000000000000000000000000000..d3928448f0904cbde94b699feb62d947004a4652 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/awr_pool_succ.json @@ -0,0 +1,95 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/awr_pool_succ", + "rounds": 2, + "batch": 256, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "awr_beta": 3.0, + "w_max": 20.0, + "awr_steps": 1500, + "bc_steps": 3000, + "ratio_steps": 1500, + "wend_steps": 1500, + "use_is": false, + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "awr_pool": "succ", + "ratio_smooth": 0.0, + "d_z": 256 + }, + "rounds": [ + { + "round": 1, + "awr": [ + { + "step": 500, + "loss": 0.203533336520195, + "mean_abs_adv": 3.2522952556610107, + "adv_std": 7.032632350921631, + "w_max_batch": 5.746964454650879 + }, + { + "step": 1000, + "loss": 0.1729510873556137, + "mean_abs_adv": 2.6058743000030518, + "adv_std": 5.858712673187256, + "w_max_batch": 11.027697563171387 + }, + { + "step": 1500, + "loss": 0.241312637925148, + "mean_abs_adv": 1.988947868347168, + "adv_std": 3.9411566257476807, + "w_max_batch": 10.441418647766113 + } + ], + "score": { + "bc_nll_success": 0.19998064637184143, + "bc_nll_failure": 0.21658773720264435, + "act_gap": 0.016607090830802917 + } + }, + { + "round": 2, + "awr": [ + { + "step": 500, + "loss": 0.14199835062026978, + "mean_abs_adv": 3.5519473552703857, + "adv_std": 8.122130393981934, + "w_max_batch": 6.081887245178223 + }, + { + "step": 1000, + "loss": 0.16939425468444824, + "mean_abs_adv": 2.661106824874878, + "adv_std": 5.243246555328369, + "w_max_batch": 5.711920738220215 + }, + { + "step": 1500, + "loss": 0.12747256457805634, + "mean_abs_adv": 2.00933575630188, + "adv_std": 4.834885120391846, + "w_max_batch": 7.9043755531311035 + } + ], + "score": { + "bc_nll_success": 0.20760184526443481, + "bc_nll_failure": 0.21295753121376038, + "act_gap": 0.0053556859493255615 + } + } + ], + "pi_0": { + "bc_nll_success": 0.18510574102401733, + "bc_nll_failure": 0.2062300741672516, + "act_gap": 0.021124333143234253 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/critic_actcon01_history.json b/frozen/rsm_libero_freeze_20261002/results/critic_actcon01_history.json new file mode 100644 index 0000000000000000000000000000000000000000..34e202e884f3e65b1903716ae2474f1b57a39e3e --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/critic_actcon01_history.json @@ -0,0 +1,786 @@ +[ + { + "step": 2000, + "reward_auc": 0.9876610505450941, + "cfm_val": 0.25738441944122314, + "per_task": { + "0": { + "n": 100, + "action_gap": 0.004566409159451723, + "success_auc": 0.5842985842985843, + "succ_rate": 0.3700000047683716 + }, + "1": { + "n": 137, + "action_gap": -0.005876636598259211, + "success_auc": 0.4227956989247312, + "succ_rate": 0.45255473256111145 + }, + "2": { + "n": 156, + "action_gap": 0.01211931649595499, + "success_auc": 0.5297852474323063, + "succ_rate": 0.32692307233810425 + }, + "3": { + "n": 107, + "action_gap": 0.002370755886659026, + "success_auc": 0.45433996383363473, + "succ_rate": 0.2616822421550751 + }, + "4": { + "n": 76, + "action_gap": -0.013497255742549896, + "success_auc": 0.5821000704721635, + "succ_rate": 0.43421053886413574 + }, + "5": { + "n": 26, + "action_gap": -0.010058850049972534, + "success_auc": 0.6470588235294118, + "succ_rate": 0.6538461446762085 + }, + "6": { + "n": 93, + "action_gap": 0.010616077110171318, + "success_auc": 0.40674603174603174, + "succ_rate": 0.22580644488334656 + }, + "7": { + "n": 129, + "action_gap": 0.0065583945252001286, + "success_auc": 0.6056045666839647, + "succ_rate": 0.3643410801887512 + }, + "8": { + "n": 97, + "action_gap": -0.022468166425824165, + "success_auc": 0.5272078501338091, + "succ_rate": 0.39175257086753845 + }, + "9": { + "n": 103, + "action_gap": 0.006738460157066584, + "success_auc": 0.5214676034348166, + "succ_rate": 0.5922330021858215 + } + }, + "by_horizon": { + "0-50": { + "n": 115, + "action_gap": 0.037848301231861115, + "action_winrate": 0.6521739130434783, + "q_mean": 0.2682979106903076 + }, + "50-100": { + "n": 130, + "action_gap": -0.006974631920456886, + "action_winrate": 0.47692307692307695, + "q_mean": 0.055154867470264435 + }, + "100-200": { + "n": 245, + "action_gap": -0.01264046411961317, + "action_winrate": 0.4448979591836735, + "q_mean": 0.03335871174931526 + }, + "200+": { + "n": 534, + "action_gap": 0.0009504547924734652, + "action_winrate": 0.46441947565543074, + "q_mean": 0.0198063962161541 + } + }, + "latent_std_min": 0.18378838896751404, + "q_action_gap": 0.0008364089298993349, + "q_action_winrate": 0.482421875, + "q_success_auc": 0.5158398905234348, + "q_mean": 0.055443257093429565 + }, + { + "step": 4000, + "reward_auc": 0.9876276512175962, + "cfm_val": 0.17982925474643707, + "per_task": { + "0": { + "n": 104, + "action_gap": -0.018495649099349976, + "success_auc": 0.6214526214526215, + "succ_rate": 0.25961539149284363 + }, + "1": { + "n": 109, + "action_gap": -0.013799305073916912, + "success_auc": 0.4601889338731444, + "succ_rate": 0.47706422209739685 + }, + "2": { + "n": 134, + "action_gap": 0.015660826116800308, + "success_auc": 0.49041656018400204, + "succ_rate": 0.3208955228328705 + }, + "3": { + "n": 110, + "action_gap": 0.007917151786386967, + "success_auc": 0.4323962516733601, + "succ_rate": 0.2454545497894287 + }, + "4": { + "n": 104, + "action_gap": 0.007151569705456495, + "success_auc": 0.4701797385620915, + "succ_rate": 0.3461538553237915 + }, + "5": { + "n": 24, + "action_gap": -0.008169957436621189, + "success_auc": 0.75, + "succ_rate": 0.3333333432674408 + }, + "6": { + "n": 66, + "action_gap": 0.015843722969293594, + "success_auc": 0.7058823529411765, + "succ_rate": 0.25757575035095215 + }, + "7": { + "n": 147, + "action_gap": -0.005361799616366625, + "success_auc": 0.6405058209554396, + "succ_rate": 0.36054420471191406 + }, + "8": { + "n": 142, + "action_gap": -0.007460034918040037, + "success_auc": 0.4775747508305648, + "succ_rate": 0.39436620473861694 + }, + "9": { + "n": 84, + "action_gap": 0.020410602912306786, + "success_auc": 0.48788265306122447, + "succ_rate": 0.6666666865348816 + } + }, + "by_horizon": { + "0-50": { + "n": 129, + "action_gap": 0.040712807327508926, + "action_winrate": 0.5736434108527132, + "q_mean": 0.22582679986953735 + }, + "50-100": { + "n": 115, + "action_gap": -0.01250066515058279, + "action_winrate": 0.5130434782608696, + "q_mean": 0.031353823840618134 + }, + "100-200": { + "n": 246, + "action_gap": -0.014171958900988102, + "action_winrate": 0.516260162601626, + "q_mean": 0.013526356779038906 + }, + "200+": { + "n": 534, + "action_gap": 0.0012622518697753549, + "action_winrate": 0.5187265917602997, + "q_mean": 0.021329164505004883 + } + }, + "latent_std_min": 0.10585425049066544, + "q_action_gap": 0.000978628871962428, + "q_action_winrate": 0.5244140625, + "q_success_auc": 0.5189727786337955, + "q_mean": 0.0463423877954483 + }, + { + "step": 6000, + "reward_auc": 0.987619517466582, + "cfm_val": 0.1564761996269226, + "per_task": { + "0": { + "n": 108, + "action_gap": -0.0029598644468933344, + "success_auc": 0.6661812886785584, + "succ_rate": 0.37962964177131653 + }, + "1": { + "n": 111, + "action_gap": -0.012450174428522587, + "success_auc": 0.4107023411371237, + "succ_rate": 0.4144144058227539 + }, + "2": { + "n": 131, + "action_gap": 0.0009704058174975216, + "success_auc": 0.5333333333333333, + "succ_rate": 0.4580152630805969 + }, + "3": { + "n": 118, + "action_gap": 0.0006856883992440999, + "success_auc": 0.3781239857189224, + "succ_rate": 0.3305084705352783 + }, + "4": { + "n": 89, + "action_gap": 0.01947815716266632, + "success_auc": 0.600111234705228, + "succ_rate": 0.3483146131038666 + }, + "5": { + "n": 22, + "action_gap": -0.004661570303142071, + "success_auc": 0.7166666666666667, + "succ_rate": 0.5454545617103577 + }, + "6": { + "n": 86, + "action_gap": -0.009215174242854118, + "success_auc": 0.6065934065934065, + "succ_rate": 0.24418604373931885 + }, + "7": { + "n": 153, + "action_gap": 0.0005523079307749867, + "success_auc": 0.7152777777777778, + "succ_rate": 0.37254902720451355 + }, + "8": { + "n": 110, + "action_gap": 0.011075697839260101, + "success_auc": 0.5532801110725443, + "succ_rate": 0.3909091055393219 + }, + "9": { + "n": 96, + "action_gap": 0.026935627683997154, + "success_auc": 0.4722858451672011, + "succ_rate": 0.6145833134651184 + } + }, + "by_horizon": { + "0-50": { + "n": 131, + "action_gap": 0.0486595593392849, + "action_winrate": 0.5954198473282443, + "q_mean": 0.22337323427200317 + }, + "50-100": { + "n": 138, + "action_gap": -0.0038172707427293062, + "action_winrate": 0.572463768115942, + "q_mean": 0.03140514716506004 + }, + "100-200": { + "n": 256, + "action_gap": -0.0018287473358213902, + "action_winrate": 0.5078125, + "q_mean": 0.017960501834750175 + }, + "200+": { + "n": 499, + "action_gap": -0.004300427623093128, + "action_winrate": 0.4348697394789579, + "q_mean": 0.02231152355670929 + } + }, + "latent_std_min": 0.1156306192278862, + "q_action_gap": 0.0031577597837895155, + "q_action_winrate": 0.4921875, + "q_success_auc": 0.5466356570656171, + "q_mean": 0.048171039670705795 + }, + { + "step": 8000, + "reward_auc": 0.9923620933521924, + "cfm_val": 0.1500718593597412, + "per_task": { + "0": { + "n": 88, + "action_gap": 0.001879670424386859, + "success_auc": 0.6567493112947659, + "succ_rate": 0.375 + }, + "1": { + "n": 112, + "action_gap": -0.013231679797172546, + "success_auc": 0.428890306122449, + "succ_rate": 0.5 + }, + "2": { + "n": 156, + "action_gap": 0.011789332143962383, + "success_auc": 0.6479665940450254, + "succ_rate": 0.3461538553237915 + }, + "3": { + "n": 110, + "action_gap": -7.351743261096999e-05, + "success_auc": 0.4026442307692308, + "succ_rate": 0.290909081697464 + }, + "4": { + "n": 114, + "action_gap": 0.02756674960255623, + "success_auc": 0.6703964194373402, + "succ_rate": 0.4035087823867798 + }, + "5": { + "n": 23, + "action_gap": -0.0038583874702453613, + "success_auc": 0.8384615384615385, + "succ_rate": 0.5652173757553101 + }, + "6": { + "n": 88, + "action_gap": 0.030580373480916023, + "success_auc": 0.6935483870967742, + "succ_rate": 0.2954545319080353 + }, + "7": { + "n": 129, + "action_gap": 0.003452255390584469, + "success_auc": 0.7311827956989247, + "succ_rate": 0.27906978130340576 + }, + "8": { + "n": 126, + "action_gap": -0.003117024665698409, + "success_auc": 0.3851744186046512, + "succ_rate": 0.3174603283405304 + }, + "9": { + "n": 78, + "action_gap": 0.00961407832801342, + "success_auc": 0.5909722222222222, + "succ_rate": 0.6153846383094788 + } + }, + "by_horizon": { + "0-50": { + "n": 129, + "action_gap": 0.050272565335035324, + "action_winrate": 0.5038759689922481, + "q_mean": 0.21413478255271912 + }, + "50-100": { + "n": 115, + "action_gap": 0.004295047372579575, + "action_winrate": 0.591304347826087, + "q_mean": 0.010329574346542358 + }, + "100-200": { + "n": 276, + "action_gap": -0.0049506304785609245, + "action_winrate": 0.5036231884057971, + "q_mean": 0.009217144921422005 + }, + "200+": { + "n": 504, + "action_gap": 0.0028754533268511295, + "action_winrate": 0.49404761904761907, + "q_mean": 0.013028163462877274 + } + }, + "latent_std_min": 0.11352813243865967, + "q_action_gap": 0.006896430626511574, + "q_action_winrate": 0.5087890625, + "q_success_auc": 0.585498046875, + "q_mean": 0.037032630294561386 + }, + { + "step": 10000, + "reward_auc": 0.9923778851315084, + "cfm_val": 0.12619173526763916, + "per_task": { + "0": { + "n": 98, + "action_gap": 0.008085733279585838, + "success_auc": 0.6601477618426771, + "succ_rate": 0.3979591727256775 + }, + "1": { + "n": 117, + "action_gap": -0.017585037276148796, + "success_auc": 0.45784198113207547, + "succ_rate": 0.45299145579338074 + }, + "2": { + "n": 145, + "action_gap": -0.006606878712773323, + "success_auc": 0.7018947368421052, + "succ_rate": 0.3448275923728943 + }, + "3": { + "n": 102, + "action_gap": -0.0062676831148564816, + "success_auc": 0.45077220077220076, + "succ_rate": 0.27450981736183167 + }, + "4": { + "n": 94, + "action_gap": 0.008275660686194897, + "success_auc": 0.6149193548387096, + "succ_rate": 0.3404255211353302 + }, + "5": { + "n": 23, + "action_gap": 0.0049131689593195915, + "success_auc": 0.9705882352941176, + "succ_rate": 0.260869562625885 + }, + "6": { + "n": 90, + "action_gap": 0.024443859234452248, + "success_auc": 0.6631016042780749, + "succ_rate": 0.24444444477558136 + }, + "7": { + "n": 158, + "action_gap": 0.016934383660554886, + "success_auc": 0.7546551724137931, + "succ_rate": 0.3670886158943176 + }, + "8": { + "n": 119, + "action_gap": 0.001397809013724327, + "success_auc": 0.4739952718676123, + "succ_rate": 0.3949579894542694 + }, + "9": { + "n": 78, + "action_gap": 0.022675467655062675, + "success_auc": 0.5071010860484545, + "succ_rate": 0.7307692170143127 + } + }, + "by_horizon": { + "0-50": { + "n": 123, + "action_gap": 0.05798455327749252, + "action_winrate": 0.5772357723577236, + "q_mean": 0.2775479257106781 + }, + "50-100": { + "n": 123, + "action_gap": 0.004857067484408617, + "action_winrate": 0.5121951219512195, + "q_mean": 0.03623020276427269 + }, + "100-200": { + "n": 281, + "action_gap": -0.0038929434958845377, + "action_winrate": 0.45907473309608543, + "q_mean": 0.0360763780772686 + }, + "200+": { + "n": 497, + "action_gap": -0.003614547196775675, + "action_winrate": 0.47283702213279677, + "q_mean": 0.026242343708872795 + } + }, + "latent_std_min": 0.12484024465084076, + "q_action_gap": 0.004725754261016846, + "q_action_winrate": 0.486328125, + "q_success_auc": 0.595913523637303, + "q_mean": 0.060326773673295975 + }, + { + "step": 12000, + "reward_auc": 0.9876347116189305, + "cfm_val": 0.1233709380030632, + "per_task": { + "0": { + "n": 103, + "action_gap": 0.005045799538493156, + "success_auc": 0.7376760563380281, + "succ_rate": 0.3106796145439148 + }, + "1": { + "n": 118, + "action_gap": -0.00090402876958251, + "success_auc": 0.6080069124423964, + "succ_rate": 0.47457626461982727 + }, + "2": { + "n": 129, + "action_gap": 0.004968222696334124, + "success_auc": 0.7342696629213483, + "succ_rate": 0.3100775182247162 + }, + "3": { + "n": 105, + "action_gap": 0.002376304008066654, + "success_auc": 0.6008163265306122, + "succ_rate": 0.3333333432674408 + }, + "4": { + "n": 97, + "action_gap": 0.0065465266816318035, + "success_auc": 0.756021409455843, + "succ_rate": 0.39175257086753845 + }, + "5": { + "n": 24, + "action_gap": 0.01102861762046814, + "success_auc": 0.9785714285714285, + "succ_rate": 0.5833333134651184 + }, + "6": { + "n": 86, + "action_gap": 0.0038813373539596796, + "success_auc": 0.4214963119072708, + "succ_rate": 0.151162788271904 + }, + "7": { + "n": 140, + "action_gap": -0.0022797761484980583, + "success_auc": 0.7220990391722099, + "succ_rate": 0.2928571403026581 + }, + "8": { + "n": 128, + "action_gap": 0.007921185344457626, + "success_auc": 0.5657476139978791, + "succ_rate": 0.359375 + }, + "9": { + "n": 94, + "action_gap": -0.0014507672749459743, + "success_auc": 0.4441391941391941, + "succ_rate": 0.5531914830207825 + } + }, + "by_horizon": { + "0-50": { + "n": 124, + "action_gap": 0.027390604838728905, + "action_winrate": 0.5887096774193549, + "q_mean": 0.19646181166172028 + }, + "50-100": { + "n": 126, + "action_gap": 0.008937668986618519, + "action_winrate": 0.5952380952380952, + "q_mean": 0.035325318574905396 + }, + "100-200": { + "n": 255, + "action_gap": -0.0027388862799853086, + "action_winrate": 0.4980392156862745, + "q_mean": 0.018841728568077087 + }, + "200+": { + "n": 519, + "action_gap": -0.0014043253613635898, + "action_winrate": 0.47398843930635837, + "q_mean": 0.00328398821875453 + } + }, + "latent_std_min": 0.13129401206970215, + "q_action_gap": 0.0030227736569941044, + "q_action_winrate": 0.5087890625, + "q_success_auc": 0.6288637560706539, + "q_mean": 0.034493446350097656 + }, + { + "step": 14000, + "reward_auc": 0.9906342913776016, + "cfm_val": 0.11462379992008209, + "per_task": { + "0": { + "n": 89, + "action_gap": 0.005121784750372171, + "success_auc": 0.665079365079365, + "succ_rate": 0.3932584226131439 + }, + "1": { + "n": 115, + "action_gap": -0.007077975198626518, + "success_auc": 0.5030637254901961, + "succ_rate": 0.4434782564640045 + }, + "2": { + "n": 167, + "action_gap": 0.012538731098175049, + "success_auc": 0.7364824717765894, + "succ_rate": 0.4071856141090393 + }, + "3": { + "n": 110, + "action_gap": 0.0010763962054625154, + "success_auc": 0.6112637362637363, + "succ_rate": 0.23636363446712494 + }, + "4": { + "n": 63, + "action_gap": 0.0034723386634141207, + "success_auc": 0.7493606138107417, + "succ_rate": 0.2698412835597992 + }, + "5": { + "n": 23, + "action_gap": -0.007009751163423061, + "success_auc": 0.9230769230769231, + "succ_rate": 0.5652173757553101 + }, + "6": { + "n": 88, + "action_gap": 0.00752568244934082, + "success_auc": 0.7718550106609808, + "succ_rate": 0.23863635957241058 + }, + "7": { + "n": 177, + "action_gap": -0.004055559169501066, + "success_auc": 0.7535563751317176, + "succ_rate": 0.4124293923377991 + }, + "8": { + "n": 107, + "action_gap": 0.010423188097774982, + "success_auc": 0.5270785659801678, + "succ_rate": 0.35514017939567566 + }, + "9": { + "n": 85, + "action_gap": 0.03035472333431244, + "success_auc": 0.5923645320197044, + "succ_rate": 0.658823549747467 + } + }, + "by_horizon": { + "0-50": { + "n": 118, + "action_gap": 0.029233518987894058, + "action_winrate": 0.6016949152542372, + "q_mean": 0.3040999472141266 + }, + "50-100": { + "n": 123, + "action_gap": 0.004453870002180338, + "action_winrate": 0.5284552845528455, + "q_mean": 0.050180476158857346 + }, + "100-200": { + "n": 242, + "action_gap": 0.0020689768716692924, + "action_winrate": 0.48760330578512395, + "q_mean": 0.015485279262065887 + }, + "200+": { + "n": 541, + "action_gap": 0.001947433571331203, + "action_winrate": 0.48613678373382624, + "q_mean": 0.013620138168334961 + } + }, + "latent_std_min": 0.12894012033939362, + "q_action_gap": 0.005421518348157406, + "q_action_winrate": 0.5048828125, + "q_success_auc": 0.6192664600960072, + "q_mean": 0.05192571133375168 + }, + { + "step": 16000, + "reward_auc": 0.9956026204792247, + "cfm_val": 0.13298256695270538, + "per_task": { + "0": { + "n": 81, + "action_gap": 0.012630690820515156, + "success_auc": 0.8055944055944056, + "succ_rate": 0.32098764181137085 + }, + "1": { + "n": 129, + "action_gap": -0.0008594573009759188, + "success_auc": 0.6262183235867447, + "succ_rate": 0.44186046719551086 + }, + "2": { + "n": 152, + "action_gap": 0.010547131299972534, + "success_auc": 0.8338224504768892, + "succ_rate": 0.3815789520740509 + }, + "3": { + "n": 109, + "action_gap": -0.00010792343528009951, + "success_auc": 0.6195238095238095, + "succ_rate": 0.2293577939271927 + }, + "4": { + "n": 105, + "action_gap": 0.02172073908150196, + "success_auc": 0.6946938775510204, + "succ_rate": 0.3333333432674408 + }, + "5": { + "n": 24, + "action_gap": -0.0010894726729020476, + "success_auc": 0.993006993006993, + "succ_rate": 0.5416666865348816 + }, + "6": { + "n": 77, + "action_gap": 0.0006615500897169113, + "success_auc": 0.5631578947368421, + "succ_rate": 0.25974026322364807 + }, + "7": { + "n": 132, + "action_gap": -0.002495224354788661, + "success_auc": 0.788235294117647, + "succ_rate": 0.35606059432029724 + }, + "8": { + "n": 123, + "action_gap": 0.004555290564894676, + "success_auc": 0.6388888888888888, + "succ_rate": 0.2926829159259796 + }, + "9": { + "n": 92, + "action_gap": 0.00992683507502079, + "success_auc": 0.5723958333333333, + "succ_rate": 0.6521739363670349 + } + }, + "by_horizon": { + "0-50": { + "n": 120, + "action_gap": 0.04743295535445213, + "action_winrate": 0.5416666666666666, + "q_mean": 0.16258755326271057 + }, + "50-100": { + "n": 123, + "action_gap": -0.004087105859071016, + "action_winrate": 0.5040650406504065, + "q_mean": 0.012095688842236996 + }, + "100-200": { + "n": 241, + "action_gap": 0.0004168970917817205, + "action_winrate": 0.43983402489626555, + "q_mean": 0.00493627181276679 + }, + "200+": { + "n": 540, + "action_gap": 0.0012288391590118408, + "action_winrate": 0.46296296296296297, + "q_mean": 0.005437801126390696 + } + }, + "latent_std_min": 0.11616120487451553, + "q_action_gap": 0.00581375602632761, + "q_action_winrate": 0.4716796875, + "q_success_auc": 0.6760932932653873, + "q_mean": 0.02453547902405262 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/critic_base_history.json b/frozen/rsm_libero_freeze_20261002/results/critic_base_history.json new file mode 100644 index 0000000000000000000000000000000000000000..a4b18afb4b012336c8203146d106e40120423540 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/critic_base_history.json @@ -0,0 +1,786 @@ +[ + { + "step": 2000, + "reward_auc": 0.9877931945820945, + "cfm_val": 0.2719613313674927, + "per_task": { + "0": { + "n": 100, + "action_gap": 0.006409567780792713, + "success_auc": 0.5019305019305019, + "succ_rate": 0.3700000047683716 + }, + "1": { + "n": 137, + "action_gap": -0.0006269386503845453, + "success_auc": 0.42838709677419357, + "succ_rate": 0.45255473256111145 + }, + "2": { + "n": 156, + "action_gap": -0.007360421121120453, + "success_auc": 0.48328664799253035, + "succ_rate": 0.32692307233810425 + }, + "3": { + "n": 107, + "action_gap": -0.0035040834918618202, + "success_auc": 0.4421338155515371, + "succ_rate": 0.2616822421550751 + }, + "4": { + "n": 76, + "action_gap": 0.00958211813122034, + "success_auc": 0.5010570824524313, + "succ_rate": 0.43421053886413574 + }, + "5": { + "n": 26, + "action_gap": 0.016778195276856422, + "success_auc": 0.7712418300653595, + "succ_rate": 0.6538461446762085 + }, + "6": { + "n": 93, + "action_gap": 0.0034999591298401356, + "success_auc": 0.4662698412698413, + "succ_rate": 0.22580644488334656 + }, + "7": { + "n": 129, + "action_gap": 0.002188619691878557, + "success_auc": 0.5111572392319668, + "succ_rate": 0.3643410801887512 + }, + "8": { + "n": 97, + "action_gap": 0.004824227187782526, + "success_auc": 0.49910793933987513, + "succ_rate": 0.39175257086753845 + }, + "9": { + "n": 103, + "action_gap": 0.0015593749703839421, + "success_auc": 0.49882903981264637, + "succ_rate": 0.5922330021858215 + } + }, + "by_horizon": { + "0-50": { + "n": 115, + "action_gap": 0.04457010701298714, + "action_winrate": 0.5391304347826087, + "q_mean": 0.258619099855423 + }, + "50-100": { + "n": 130, + "action_gap": 0.0029214469250291586, + "action_winrate": 0.5538461538461539, + "q_mean": 0.059412311762571335 + }, + "100-200": { + "n": 245, + "action_gap": -0.006007762625813484, + "action_winrate": 0.4489795918367347, + "q_mean": 0.03499697521328926 + }, + "200+": { + "n": 534, + "action_gap": -0.00487018097192049, + "action_winrate": 0.5056179775280899, + "q_mean": 0.016915302723646164 + } + }, + "latent_std_min": 0.15928788483142853, + "q_action_gap": 0.0013991909800097346, + "q_action_winrate": 0.501953125, + "q_success_auc": 0.49751061560443544, + "q_mean": 0.05378107726573944 + }, + { + "step": 4000, + "reward_auc": 0.9918061033043611, + "cfm_val": 0.17078743875026703, + "per_task": { + "0": { + "n": 90, + "action_gap": 0.006965033244341612, + "success_auc": 0.6233836206896551, + "succ_rate": 0.35555556416511536 + }, + "1": { + "n": 104, + "action_gap": -0.004016174003481865, + "success_auc": 0.4863636363636364, + "succ_rate": 0.42307692766189575 + }, + "2": { + "n": 138, + "action_gap": -0.007320027332752943, + "success_auc": 0.4710648148148148, + "succ_rate": 0.3478260934352875 + }, + "3": { + "n": 124, + "action_gap": 0.016234273090958595, + "success_auc": 0.4537373737373737, + "succ_rate": 0.2016129046678543 + }, + "4": { + "n": 101, + "action_gap": 0.004218746442347765, + "success_auc": 0.542572463768116, + "succ_rate": 0.31683167815208435 + }, + "5": { + "n": 18, + "action_gap": 0.028326719999313354, + "success_auc": 0.7901234567901234, + "succ_rate": 0.5 + }, + "6": { + "n": 80, + "action_gap": 0.028160223737359047, + "success_auc": 0.6538201487491548, + "succ_rate": 0.36250001192092896 + }, + "7": { + "n": 159, + "action_gap": 0.0043665445409715176, + "success_auc": 0.609965034965035, + "succ_rate": 0.3459119498729706 + }, + "8": { + "n": 129, + "action_gap": 0.005183717235922813, + "success_auc": 0.6113013698630136, + "succ_rate": 0.43410852551460266 + }, + "9": { + "n": 81, + "action_gap": 0.028182461857795715, + "success_auc": 0.4458064516129032, + "succ_rate": 0.6172839403152466 + } + }, + "by_horizon": { + "0-50": { + "n": 134, + "action_gap": 0.06312573701143265, + "action_winrate": 0.5970149253731343, + "q_mean": 0.28379589319229126 + }, + "50-100": { + "n": 121, + "action_gap": 0.012869387865066528, + "action_winrate": 0.5537190082644629, + "q_mean": 0.03760857135057449 + }, + "100-200": { + "n": 249, + "action_gap": -0.0013214896898716688, + "action_winrate": 0.5461847389558233, + "q_mean": 0.022991467267274857 + }, + "200+": { + "n": 520, + "action_gap": -0.003154587931931019, + "action_winrate": 0.43653846153846154, + "q_mean": 0.016621064394712448 + } + }, + "latent_std_min": 0.1195826530456543, + "q_action_gap": 0.007858015596866608, + "q_action_winrate": 0.498046875, + "q_success_auc": 0.5521330500163452, + "q_mean": 0.05561242252588272 + }, + { + "step": 6000, + "reward_auc": 0.9877277214394687, + "cfm_val": 0.14670471847057343, + "per_task": { + "0": { + "n": 114, + "action_gap": -0.0017151666106656194, + "success_auc": 0.6476650563607085, + "succ_rate": 0.3947368562221527 + }, + "1": { + "n": 117, + "action_gap": -0.00499859219416976, + "success_auc": 0.36208955223880596, + "succ_rate": 0.4273504316806793 + }, + "2": { + "n": 151, + "action_gap": -0.009663020260632038, + "success_auc": 0.48579545454545453, + "succ_rate": 0.3642384111881256 + }, + "3": { + "n": 95, + "action_gap": 0.013272133655846119, + "success_auc": 0.3953846153846154, + "succ_rate": 0.31578946113586426 + }, + "4": { + "n": 92, + "action_gap": 0.008168470114469528, + "success_auc": 0.6130831643002028, + "succ_rate": 0.3695652186870575 + }, + "5": { + "n": 28, + "action_gap": 0.010491804219782352, + "success_auc": 0.5935828877005348, + "succ_rate": 0.3928571343421936 + }, + "6": { + "n": 79, + "action_gap": -0.0009604941587895155, + "success_auc": 0.6393034825870647, + "succ_rate": 0.15189872682094574 + }, + "7": { + "n": 143, + "action_gap": 0.002327292924746871, + "success_auc": 0.6429769392033543, + "succ_rate": 0.37062937021255493 + }, + "8": { + "n": 123, + "action_gap": 0.003327814396470785, + "success_auc": 0.48412698412698413, + "succ_rate": 0.3414634168148041 + }, + "9": { + "n": 82, + "action_gap": 0.004303997382521629, + "success_auc": 0.3740350877192982, + "succ_rate": 0.6951219439506531 + } + }, + "by_horizon": { + "0-50": { + "n": 120, + "action_gap": 0.017688516527414322, + "action_winrate": 0.5833333333333334, + "q_mean": 0.19690124690532684 + }, + "50-100": { + "n": 140, + "action_gap": -0.0035559427924454212, + "action_winrate": 0.5142857142857142, + "q_mean": 0.035192739218473434 + }, + "100-200": { + "n": 248, + "action_gap": -0.006306999828666449, + "action_winrate": 0.5, + "q_mean": 0.010996377095580101 + }, + "200+": { + "n": 516, + "action_gap": 0.0019867457449436188, + "action_winrate": 0.48643410852713176, + "q_mean": 0.012091262266039848 + } + }, + "latent_std_min": 0.12486922740936279, + "q_action_gap": 0.00106036604847759, + "q_action_winrate": 0.5048828125, + "q_success_auc": 0.5337773009736251, + "q_mean": 0.0366419181227684 + }, + { + "step": 8000, + "reward_auc": 0.9926145839060238, + "cfm_val": 0.13243581354618073, + "per_task": { + "0": { + "n": 103, + "action_gap": -0.007044427562505007, + "success_auc": 0.6183978873239436, + "succ_rate": 0.3106796145439148 + }, + "1": { + "n": 115, + "action_gap": 0.00042230208055116236, + "success_auc": 0.5823244552058111, + "succ_rate": 0.5130434632301331 + }, + "2": { + "n": 144, + "action_gap": 0.0024494652170687914, + "success_auc": 0.5689453125, + "succ_rate": 0.4444444477558136 + }, + "3": { + "n": 112, + "action_gap": 0.005480488296598196, + "success_auc": 0.4014336917562724, + "succ_rate": 0.2767857015132904 + }, + "4": { + "n": 102, + "action_gap": 0.0025110540445894003, + "success_auc": 0.5699013157894737, + "succ_rate": 0.37254902720451355 + }, + "5": { + "n": 26, + "action_gap": 0.00364819192327559, + "success_auc": 0.7810650887573964, + "succ_rate": 0.5 + }, + "6": { + "n": 79, + "action_gap": -0.0009238740894943476, + "success_auc": 0.6669085631349783, + "succ_rate": 0.3291139304637909 + }, + "7": { + "n": 127, + "action_gap": -0.00818592868745327, + "success_auc": 0.6187012987012988, + "succ_rate": 0.3937007784843445 + }, + "8": { + "n": 134, + "action_gap": 0.01101685967296362, + "success_auc": 0.4859437751004016, + "succ_rate": 0.3805970251560211 + }, + "9": { + "n": 82, + "action_gap": 0.03006887063384056, + "success_auc": 0.5240384615384616, + "succ_rate": 0.6829268336296082 + } + }, + "by_horizon": { + "0-50": { + "n": 117, + "action_gap": 0.06807809323072433, + "action_winrate": 0.6068376068376068, + "q_mean": 0.29577046632766724 + }, + "50-100": { + "n": 125, + "action_gap": 0.007352953311055899, + "action_winrate": 0.552, + "q_mean": 0.035094257444143295 + }, + "100-200": { + "n": 277, + "action_gap": -0.011254442855715752, + "action_winrate": 0.4729241877256318, + "q_mean": 0.031610190868377686 + }, + "200+": { + "n": 505, + "action_gap": -0.004548436962068081, + "action_winrate": 0.4316831683168317, + "q_mean": 0.014708572998642921 + } + }, + "latent_std_min": 0.13052812218666077, + "q_action_gap": 0.003388490993529558, + "q_action_winrate": 0.4775390625, + "q_success_auc": 0.5410753705455692, + "q_mean": 0.05388259142637253 + }, + { + "step": 10000, + "reward_auc": 0.9952735788801362, + "cfm_val": 0.12641239166259766, + "per_task": { + "0": { + "n": 93, + "action_gap": 0.00958632118999958, + "success_auc": 0.5436280137772675, + "succ_rate": 0.2795698940753937 + }, + "1": { + "n": 114, + "action_gap": 0.004666919354349375, + "success_auc": 0.5947611710323575, + "succ_rate": 0.5175438523292542 + }, + "2": { + "n": 149, + "action_gap": 0.008862324059009552, + "success_auc": 0.617196056955093, + "succ_rate": 0.4429530203342438 + }, + "3": { + "n": 115, + "action_gap": -8.788835839368403e-05, + "success_auc": 0.4393939393939394, + "succ_rate": 0.2869565188884735 + }, + "4": { + "n": 112, + "action_gap": -0.0038778905291110277, + "success_auc": 0.7638474295190714, + "succ_rate": 0.4017857015132904 + }, + "5": { + "n": 23, + "action_gap": 0.013691545464098454, + "success_auc": 0.8409090909090909, + "succ_rate": 0.52173912525177 + }, + "6": { + "n": 83, + "action_gap": 0.009849518537521362, + "success_auc": 0.6374807987711214, + "succ_rate": 0.2530120611190796 + }, + "7": { + "n": 134, + "action_gap": -0.0017945445142686367, + "success_auc": 0.7155835080363382, + "succ_rate": 0.3955223858356476 + }, + "8": { + "n": 140, + "action_gap": -9.543576743453741e-05, + "success_auc": 0.5804810360777058, + "succ_rate": 0.3285714387893677 + }, + "9": { + "n": 61, + "action_gap": -0.0006616313476115465, + "success_auc": 0.5769230769230769, + "succ_rate": 0.5737704634666443 + } + }, + "by_horizon": { + "0-50": { + "n": 110, + "action_gap": 0.04189131036400795, + "action_winrate": 0.6090909090909091, + "q_mean": 0.22503556311130524 + }, + "50-100": { + "n": 145, + "action_gap": 0.002932266565039754, + "action_winrate": 0.503448275862069, + "q_mean": 0.01357592549175024 + }, + "100-200": { + "n": 255, + "action_gap": -0.0037341732531785965, + "action_winrate": 0.4470588235294118, + "q_mean": 0.008922974579036236 + }, + "200+": { + "n": 514, + "action_gap": -0.0018349618185311556, + "action_winrate": 0.4669260700389105, + "q_mean": 0.007097852881997824 + } + }, + "latent_std_min": 0.11313363909721375, + "q_action_gap": 0.0030642952769994736, + "q_action_winrate": 0.482421875, + "q_success_auc": 0.5804743292800618, + "q_mean": 0.0318809375166893 + }, + { + "step": 12000, + "reward_auc": 0.9875996015936255, + "cfm_val": 0.14582675695419312, + "per_task": { + "0": { + "n": 106, + "action_gap": 0.019602810963988304, + "success_auc": 0.5134803921568627, + "succ_rate": 0.3207547068595886 + }, + "1": { + "n": 127, + "action_gap": 0.006570063065737486, + "success_auc": 0.5638350720317934, + "succ_rate": 0.4803149700164795 + }, + "2": { + "n": 150, + "action_gap": -0.005994896870106459, + "success_auc": 0.618923449431924, + "succ_rate": 0.3933333456516266 + }, + "3": { + "n": 114, + "action_gap": 0.0037662810645997524, + "success_auc": 0.44189016602809705, + "succ_rate": 0.2368421107530594 + }, + "4": { + "n": 89, + "action_gap": 0.016635524109005928, + "success_auc": 0.6725571725571725, + "succ_rate": 0.4157303273677826 + }, + "5": { + "n": 17, + "action_gap": 0.027434324845671654, + "success_auc": 1.0, + "succ_rate": 0.529411792755127 + }, + "6": { + "n": 80, + "action_gap": 0.008997109718620777, + "success_auc": 0.7337526205450734, + "succ_rate": 0.3375000059604645 + }, + "7": { + "n": 123, + "action_gap": -0.0023393582087010145, + "success_auc": 0.738204833141542, + "succ_rate": 0.35772356390953064 + }, + "8": { + "n": 135, + "action_gap": 0.012750799767673016, + "success_auc": 0.5908029878618114, + "succ_rate": 0.3777777850627899 + }, + "9": { + "n": 83, + "action_gap": 0.04165320843458176, + "success_auc": 0.6290322580645161, + "succ_rate": 0.6265060305595398 + } + }, + "by_horizon": { + "0-50": { + "n": 141, + "action_gap": 0.06903799623250961, + "action_winrate": 0.6453900709219859, + "q_mean": 0.1966162919998169 + }, + "50-100": { + "n": 137, + "action_gap": 0.013401753269135952, + "action_winrate": 0.5693430656934306, + "q_mean": 0.04996121674776077 + }, + "100-200": { + "n": 262, + "action_gap": -0.002184053650125861, + "action_winrate": 0.5229007633587787, + "q_mean": 0.00442706560716033 + }, + "200+": { + "n": 484, + "action_gap": -0.0020624196622520685, + "action_winrate": 0.47107438016528924, + "q_mean": 0.004376966040581465 + } + }, + "latent_std_min": 0.11370516568422318, + "q_action_gap": 0.009765589609742165, + "q_action_winrate": 0.521484375, + "q_success_auc": 0.598435692470269, + "q_mean": 0.03695891052484512 + }, + { + "step": 14000, + "reward_auc": 0.9930000897424393, + "cfm_val": 0.11024355888366699, + "per_task": { + "0": { + "n": 105, + "action_gap": 0.006106030195951462, + "success_auc": 0.647887323943662, + "succ_rate": 0.32380953431129456 + }, + "1": { + "n": 100, + "action_gap": 0.0031750958878546953, + "success_auc": 0.5752709755118426, + "succ_rate": 0.4699999988079071 + }, + "2": { + "n": 146, + "action_gap": 0.0011619975557550788, + "success_auc": 0.7397233586596532, + "succ_rate": 0.4041095972061157 + }, + "3": { + "n": 132, + "action_gap": -0.001316036214120686, + "success_auc": 0.5952871870397644, + "succ_rate": 0.2651515007019043 + }, + "4": { + "n": 85, + "action_gap": 0.03164169192314148, + "success_auc": 0.5798368298368298, + "succ_rate": 0.38823530077934265 + }, + "5": { + "n": 22, + "action_gap": 0.0435030423104763, + "success_auc": 1.0, + "succ_rate": 0.5454545617103577 + }, + "6": { + "n": 87, + "action_gap": 0.019851239398121834, + "success_auc": 0.6884920634920635, + "succ_rate": 0.27586206793785095 + }, + "7": { + "n": 129, + "action_gap": -0.0024974446278065443, + "success_auc": 0.7235294117647059, + "succ_rate": 0.26356589794158936 + }, + "8": { + "n": 137, + "action_gap": 0.0035060448572039604, + "success_auc": 0.5772413793103448, + "succ_rate": 0.36496350169181824 + }, + "9": { + "n": 81, + "action_gap": 0.03467779606580734, + "success_auc": 0.4585714285714286, + "succ_rate": 0.6913580298423767 + } + }, + "by_horizon": { + "0-50": { + "n": 128, + "action_gap": 0.05899292230606079, + "action_winrate": 0.609375, + "q_mean": 0.30233797430992126 + }, + "50-100": { + "n": 139, + "action_gap": 0.004043913912028074, + "action_winrate": 0.49640287769784175, + "q_mean": 0.045786742120981216 + }, + "100-200": { + "n": 248, + "action_gap": 0.0032756340224295855, + "action_winrate": 0.5, + "q_mean": 0.016110241413116455 + }, + "200+": { + "n": 509, + "action_gap": 0.0007264256710186601, + "action_winrate": 0.4911591355599214, + "q_mean": 0.014695562422275543 + } + }, + "latent_std_min": 0.1204683780670166, + "q_action_gap": 0.009077447466552258, + "q_action_winrate": 0.5087890625, + "q_success_auc": 0.6366617838541667, + "q_mean": 0.055213868618011475 + }, + { + "step": 16000, + "reward_auc": 0.9877941981390257, + "cfm_val": 0.13146889209747314, + "per_task": { + "0": { + "n": 96, + "action_gap": 0.004865909926593304, + "success_auc": 0.7935483870967742, + "succ_rate": 0.3229166567325592 + }, + "1": { + "n": 119, + "action_gap": 0.001266196253709495, + "success_auc": 0.5974431818181818, + "succ_rate": 0.462184876203537 + }, + "2": { + "n": 145, + "action_gap": 0.0035740588791668415, + "success_auc": 0.8214736842105264, + "succ_rate": 0.3448275923728943 + }, + "3": { + "n": 107, + "action_gap": -0.00022753907251171768, + "success_auc": 0.6809024979854955, + "succ_rate": 0.3177570104598999 + }, + "4": { + "n": 98, + "action_gap": 0.028498968109488487, + "success_auc": 0.662719298245614, + "succ_rate": 0.3877550959587097 + }, + "5": { + "n": 20, + "action_gap": -0.010041766799986362, + "success_auc": 0.9797979797979798, + "succ_rate": 0.44999998807907104 + }, + "6": { + "n": 84, + "action_gap": 0.003478787373751402, + "success_auc": 0.5842781557067271, + "succ_rate": 0.25 + }, + "7": { + "n": 141, + "action_gap": 0.0013932707952335477, + "success_auc": 0.7867276887871854, + "succ_rate": 0.326241135597229 + }, + "8": { + "n": 115, + "action_gap": -0.003131964011117816, + "success_auc": 0.45934959349593496, + "succ_rate": 0.2869565188884735 + }, + "9": { + "n": 99, + "action_gap": 0.009113285690546036, + "success_auc": 0.5525423728813559, + "succ_rate": 0.5959596037864685 + } + }, + "by_horizon": { + "0-50": { + "n": 134, + "action_gap": 0.029561201110482216, + "action_winrate": 0.5895522388059702, + "q_mean": 0.18105097115039825 + }, + "50-100": { + "n": 127, + "action_gap": 0.008339605294167995, + "action_winrate": 0.5433070866141733, + "q_mean": 0.015619616955518723 + }, + "100-200": { + "n": 257, + "action_gap": -0.0032016062177717686, + "action_winrate": 0.44357976653696496, + "q_mean": 0.004435449372977018 + }, + "200+": { + "n": 506, + "action_gap": 0.001061168615706265, + "action_winrate": 0.5158102766798419, + "q_mean": 0.010990219190716743 + } + }, + "latent_std_min": 0.11561814695596695, + "q_action_gap": 0.0046235048212111, + "q_action_winrate": 0.5107421875, + "q_success_auc": 0.6598699763593381, + "q_mean": 0.03217332437634468 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/ope_null_base.json b/frozen/rsm_libero_freeze_20261002/results/ope_null_base.json new file mode 100644 index 0000000000000000000000000000000000000000..f7cede01501b5cf3eec74d2a9d2e352e54c85667 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/ope_null_base.json @@ -0,0 +1,51 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/ope_null_base", + "batch": 512, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 16, + "bc_steps": 6000, + "ratio_steps": 4000, + "wend_steps": 4000, + "pi_mode": "all", + "seed": 0, + "in_ram": 0, + "d_z": 256 + }, + "calibration": { + "calib_scale": 5.237595756905884, + "E_mu[W_chunk]": 0.18588261306285858, + "E_mu[w_endpoint]": 1.0162439346313477, + "w_p05": 0.178162083029747, + "w_p50": 0.769451379776001, + "w_p95": 2.4898264408111572, + "ess_frac": 0.5588774085044861, + "corr_w_vs_W": 0.4341499684578188 + }, + "horizon": { + "restart_p": 0.505050505050505, + "mean_hops": 1.505050505050505, + "mean_hops_untruncated": 2.020408163265306, + "effective_frames": 75.25252525252519, + "gamma_effective": 0.9867114093959731, + "gamma_nominal": 0.99, + "truncation_mass": 0.25507601265177016 + }, + "value": { + "pi_mode": "all", + "rel_shift_IS_vs_noIS": 0.18422631919384003, + "gate_expectation": "null: weights ~1 and rel_shift should be SMALL", + "auc_success_IS": 0.6577155507688626, + "auc_success_noIS": 0.6631035720696464, + "q_mean_IS": 4.157533168792725, + "q_mean_noIS": 4.162613391876221, + "ess_particles": 0.6232997179031372, + "depth": 2, + "beta": 0.98, + "gamma": 0.99 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/ope_signal_base.json b/frozen/rsm_libero_freeze_20261002/results/ope_signal_base.json new file mode 100644 index 0000000000000000000000000000000000000000..f3ee9d545264b17c20a9aefa1444adb5615de8d6 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/ope_signal_base.json @@ -0,0 +1,51 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/ope_signal_base", + "batch": 512, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 16, + "bc_steps": 6000, + "ratio_steps": 4000, + "wend_steps": 4000, + "pi_mode": "succ", + "seed": 0, + "in_ram": 0, + "d_z": 256 + }, + "calibration": { + "calib_scale": 5.228771711827236, + "E_mu[W_chunk]": 0.1858443021774292, + "E_mu[w_endpoint]": 1.0155830383300781, + "w_p05": 0.18472248315811157, + "w_p50": 0.7708338499069214, + "w_p95": 2.5086076259613037, + "ess_frac": 0.5631883144378662, + "corr_w_vs_W": 0.4324678136650354 + }, + "horizon": { + "restart_p": 0.505050505050505, + "mean_hops": 1.505050505050505, + "mean_hops_untruncated": 2.020408163265306, + "effective_frames": 75.25252525252519, + "gamma_effective": 0.9867114093959731, + "gamma_nominal": 0.99, + "truncation_mass": 0.25507601265177016 + }, + "value": { + "pi_mode": "succ", + "rel_shift_IS_vs_noIS": 0.19249221682548523, + "gate_expectation": "signal: pi is better than mu, Q should move UP", + "auc_success_IS": 0.6645485550170526, + "auc_success_noIS": 0.6625660663355871, + "q_mean_IS": 4.31668758392334, + "q_mean_noIS": 4.41709566116333, + "ess_particles": 0.63212651014328, + "depth": 2, + "beta": 0.98, + "gamma": 0.99 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/ope_smoketest_smooth.json b/frozen/rsm_libero_freeze_20261002/results/ope_smoketest_smooth.json new file mode 100644 index 0000000000000000000000000000000000000000..4e510bf928ac191025f9036e3b34c895f94f950c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/ope_smoketest_smooth.json @@ -0,0 +1,53 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/ope_smoketest_smooth", + "batch": 512, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "bc_steps": 3000, + "ratio_steps": 3000, + "wend_steps": 3000, + "pi_mode": "all", + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "ratio_smooth": 0.5, + "d_z": 256 + }, + "calibration": { + "calib_scale": 4.564842539855811, + "E_mu[W_chunk]": 0.22500823438167572, + "E_mu[w_endpoint]": 1.0092662572860718, + "w_p05": 0.18696357309818268, + "w_p50": 0.8847378492355347, + "w_p95": 2.304257869720459, + "ess_frac": 0.6249898076057434, + "corr_w_vs_W": 0.23125867938004438 + }, + "horizon": { + "restart_p": 0.505050505050505, + "mean_hops": 1.505050505050505, + "mean_hops_untruncated": 2.020408163265306, + "effective_frames": 75.25252525252519, + "gamma_effective": 0.9867114093959731, + "gamma_nominal": 0.99, + "truncation_mass": 0.25507601265177016 + }, + "value": { + "pi_mode": "all", + "rel_shift_IS_vs_noIS": 0.21909917891025543, + "gate_expectation": "null: weights ~1 and rel_shift should be SMALL", + "auc_success_IS": 0.6674714294261952, + "auc_success_noIS": 0.6499461497038234, + "q_mean_IS": 4.233530044555664, + "q_mean_noIS": 4.331247329711914, + "ess_particles": 0.6933380365371704, + "depth": 2, + "beta": 0.98, + "gamma": 0.99 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/ope_smooth_signal.json b/frozen/rsm_libero_freeze_20261002/results/ope_smooth_signal.json new file mode 100644 index 0000000000000000000000000000000000000000..260781c0e5808442cbeefa1e9ab747c54dbdd25a --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/ope_smooth_signal.json @@ -0,0 +1,53 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/ope_smooth_signal", + "batch": 512, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "bc_steps": 3000, + "ratio_steps": 3000, + "wend_steps": 3000, + "pi_mode": "succ", + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "ratio_smooth": 0.5, + "d_z": 256 + }, + "calibration": { + "calib_scale": 3.764181771045251, + "E_mu[W_chunk]": 0.2209673523902893, + "E_mu[w_endpoint]": 1.008519172668457, + "w_p05": 0.31671518087387085, + "w_p50": 0.9019677042961121, + "w_p95": 2.0570905208587646, + "ess_frac": 0.7216845154762268, + "corr_w_vs_W": 0.3029320624145348 + }, + "horizon": { + "restart_p": 0.505050505050505, + "mean_hops": 1.505050505050505, + "mean_hops_untruncated": 2.020408163265306, + "effective_frames": 75.25252525252519, + "gamma_effective": 0.9867114093959731, + "gamma_nominal": 0.99, + "truncation_mass": 0.25507601265177016 + }, + "value": { + "pi_mode": "succ", + "rel_shift_IS_vs_noIS": 0.2472643256187439, + "gate_expectation": "signal: pi is better than mu, Q should move UP", + "auc_success_IS": 0.6510411057260815, + "auc_success_noIS": 0.6556542810985461, + "q_mean_IS": 4.378605842590332, + "q_mean_noIS": 4.441417694091797, + "ess_particles": 0.9089834690093994, + "depth": 2, + "beta": 0.98, + "gamma": 0.99 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/sweep_actcon.json b/frozen/rsm_libero_freeze_20261002/results/sweep_actcon.json new file mode 100644 index 0000000000000000000000000000000000000000..8b8b7277e2cc8b005a41d8026622464a0371d20f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/sweep_actcon.json @@ -0,0 +1,230 @@ +[ + { + "beta": 0.96, + "depth": 1, + "eff_frames": 24.99999999999998, + "gamma_eff": 0.96, + "gap_pooled": -51.546424865722656, + "win_pooled": 0.46142578125, + "gap_pooled_crosstask": -125.83489990234375, + "win_pooled_crosstask": 0.5009765625, + "state_auc": 0.5813405354817708, + "gap_0-50": 80.0497817993164, + "win_0-50": 0.6206896551724138, + "gap_50-100": -43.533599853515625, + "win_50-100": 0.576271186440678, + "gap_100-200": -55.44401931762695, + "win_100-200": 0.46938775510204084, + "gap_200+": -83.900634765625, + "win_200+": 0.3930254476908577 + }, + { + "beta": 0.96, + "depth": 2, + "eff_frames": 48.74999999999993, + "gamma_eff": 0.9794871794871794, + "gap_pooled": 34.69417953491211, + "win_pooled": 0.65234375, + "gap_pooled_crosstask": -4.634228706359863, + "win_pooled_crosstask": 0.69287109375, + "state_auc": 0.5486317952473958, + "gap_0-50": 162.04180908203125, + "win_0-50": 0.7509578544061303, + "gap_50-100": 40.9615592956543, + "win_50-100": 0.6694915254237288, + "gap_100-200": 11.722060203552246, + "win_100-200": 0.6224489795918368, + "gap_200+": 12.582496643066406, + "win_200+": 0.6380772855796418 + }, + { + "beta": 0.96, + "depth": 3, + "eff_frames": 71.31249999999993, + "gamma_eff": 0.985977212971078, + "gap_pooled": -28.83934211730957, + "win_pooled": 0.5517578125, + "gap_pooled_crosstask": -71.80011749267578, + "win_pooled_crosstask": 0.5625, + "state_auc": 0.5696919759114584, + "gap_0-50": 97.36705017089844, + "win_0-50": 0.6781609195402298, + "gap_50-100": -16.318790435791016, + "win_50-100": 0.5550847457627118, + "gap_100-200": -48.95175552368164, + "win_100-200": 0.4959183673469388, + "gap_200+": -53.38188552856445, + "win_200+": 0.5457115928369463 + }, + { + "beta": 0.98, + "depth": 1, + "eff_frames": 49.99999999999996, + "gamma_eff": 0.98, + "gap_pooled": -61.46691131591797, + "win_pooled": 0.46142578125, + "gap_pooled_crosstask": -128.90740966796875, + "win_pooled_crosstask": 0.515625, + "state_auc": 0.600732421875, + "gap_0-50": 79.28109741210938, + "win_0-50": 0.6130268199233716, + "gap_50-100": -55.58386993408203, + "win_50-100": 0.4830508474576271, + "gap_100-200": -63.31771469116211, + "win_100-200": 0.463265306122449, + "gap_200+": -96.5439453125, + "win_200+": 0.4184731385485391 + }, + { + "beta": 0.98, + "depth": 2, + "eff_frames": 97.49999999999986, + "gamma_eff": 0.9897435897435898, + "gap_pooled": 30.28516387939453, + "win_pooled": 0.62646484375, + "gap_pooled_crosstask": -4.869052886962891, + "win_pooled_crosstask": 0.6865234375, + "state_auc": 0.5759409586588542, + "gap_0-50": 156.78802490234375, + "win_0-50": 0.7203065134099617, + "gap_50-100": 38.11271667480469, + "win_50-100": 0.6271186440677966, + "gap_100-200": 9.85483455657959, + "win_100-200": 0.5897959183673469, + "gap_200+": 6.860384464263916, + "win_200+": 0.6201696512723845 + }, + { + "beta": 0.98, + "depth": 3, + "eff_frames": 142.62499999999986, + "gamma_eff": 0.992988606485539, + "gap_pooled": -30.98450469970703, + "win_pooled": 0.53857421875, + "gap_pooled_crosstask": -76.52243041992188, + "win_pooled_crosstask": 0.5615234375, + "state_auc": 0.6020416259765625, + "gap_0-50": 93.0474624633789, + "win_0-50": 0.685823754789272, + "gap_50-100": -7.158599853515625, + "win_50-100": 0.5550847457627118, + "gap_100-200": -56.07952880859375, + "win_100-200": 0.5122448979591837, + "gap_200+": -55.205711364746094, + "win_200+": 0.5108388312912346 + }, + { + "beta": 0.99, + "depth": 1, + "eff_frames": 99.99999999999991, + "gamma_eff": 0.99, + "gap_pooled": -60.12482452392578, + "win_pooled": 0.45654296875, + "gap_pooled_crosstask": -129.4288787841797, + "win_pooled_crosstask": 0.5185546875, + "state_auc": 0.6174367268880209, + "gap_0-50": 83.76277923583984, + "win_0-50": 0.6091954022988506, + "gap_50-100": -40.346195220947266, + "win_50-100": 0.5550847457627118, + "gap_100-200": -67.20990753173828, + "win_100-200": 0.4346938775510204, + "gap_200+": -96.64766693115234, + "win_200+": 0.4071630537229029 + }, + { + "beta": 0.99, + "depth": 2, + "eff_frames": 190.0900900900899, + "gamma_eff": 0.994739336492891, + "gap_pooled": 24.974506378173828, + "win_pooled": 0.61328125, + "gap_pooled_crosstask": -10.323814392089844, + "win_pooled_crosstask": 0.64697265625, + "state_auc": 0.5864532470703125, + "gap_0-50": 148.56842041015625, + "win_0-50": 0.7126436781609196, + "gap_50-100": 36.02408981323242, + "win_50-100": 0.6610169491525424, + "gap_100-200": 2.261622667312622, + "win_100-200": 0.5836734693877551, + "gap_200+": 2.602782964706421, + "win_200+": 0.5918944392082941 + }, + { + "beta": 0.99, + "depth": 3, + "eff_frames": 271.2523334144953, + "gamma_eff": 0.9963133957691271, + "gap_pooled": -26.120960235595703, + "win_pooled": 0.541015625, + "gap_pooled_crosstask": -76.4961929321289, + "win_pooled_crosstask": 0.53173828125, + "state_auc": 0.5991790771484375, + "gap_0-50": 91.29505157470703, + "win_0-50": 0.632183908045977, + "gap_50-100": -0.051404986530542374, + "win_50-100": 0.5932203389830508, + "gap_100-200": -51.6431999206543, + "win_100-200": 0.5040816326530613, + "gap_200+": -49.01643371582031, + "win_200+": 0.5240339302544769 + }, + { + "beta": 0.995, + "depth": 1, + "eff_frames": 199.99999999999983, + "gamma_eff": 0.995, + "gap_pooled": -68.11668395996094, + "win_pooled": 0.4619140625, + "gap_pooled_crosstask": -134.58949279785156, + "win_pooled_crosstask": 0.50146484375, + "state_auc": 0.6300608317057291, + "gap_0-50": 89.25088500976562, + "win_0-50": 0.6245210727969349, + "gap_50-100": -54.56651306152344, + "win_50-100": 0.559322033898305, + "gap_100-200": -72.14842224121094, + "win_100-200": 0.45918367346938777, + "gap_200+": -107.98023223876953, + "win_200+": 0.40150801131008484 + }, + { + "beta": 0.995, + "depth": 2, + "eff_frames": 360.1601601601599, + "gamma_eff": 0.9972234574763758, + "gap_pooled": 15.491418838500977, + "win_pooled": 0.5751953125, + "gap_pooled_crosstask": -22.10919189453125, + "win_pooled_crosstask": 0.6171875, + "state_auc": 0.6097300211588542, + "gap_0-50": 146.7181854248047, + "win_0-50": 0.7088122605363985, + "gap_50-100": 23.76041603088379, + "win_50-100": 0.5720338983050848, + "gap_100-200": -3.270139217376709, + "win_100-200": 0.5346938775510204, + "gap_200+": -9.964289665222168, + "win_200+": 0.5617342130065975 + }, + { + "beta": 0.995, + "depth": 3, + "eff_frames": 488.41654467280046, + "gamma_eff": 0.9979525673097951, + "gap_pooled": -25.263416290283203, + "win_pooled": 0.53662109375, + "gap_pooled_crosstask": -73.59703826904297, + "win_pooled_crosstask": 0.51708984375, + "state_auc": 0.6070821126302083, + "gap_0-50": 102.81361389160156, + "win_0-50": 0.6551724137931034, + "gap_50-100": -12.5304536819458, + "win_50-100": 0.5889830508474576, + "gap_100-200": -42.36178970336914, + "win_100-200": 0.5204081632653061, + "gap_200+": -51.70533752441406, + "win_200+": 0.5032987747408105 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/sweep_actcon01.json b/frozen/rsm_libero_freeze_20261002/results/sweep_actcon01.json new file mode 100644 index 0000000000000000000000000000000000000000..b99b04db04fb7ca934f9971c729e31c8f77a4a52 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/sweep_actcon01.json @@ -0,0 +1,230 @@ +[ + { + "beta": 0.96, + "depth": 1, + "eff_frames": 24.99999999999998, + "gamma_eff": 0.96, + "gap_pooled": 6.30864143371582, + "win_pooled": 0.48974609375, + "gap_pooled_crosstask": 5.91621732711792, + "win_pooled_crosstask": 0.4765625, + "state_auc": 0.6868655641649493, + "gap_0-50": 53.18166732788086, + "win_0-50": 0.6010050251256281, + "gap_50-100": -1.352872610092163, + "win_50-100": 0.5072324011571842, + "gap_100-200": -0.8440123200416565, + "win_100-200": 0.4645354645354645, + "gap_200+": 0.4466739594936371, + "win_200+": 0.4708994708994709 + }, + { + "beta": 0.96, + "depth": 2, + "eff_frames": 48.74999999999993, + "gamma_eff": 0.9794871794871794, + "gap_pooled": 5.7522172927856445, + "win_pooled": 0.4842529296875, + "gap_pooled_crosstask": 3.9665169715881348, + "win_pooled_crosstask": 0.478515625, + "state_auc": 0.6975916856370438, + "gap_0-50": 55.342628479003906, + "win_0-50": 0.5798994974874372, + "gap_50-100": 2.232736349105835, + "win_50-100": 0.5053037608486017, + "gap_100-200": -2.134530782699585, + "win_100-200": 0.46703296703296704, + "gap_200+": -1.439578652381897, + "win_200+": 0.46440596440596443 + }, + { + "beta": 0.96, + "depth": 3, + "eff_frames": 71.31249999999993, + "gamma_eff": 0.985977212971078, + "gap_pooled": 5.2091827392578125, + "win_pooled": 0.48828125, + "gap_pooled_crosstask": 2.6576032638549805, + "win_pooled_crosstask": 0.47998046875, + "state_auc": 0.6982983088828134, + "gap_0-50": 53.2354736328125, + "win_0-50": 0.5758793969849246, + "gap_50-100": 7.161194801330566, + "win_50-100": 0.5226615236258437, + "gap_100-200": -3.719944953918457, + "win_100-200": 0.468031968031968, + "gap_200+": -2.471020221710205, + "win_200+": 0.4684944684944685 + }, + { + "beta": 0.98, + "depth": 1, + "eff_frames": 49.99999999999996, + "gamma_eff": 0.98, + "gap_pooled": 6.295346260070801, + "win_pooled": 0.48291015625, + "gap_pooled_crosstask": 5.396781921386719, + "win_pooled_crosstask": 0.474365234375, + "state_auc": 0.6895984549860658, + "gap_0-50": 54.81524658203125, + "win_0-50": 0.6090452261306533, + "gap_50-100": -0.7992590665817261, + "win_50-100": 0.5284474445515911, + "gap_100-200": -1.1928950548171997, + "win_100-200": 0.47002997002997005, + "gap_200+": 0.05947805568575859, + "win_200+": 0.44757094757094756 + }, + { + "beta": 0.98, + "depth": 2, + "eff_frames": 97.49999999999986, + "gamma_eff": 0.9897435897435898, + "gap_pooled": 5.325685501098633, + "win_pooled": 0.48388671875, + "gap_pooled_crosstask": 3.506357192993164, + "win_pooled_crosstask": 0.4827880859375, + "state_auc": 0.7004525566035722, + "gap_0-50": 53.64113235473633, + "win_0-50": 0.5648241206030151, + "gap_50-100": 5.9683966636657715, + "win_50-100": 0.5274831243972999, + "gap_100-200": -3.4839394092559814, + "win_100-200": 0.46403596403596403, + "gap_200+": -2.1547107696533203, + "win_200+": 0.46320346320346323 + }, + { + "beta": 0.98, + "depth": 3, + "eff_frames": 142.62499999999986, + "gamma_eff": 0.992988606485539, + "gap_pooled": 5.533291816711426, + "win_pooled": 0.4918212890625, + "gap_pooled_crosstask": 1.2059924602508545, + "win_pooled_crosstask": 0.4788818359375, + "state_auc": 0.6955710735894732, + "gap_0-50": 52.95362854003906, + "win_0-50": 0.563819095477387, + "gap_50-100": 10.891581535339355, + "win_50-100": 0.5226615236258437, + "gap_100-200": -3.717881202697754, + "win_100-200": 0.4675324675324675, + "gap_200+": -2.6963698863983154, + "win_200+": 0.4785954785954786 + }, + { + "beta": 0.99, + "depth": 1, + "eff_frames": 99.99999999999991, + "gamma_eff": 0.99, + "gap_pooled": 5.030198574066162, + "win_pooled": 0.4903564453125, + "gap_pooled_crosstask": 4.482872009277344, + "win_pooled_crosstask": 0.473388671875, + "state_auc": 0.6890126312717897, + "gap_0-50": 43.38360595703125, + "win_0-50": 0.5869346733668341, + "gap_50-100": -0.8099265098571777, + "win_50-100": 0.5197685631629702, + "gap_100-200": -0.7152834534645081, + "win_100-200": 0.476023976023976, + "gap_200+": 0.07517894357442856, + "win_200+": 0.4668109668109668 + }, + { + "beta": 0.99, + "depth": 2, + "eff_frames": 190.0900900900899, + "gamma_eff": 0.994739336492891, + "gap_pooled": 3.990938425064087, + "win_pooled": 0.48388671875, + "gap_pooled_crosstask": 2.947385787963867, + "win_pooled_crosstask": 0.4820556640625, + "state_auc": 0.6884089513406015, + "gap_0-50": 41.63627243041992, + "win_0-50": 0.5738693467336683, + "gap_50-100": 4.091736793518066, + "win_50-100": 0.5380906460945034, + "gap_100-200": -2.1627180576324463, + "win_100-200": 0.45704295704295705, + "gap_200+": -2.0797717571258545, + "win_200+": 0.46176046176046176 + }, + { + "beta": 0.99, + "depth": 3, + "eff_frames": 271.2523334144953, + "gamma_eff": 0.9963133957691271, + "gap_pooled": 3.611988067626953, + "win_pooled": 0.494140625, + "gap_pooled_crosstask": 2.0005316734313965, + "win_pooled_crosstask": 0.4805908203125, + "state_auc": 0.6812484177231277, + "gap_0-50": 42.16130447387695, + "win_0-50": 0.6040201005025125, + "gap_50-100": 7.271562099456787, + "win_50-100": 0.5207328833172613, + "gap_100-200": -4.476435661315918, + "win_100-200": 0.47352647352647353, + "gap_200+": -2.63104248046875, + "win_200+": 0.47113997113997114 + }, + { + "beta": 0.995, + "depth": 1, + "eff_frames": 199.99999999999983, + "gamma_eff": 0.995, + "gap_pooled": 6.226694583892822, + "win_pooled": 0.4937744140625, + "gap_pooled_crosstask": 5.46646785736084, + "win_pooled_crosstask": 0.4813232421875, + "state_auc": 0.6890978454599711, + "gap_0-50": 53.39063262939453, + "win_0-50": 0.6060301507537689, + "gap_50-100": -0.2218518704175949, + "win_50-100": 0.5188042430086789, + "gap_100-200": -0.9892496466636658, + "win_100-200": 0.47802197802197804, + "gap_200+": 0.023074371740221977, + "win_200+": 0.46825396825396826 + }, + { + "beta": 0.995, + "depth": 2, + "eff_frames": 360.1601601601599, + "gamma_eff": 0.9972234574763758, + "gap_pooled": 5.552397727966309, + "win_pooled": 0.4931640625, + "gap_pooled_crosstask": 3.7978029251098633, + "win_pooled_crosstask": 0.4825439453125, + "state_auc": 0.6908156643631088, + "gap_0-50": 52.535335540771484, + "win_0-50": 0.5829145728643216, + "gap_50-100": 6.096987724304199, + "win_50-100": 0.5274831243972999, + "gap_100-200": -3.048335075378418, + "win_100-200": 0.4695304695304695, + "gap_200+": -1.685240626335144, + "win_200+": 0.4745069745069745 + }, + { + "beta": 0.995, + "depth": 3, + "eff_frames": 488.41654467280046, + "gamma_eff": 0.9979525673097951, + "gap_pooled": 4.832504749298096, + "win_pooled": 0.4888916015625, + "gap_pooled_crosstask": 2.0376412868499756, + "win_pooled_crosstask": 0.48095703125, + "state_auc": 0.687118537828745, + "gap_0-50": 52.42646026611328, + "win_0-50": 0.5718592964824121, + "gap_50-100": 8.476884841918945, + "win_50-100": 0.532304725168756, + "gap_100-200": -4.376927852630615, + "win_100-200": 0.45054945054945056, + "gap_200+": -3.031353235244751, + "win_200+": 0.4766714766714767 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/results/sweep_base.json b/frozen/rsm_libero_freeze_20261002/results/sweep_base.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaa528bb0af6955eb2e55075299d45a94d6e59f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/results/sweep_base.json @@ -0,0 +1,230 @@ +[ + { + "beta": 0.96, + "depth": 1, + "eff_frames": 24.99999999999998, + "gamma_eff": 0.96, + "gap_pooled": 2.919712543487549, + "win_pooled": 0.5205078125, + "gap_pooled_crosstask": 2.7210028171539307, + "win_pooled_crosstask": 0.494140625, + "state_auc": 0.6619578043619792, + "gap_0-50": 27.9962100982666, + "win_0-50": 0.6398467432950191, + "gap_50-100": -0.9122968912124634, + "win_50-100": 0.5127118644067796, + "gap_100-200": -2.5012218952178955, + "win_100-200": 0.5102040816326531, + "gap_200+": 0.10693741589784622, + "win_200+": 0.49764373232799247 + }, + { + "beta": 0.96, + "depth": 2, + "eff_frames": 48.74999999999993, + "gamma_eff": 0.9794871794871794, + "gap_pooled": 2.280273914337158, + "win_pooled": 0.5009765625, + "gap_pooled_crosstask": 1.7893123626708984, + "win_pooled_crosstask": 0.5146484375, + "state_auc": 0.6495737711588542, + "gap_0-50": 20.17959976196289, + "win_0-50": 0.6015325670498084, + "gap_50-100": -0.04096969589591026, + "win_50-100": 0.5084745762711864, + "gap_100-200": -1.4540495872497559, + "win_100-200": 0.5040816326530613, + "gap_200+": 0.11807619035243988, + "win_200+": 0.473138548539114 + }, + { + "beta": 0.96, + "depth": 3, + "eff_frames": 71.31249999999993, + "gamma_eff": 0.985977212971078, + "gap_pooled": 3.340029716491699, + "win_pooled": 0.49658203125, + "gap_pooled_crosstask": 2.551269292831421, + "win_pooled_crosstask": 0.50439453125, + "state_auc": 0.6516652425130208, + "gap_0-50": 29.56572914123535, + "win_0-50": 0.578544061302682, + "gap_50-100": -1.016560673713684, + "win_50-100": 0.4449152542372881, + "gap_100-200": -1.5416101217269897, + "win_100-200": 0.47346938775510206, + "gap_200+": 0.11217954009771347, + "win_200+": 0.49858623939679547 + }, + { + "beta": 0.98, + "depth": 1, + "eff_frames": 49.99999999999996, + "gamma_eff": 0.98, + "gap_pooled": 4.422482490539551, + "win_pooled": 0.490234375, + "gap_pooled_crosstask": 3.0656747817993164, + "win_pooled_crosstask": 0.47021484375, + "state_auc": 0.6657206217447916, + "gap_0-50": 36.3089599609375, + "win_0-50": 0.6053639846743295, + "gap_50-100": -2.8381195068359375, + "win_50-100": 0.5211864406779662, + "gap_100-200": -1.0212669372558594, + "win_100-200": 0.45918367346938777, + "gap_200+": 0.7076546549797058, + "win_200+": 0.46936852026390197 + }, + { + "beta": 0.98, + "depth": 2, + "eff_frames": 97.49999999999986, + "gamma_eff": 0.9897435897435898, + "gap_pooled": 3.420022964477539, + "win_pooled": 0.5068359375, + "gap_pooled_crosstask": 3.1979477405548096, + "win_pooled_crosstask": 0.4892578125, + "state_auc": 0.6654937744140625, + "gap_0-50": 31.808181762695312, + "win_0-50": 0.6130268199233716, + "gap_50-100": 0.33880019187927246, + "win_50-100": 0.5338983050847458, + "gap_100-200": -2.4181067943573, + "win_100-200": 0.47551020408163264, + "gap_200+": -0.18172825872898102, + "win_200+": 0.4891611687087653 + }, + { + "beta": 0.98, + "depth": 3, + "eff_frames": 142.62499999999986, + "gamma_eff": 0.992988606485539, + "gap_pooled": 3.5487027168273926, + "win_pooled": 0.50390625, + "gap_pooled_crosstask": 2.7771530151367188, + "win_pooled_crosstask": 0.50341796875, + "state_auc": 0.6565541585286458, + "gap_0-50": 27.154804229736328, + "win_0-50": 0.5977011494252874, + "gap_50-100": 1.9898091554641724, + "win_50-100": 0.4830508474576271, + "gap_100-200": -1.0167019367218018, + "win_100-200": 0.49795918367346936, + "gap_200+": 0.19691623747348785, + "win_200+": 0.4882186616399623 + }, + { + "beta": 0.99, + "depth": 1, + "eff_frames": 99.99999999999991, + "gamma_eff": 0.99, + "gap_pooled": 4.452927589416504, + "win_pooled": 0.51025390625, + "gap_pooled_crosstask": 2.8550586700439453, + "win_pooled_crosstask": 0.4912109375, + "state_auc": 0.6666798909505208, + "gap_0-50": 33.996402740478516, + "win_0-50": 0.6398467432950191, + "gap_50-100": 1.073217749595642, + "win_50-100": 0.5296610169491526, + "gap_100-200": -1.5662366151809692, + "win_100-200": 0.47959183673469385, + "gap_200+": 0.7169742584228516, + "win_200+": 0.4882186616399623 + }, + { + "beta": 0.99, + "depth": 2, + "eff_frames": 190.0900900900899, + "gamma_eff": 0.994739336492891, + "gap_pooled": 3.6026997566223145, + "win_pooled": 0.5185546875, + "gap_pooled_crosstask": 1.7554620504379272, + "win_pooled_crosstask": 0.48193359375, + "state_auc": 0.6637013753255209, + "gap_0-50": 26.31501579284668, + "win_0-50": 0.5977011494252874, + "gap_50-100": 2.8295605182647705, + "win_50-100": 0.5466101694915254, + "gap_100-200": -1.1450427770614624, + "win_100-200": 0.5020408163265306, + "gap_200+": 0.380211740732193, + "win_200+": 0.5004712535344015 + }, + { + "beta": 0.99, + "depth": 3, + "eff_frames": 271.2523334144953, + "gamma_eff": 0.9963133957691271, + "gap_pooled": 3.078533411026001, + "win_pooled": 0.50537109375, + "gap_pooled_crosstask": 1.4733316898345947, + "win_pooled_crosstask": 0.49853515625, + "state_auc": 0.6554555257161458, + "gap_0-50": 27.982181549072266, + "win_0-50": 0.5593869731800766, + "gap_50-100": 2.456202268600464, + "win_50-100": 0.5127118644067796, + "gap_100-200": -1.2090694904327393, + "win_100-200": 0.45918367346938777, + "gap_200+": -0.9290597438812256, + "win_200+": 0.5117813383600377 + }, + { + "beta": 0.995, + "depth": 1, + "eff_frames": 199.99999999999983, + "gamma_eff": 0.995, + "gap_pooled": 4.393555641174316, + "win_pooled": 0.49853515625, + "gap_pooled_crosstask": 3.221923828125, + "win_pooled_crosstask": 0.486328125, + "state_auc": 0.6645701090494792, + "gap_0-50": 39.18448257446289, + "win_0-50": 0.6283524904214559, + "gap_50-100": -1.7130212783813477, + "win_50-100": 0.5127118644067796, + "gap_100-200": -1.7897416353225708, + "win_100-200": 0.45918367346938777, + "gap_200+": 0.049102868884801865, + "win_200+": 0.4816211121583412 + }, + { + "beta": 0.995, + "depth": 2, + "eff_frames": 360.1601601601599, + "gamma_eff": 0.9972234574763758, + "gap_pooled": 5.160642147064209, + "win_pooled": 0.4912109375, + "gap_pooled_crosstask": 3.7217297554016113, + "win_pooled_crosstask": 0.4873046875, + "state_auc": 0.6655629475911459, + "gap_0-50": 39.35454559326172, + "win_0-50": 0.6168582375478927, + "gap_50-100": 2.9915273189544678, + "win_50-100": 0.4872881355932203, + "gap_100-200": -0.6084309220314026, + "win_100-200": 0.4775510204081633, + "gap_200+": -0.10406177490949631, + "win_200+": 0.46748350612629597 + }, + { + "beta": 0.995, + "depth": 3, + "eff_frames": 488.41654467280046, + "gamma_eff": 0.9979525673097951, + "gap_pooled": 4.199846267700195, + "win_pooled": 0.515625, + "gap_pooled_crosstask": 2.3940823078155518, + "win_pooled_crosstask": 0.486328125, + "state_auc": 0.6591898600260416, + "gap_0-50": 37.53031539916992, + "win_0-50": 0.6206896551724138, + "gap_50-100": 4.017754077911377, + "win_50-100": 0.559322033898305, + "gap_100-200": -4.878033638000488, + "win_100-200": 0.47959183673469385, + "gap_200+": 0.23366372287273407, + "win_200+": 0.49670122525918947 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_freeze_20261002/reward_diag.py b/frozen/rsm_libero_freeze_20261002/reward_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..d6783a88e07eeb815acc9cb124bf3ffc4588d40f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/reward_diag.py @@ -0,0 +1,56 @@ +"""How good is the RSM reward head, really? Held-out (val-split) frames, per task, plus the +two failure modes that matter for ranking: (a) goal-mismatch (right state, wrong task id), +(b) imagined endpoints (flow samples) vs. the true future subgoal fraction. +usage: reward_diag.py --cache C --critic ckpt [--subgoal-dir D] [--mask M]""" +import argparse, os, sys, numpy as np, torch +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from data import LiberoRSMData +from is_ope import load_critic +from train_rsm import sample_future, auc + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) +ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="") +ap.add_argument("--n", type=int, default=20000); ap.add_argument("--beta", type=float, default=0.98) +a = ap.parse_args() +dev = "cuda" if torch.cuda.is_available() else "cpu" +d = LiberoRSMData(a.cache, chunk=10, seed=0, in_ram=False, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, + success_mask=a.mask, norm_pool="demos") +enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d) +lat = enc # load_critic already wraps the encoder with the proprio append (same as the evaluator) +rng = np.random.default_rng(0) +with torch.no_grad(): + fb = d.sample_frames(a.n, rng, "val", dev) + x, tk, r = fb["x"], fb["task"], fb["r"].float() + z = lat(x); rh = torch.sigmoid(rew(z, tk)) + e = (rh - r); print(f"VAL frames n={a.n}: MSE={float(e.pow(2).mean()):.4f} (const-null MSE={float((r-r.mean()).pow(2).mean()):.4f}) " + f"Pearson={float(np.corrcoef(rh.cpu(), r.cpu())[0,1]):.3f} mean r={float(r.mean()):.3f} mean r_hat={float(rh.mean()):.3f}") + print(f" AUC(all subgoals satisfied, r==1): {auc(rh.cpu().numpy(), (r.cpu().numpy()>=0.999).astype(float)):.3f} " + f"AUC(any progress, r>0): {auc(rh.cpu().numpy(), (r.cpu().numpy()>0.001).astype(float)):.3f}") + # calibration by true fraction + for lo, hi in ((0, 0.001), (0.001, 0.4), (0.4, 0.7), (0.7, 0.999), (0.999, 1.01)): + m = (r >= lo) & (r < hi) + if m.any(): print(f" true r in [{lo:.2f},{hi:.2f}): n={int(m.sum()):6d} mean r_hat={float(rh[m].mean()):.3f} std={float(rh[m].std()):.3f}") + # per task + for t in range(d.n_task): + m = tk == t + if m.sum() > 50: + print(f" task {t}: n={int(m.sum()):5d} Pearson={float(np.corrcoef(rh[m].cpu(), r[m].cpu())[0,1]):.3f} MSE={float(e[m].pow(2).mean()):.4f} mean r={float(r[m].mean()):.3f}") + # (a) goal mismatch: same latent, wrong task id + tk2 = (tk + torch.randint(1, d.n_task, tk.shape, device=dev)) % d.n_task + rh2 = torch.sigmoid(rew(z, tk2)) + print(f"GOAL-MISMATCH (wrong task id): mean r_hat={float(rh2.mean()):.3f} vs correct-task {float(rh.mean()):.3f}; " + f"fraction where wrong-task r_hat > correct-task r_hat: {float((rh2 > rh).float().mean()):.3f}") + # (b) imagined endpoints: flow sample at beta vs true future subgoal fraction + vb = d.sample(min(a.n, 8192), rng, a.beta, a.beta, "val", dev) + zc = lat(vb["x_now"]); zf_true = lat(vb["x_fut"]) + zf_imag = sample_future(flow, zc, vb["a_now"], vb["task"], vb["beta"], rms, 8, n=1) + r_true_fut = torch.sigmoid(rew(zf_true, vb["task"])) + r_imag = torch.sigmoid(rew(zf_imag, vb["task"])) + print(f"IMAGINED ENDPOINTS (beta={a.beta}): r_hat(true future latent) mean={float(r_true_fut.mean()):.3f}, r_hat(flow sample) mean={float(r_imag.mean()):.3f}, " + f"Pearson(imagined, true-future r_hat)={float(np.corrcoef(r_imag.cpu(), r_true_fut.cpu())[0,1]):.3f}, " + f"Pearson(imagined, TRUE future subgoal fraction)={float(np.corrcoef(r_imag.cpu(), vb['r_fut'].float().cpu())[0,1]) if 'r_fut' in vb else float('nan'):.3f}") + # (c) random latents: gaussian noise in latent space -> base-rate drift? + zr = torch.randn_like(z) * z.std(0, keepdim=True) + z.mean(0, keepdim=True) + print(f"RANDOM LATENTS (matched moments): mean r_hat={float(torch.sigmoid(rew(zr, tk)).mean()):.3f}") +print("[diag] DONE") diff --git a/frozen/rsm_libero_freeze_20261002/rsm_main.py b/frozen/rsm_libero_freeze_20261002/rsm_main.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4a18bd041b51cf2b7467d577da05157cb535f4 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/rsm_main.py @@ -0,0 +1,325 @@ +"""origin/main's MIMICGEN RSM port, applied to the LIBERO-10 latent corpus. + +SCOPE CORRECTION. This file ports mimicgen_rsm/rsm_mimicgen/rsm.py, which is +ONE variant on main and not the main RSM recipe. The headline recipe in +ogbench_unified_rsm IS action-conditioned: its flow trains on (s, a, g) -> +s_{t+K} pairs and hop 1 uses the queried action. Only the mimicgen port drops +that, stating "NOT goal-conditioned ... d_beta(s'|s), reward(s), qf(s,a)". +Both are worth running here; do not read this file as "what main does". + +Our own recipe differs from main's in four ways that matter, and this file adopts +all four. See notes/rsm_formula_comparison.pdf for the derivation side. + +1. REWARD IS AN ARRIVAL DETECTOR, NOT AN OUTCOME PREDICTOR. + main: a classifier with a CALIBRATED threshold, hard-thresholded to + r_hat(s) = 1[logit > thr] - 1 in {0, -1}; the threshold is fit on held-out + episodes because "the classifier's scores are well ordered but not centred on + 0". ours (until now): r = 1 on EVERY frame of a successful episode, i.e. + P(this episode succeeds | s). Measured consequence of ours: a directly + supervised Q(z,a) beats a state-only V(z) by AUC 0.9550 vs 0.9539, delta + +0.0012 -- the action adds nothing, because whether an episode succeeds is a + property of the state, not of the next 10 frames. + +2. THE OCCUPANCY IS STATE-ONLY in THIS port: d_beta(s'|s). The ogbench recipe + conditions on the action instead; that variant is the action-conditioned + critic this lane already has. + +3. THE ACTION ENTERS BY SUPERVISED REGRESSION, NOT BY CONDITIONING A GENERATIVE + MODEL ON A COUNTERFACTUAL. main distils a student + qf(s,a) <- r + gamma * (1-done) * V(s'), s' the REAL logged next state, + with V from the frozen occupancy and, in their words, "no TD bootstrap off + qf". Ours conditioned the flow on a candidate action, which is unsupervised in + the action direction; probe_crn measured the result to have the right + magnitude and an arbitrary sign. + +4. ARRIVAL ABSORBS AND STOPPING IS GEOMETRIC OVER MANY HOPS. + p_stop = beta(1-gamma)/(gamma(1-beta)); a rollout stops on the coin OR on + reaching the goal, over max_hops (expected ~11 at beta=0.9, gamma=0.99). Ours + read the reward once at a fixed depth of 2-3. The reduction is an optimistic + hop-weighted expectile, not a plain mean. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from data import LiberoRSMData +from model import Encoder, RewardHead, OccFlow, mlp, ema_update +from train_rsm import auc + + +# --------------------------------------------------------------------------- # +def p_stop_of(beta: float, gamma: float) -> float: + """main's geometric stopping probability. beta <= gamma is required.""" + assert beta <= gamma, f"need beta <= gamma, got {beta} > {gamma}" + return beta * (1.0 - gamma) / (gamma * (1.0 - beta)) if beta < gamma else 1.0 + + +def hop_weighted_value(r, absorb_hop, tau, rho, gamma, gain=1.0): + """main's speed-weighted upper expectile over per-rollout returns in {0,-1}.""" + A = 1.0 / (2.0 * (1.0 - tau)) + is_goal = r == 0.0 + w = torch.where(is_goal, + 1.0 + (A - 1.0) * gain * rho ** (absorb_hop.clamp_min(1) - 1).float(), + torch.ones_like(r)) + return ((w * r).sum(1) / w.sum(1).clamp_min(1e-12)) / (1.0 - gamma) + + +def value_from_at_goal_prob(q, tau, gamma): + if tau == 0.5: + m = q - 1.0 + else: + num = (1.0 - tau) * (1.0 - q) + den = tau * q + (1.0 - tau) * (1.0 - q) + m = -num / den.clamp_min(1e-12) + return m / (1.0 - gamma) + + +class MainRSM(torch.nn.Module): + """State-only occupancy + thresholded arrival reward + geometric-stop value.""" + + def __init__(self, d_lat, n_task, width=1024, depth=4): + super().__init__() + # d_act=1 with a zero action: the occupancy is state-only by construction, + # while reusing the same FiLM/Fourier successor the rest of the lane uses. + self.flow = OccFlow(d_lat, 1, n_task, width=width, depth=depth) + self.rew = RewardHead(d_lat, n_task) + self.register_buffer("rms", torch.ones(d_lat)) + self.threshold = 0.0 + + def flow_v(self, z, task, beta, x_k, k): + a0 = torch.zeros(z.shape[0], 1, device=z.device) + return self.flow(z, a0, task, beta, x_k, k) + + @torch.no_grad() + def hop(self, z, task, beta, steps=8): + x = torch.randn_like(z) + for s in range(steps): + k = torch.full((z.shape[0],), 1.0 - s / steps, device=z.device) + x = x + self.flow_v(z, task, beta, x, k) / steps + return z + x * self.rms + + @torch.no_grad() + def r_hat(self, z, task): + """Hard arrival reward in {0, -1} at the CALIBRATED threshold.""" + return (self.rew(z, task) > self.threshold).float() - 1.0 + + @torch.no_grad() + def estimate_value(self, z, task, *, beta, gamma, n_samples=16, max_hops=20, + tau=0.5, rho=0.9, gain=1.0, mode="hop", flow_steps=8): + B = z.shape[0] + p_stop = p_stop_of(beta, gamma) + s = z.repeat_interleave(n_samples, 0) + tk = task.repeat_interleave(n_samples, 0) + bq = torch.full((s.shape[0],), beta, device=z.device) + M = s.shape[0] + active = torch.ones(M, dtype=torch.bool, device=z.device) + stopped = s.clone() + absorb = torch.zeros(M, dtype=torch.long, device=z.device) + for h in range(1, max_hops + 1): + s_next = self.hop(s, tk, bq, steps=flow_steps) + s = torch.where(active.unsqueeze(-1), s_next, s) + at_goal = self.r_hat(s, tk) == 0.0 + coin = torch.rand(M, device=z.device) < p_stop + just = active & (coin | at_goal) + absorb = torch.where(just & at_goal, torch.full_like(absorb, h), absorb) + stopped = torch.where(just.unsqueeze(-1), s, stopped) + active = active & ~just + if not active.any(): + break + stopped = torch.where(active.unsqueeze(-1), s, stopped) + r = self.r_hat(stopped, tk).reshape(B, n_samples) + ah = absorb.reshape(B, n_samples) + if mode == "hop": + return hop_weighted_value(r, ah, tau, rho, gamma, gain) + q = (r == 0.0).float().mean(1) + return value_from_at_goal_prob(q, tau, gamma) + + +class QStudent(torch.nn.Module): + def __init__(self, d_lat, d_act, n_task, d_task=64, width=1024, depth=3): + super().__init__() + self.task = torch.nn.Embedding(n_task, d_task) + self.net = mlp([d_lat + d_act + d_task] + [width] * depth + [1], norm=True) + + def forward(self, z, a, task): + return self.net(torch.cat([z, a, self.task(task)], -1)).squeeze(-1) + + +def calibrate_threshold(model, d, enc, dev, rng, n=8192): + """Fit the cutoff on HELD-OUT frames, as main does. + + Chosen to match the positive base rate rather than at logit 0: main's note is + that the scores are well ordered but not centred, and estimate_value + thresholds hard, so an uncentred cutoff silently changes the arrival rate. + """ + P, Y = [], [] + with torch.no_grad(): + for _ in range(max(1, n // 2048)): + b = d.sample_frames(2048, rng, "val", dev) + z = enc(b["x"]) + P.append(model.rew(z, b["task"]).cpu().numpy()) + Y.append(b["r"].cpu().numpy()) + P = np.concatenate(P); Y = np.concatenate(Y) + pos = float(Y.mean()) + thr = float(np.quantile(P, 1.0 - pos)) if 0 < pos < 1 else 0.0 + a = auc(P, Y) + at_rate = float((P > thr).mean()) + return thr, a, pos, at_rate + + +# --------------------------------------------------------------------------- # +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--d-z", type=int, default=256) + ap.add_argument("--enc-width", type=int, default=1024) + ap.add_argument("--flow-width", type=int, default=1024) + ap.add_argument("--flow-depth", type=int, default=4) + ap.add_argument("--beta", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--k-success", type=int, default=10, + help="frames at the END of a successful episode counted as " + "AT GOAL. This is main's arrival convention; the dense " + "whole-episode label is an outcome predictor and was " + "measured to carry no action information.") + ap.add_argument("--n-value-samples", type=int, default=16) + ap.add_argument("--max-hops", type=int, default=20) + ap.add_argument("--value-expectile", type=float, default=0.7) + ap.add_argument("--expectile-mode", default="hop", choices=["hop", "reward"]) + ap.add_argument("--hop-rho", type=float, default=0.9) + ap.add_argument("--occ-steps", type=int, default=20000) + ap.add_argument("--qf-steps", type=int, default=40000) + ap.add_argument("--distill-states", type=int, default=153600, + help="transitions in the distillation buffer; V is " + "computed once per transition, not per batch") + ap.add_argument("--batch", type=int, default=512) + ap.add_argument("--qf-batch", type=int, default=256) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--ema", type=float, default=0.005) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + 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" + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + # ARRIVAL labels, not outcome labels + d = LiberoRSMData(args.cache, chunk=args.chunk, k_success=args.k_success, + seed=args.seed, in_ram=bool(args.in_ram), + reward_mode="terminal", norm_pool=args.norm_pool) + print(f"[main-rsm] {d.n_ep} eps, at-goal frames {float(d.r.mean()):.4f} " + f"(main's arrival convention), p_stop " + f"{p_stop_of(args.beta, args.gamma):.4f}, E[hops] " + f"{1.0 / max(p_stop_of(args.beta, args.gamma), 1e-9):.1f}", flush=True) + + enc = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) + enc_t = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) + enc_t.load_state_dict(enc.state_dict()) + for p in enc_t.parameters(): + p.requires_grad_(False) + m = MainRSM(args.d_z, d.n_task, args.flow_width, args.flow_depth).to(dev) + opt = torch.optim.AdamW(list(enc.parameters()) + list(m.flow.parameters()) + + list(m.rew.parameters()), lr=args.lr, weight_decay=0.01) + rng = np.random.default_rng(args.seed) + pos_w = torch.tensor(max((1 - d.r.mean()) / max(d.r.mean(), 1e-6), 1.0), device=dev) + + # ---- stage 1: state-only occupancy + arrival classifier ---- + for step in range(1, args.occ_steps + 1): + b = d.sample(args.batch, rng, args.beta, args.beta, "train", dev) + z = enc(b["x_now"]) + with torch.no_grad(): + z_fut = enc_t(b["x_fut"]) + l_rew = F.binary_cross_entropy_with_logits( + m.rew(z, b["task"]), b["r_now"], pos_weight=pos_w) + delta = z_fut - (z.detach() if step <= 2000 else z) + with torch.no_grad(): + m.rms.mul_(0.99).add_(delta.pow(2).mean(0).sqrt().clamp_min(1e-3), alpha=0.01) + y = delta / m.rms + k = torch.rand(args.batch, device=dev) + noise = torch.randn_like(y) + x_k = (1 - k)[:, None] * y + k[:, None] * noise + v = m.flow_v(z if step > 2000 else z.detach(), b["task"], b["beta"], x_k, k) + l_cfm = (v - (y - noise)).pow(2).mean() + std = z.std(0) + loss = l_rew + l_cfm + 10.0 * F.relu(0.1 - std).mean() + opt.zero_grad(); loss.backward() + torch.nn.utils.clip_grad_norm_( + list(enc.parameters()) + list(m.flow.parameters()) + + list(m.rew.parameters()), 1.0) + opt.step(); ema_update(enc_t, enc, args.ema) + if step % 2000 == 0: + print(f"[occ] {step} rew={float(l_rew):.4f} cfm={float(l_cfm):.4f}", + flush=True) + + enc.eval(); m.eval() + torch.save({"enc": enc.state_dict(), "flow": m.flow.state_dict(), + "rew": m.rew.state_dict(), "rms": m.rms.cpu(), + "config": vars(args)}, out / "stage1.pt") + thr, a_r, pos, at_rate = calibrate_threshold(m, d, enc, dev, + np.random.default_rng(args.seed + 5)) + m.threshold = thr + print(f"[main-rsm] arrival classifier AUC {a_r:.4f}; threshold {thr:+.3f} " + f"calibrated to base rate {pos:.4f} (at-goal rate {at_rate:.4f})", + flush=True) + + # ---- stage 2: distil qf(z,a) <- r + gamma (1-done) V(z'), REAL z' ---- + # Build the distillation BUFFER once. Recomputing V per batch means a fresh + # 16-rollout, 20-hop expansion every step (<1.7 steps/s measured); the target + # does not change during stage 2, so it is computed once and regressed on. + rq = np.random.default_rng(args.seed + 11) + Z, ZA, TK, TG = [], [], [], [] + got, bs = 0, 512 + while got < args.distill_states: + b = d.sample_frames(bs, rq, "train", dev) + t_next = np.minimum(b["t_idx"] + d.chunk, d.ep_to[b["ep"]] - 1) + done = torch.from_numpy( + (t_next >= d.ep_to[b["ep"]] - 1).astype(np.float32)).to(dev) + with torch.no_grad(): + z = enc(b["x"]) + zn = enc(torch.from_numpy(d._feat(t_next)).to(dev)) + r_now = m.r_hat(z, b["task"]) + v_next = m.estimate_value( + zn, b["task"], beta=args.beta, gamma=args.gamma, + n_samples=args.n_value_samples, max_hops=args.max_hops, + tau=args.value_expectile, rho=args.hop_rho, + mode=args.expectile_mode) + target = r_now + args.gamma * (1 - done) * v_next + Z.append(z.cpu()); ZA.append(b["a"].cpu()) + TK.append(b["task"].cpu()); TG.append(target.cpu()) + got += bs + if got % 25600 == 0: + print(f"[buf] {got}/{args.distill_states} " + f"target_mean={float(target.mean()):.3f}", flush=True) + Z = torch.cat(Z); ZA = torch.cat(ZA); TK = torch.cat(TK); TG = torch.cat(TG) + print(f"[buf] done {tuple(Z.shape)} target mean {float(TG.mean()):.3f} " + f"sd {float(TG.std()):.3f}", flush=True) + + qf = QStudent(args.d_z, d.chunk * d.adim, d.n_task).to(dev) + qopt = torch.optim.Adam(qf.parameters(), lr=args.lr) + for step in range(1, args.qf_steps + 1): + idx = torch.randint(0, len(Z), (args.qf_batch,)) + loss = F.mse_loss(qf(Z[idx].to(dev), ZA[idx].to(dev), TK[idx].to(dev)), + TG[idx].to(dev)) + qopt.zero_grad(); loss.backward() + torch.nn.utils.clip_grad_norm_(qf.parameters(), 1.0); qopt.step() + if step % 4000 == 0: + print(f"[qf] {step} loss={float(loss):.4f}", flush=True) + + torch.save({"enc": enc.state_dict(), "flow": m.flow.state_dict(), + "rew": m.rew.state_dict(), "rms": m.rms.cpu(), + "threshold": thr, "qf": qf.state_dict(), + "config": vars(args), "d_act": d.chunk * d.adim, + "tasks": d.tasks, "arrival_auc": a_r}, out / "main_rsm.pt") + print("[main-rsm] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/run_cell.sh b/frozen/rsm_libero_freeze_20261002/run_cell.sh new file mode 100644 index 0000000000000000000000000000000000000000..f265e371adf207ae96d6f83c3d57599084bedf8d --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/run_cell.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# Self-resubmitting cell on IBM's preemptable queue (SIGINT on preemption; LSF -r does not +# requeue). Both train_rsm.py (--resume 1, ckpt.pt) and bc_arm.py (bc_resume.pt) continue +# from their last checkpoint, so a preempted cell picks up where it left off. +set -uo pipefail +B=/proj/dmfexp/zwhong/rsm_libero; PY=/proj/dmfexp/zwhong/venvs/lerobot_env/bin/python +cd $B/code; export PYTHONUNBUFFERED=1 +echo "[cell] $CELL start $(date -u +%T) on $(hostname)" +eval "$PY $CMD"; RC=$? +echo "[cell] $CELL rc=$RC $(date -u +%T)" +DONE=$(grep -qE "^\[(rsm|bc_arm|iql)\] DONE" $O/logs/$CELL.out 2>/dev/null && echo 1 || echo 0) +if [ "$RC" -ne 0 ] && [ "$DONE" = 0 ]; then + echo "[cell] $CELL incomplete -> resubmitting" + bsub -G grp_preemptable -q preemptable -r -gpu num=1 -n 8 -M 160G -R 'rusage[mem=160G]' -J $CELL \ + -o $O/logs/$CELL.out -e $O/logs/$CELL.err -env "all, CELL=$CELL, CMD=$CMD, O=$O" $B/run_cell.sh +fi +exit $RC diff --git a/frozen/rsm_libero_freeze_20261002/run_ope.py b/frozen/rsm_libero_freeze_20261002/run_ope.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d6a6167bd9d645022263ab0b9416d13a150d09 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/run_ope.py @@ -0,0 +1,171 @@ +"""Driver: pi_0 -> ratio -> endpoint weight -> IS-corrected Q, with the gate. + +Order of operations is deliberate. The IS machinery is validated BEFORE any +policy is trained on it, because a critic that is never checked is how the +smolvla line shipped an advantage of 0.019 and a null AWR result. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import (load_critic, train_bc, train_ratio, train_endpoint_ratio, + train_likelihood_ratio, + q_recursive, precompute_decision_logratio, chunk_logW_fast, + effective_horizon) +from train_rsm import auc + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--batch", type=int, default=512) + 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=16) + ap.add_argument("--bc-steps", type=int, default=8000) + ap.add_argument("--ratio-steps", type=int, default=6000) + ap.add_argument("--wend-steps", type=int, default=6000) + ap.add_argument("--pi-mode", default="succ", choices=["succ", "all"], + help="succ = BC on successful rollouts (a genuinely better " + "target policy); all = BC on everything, which approximates " + "the behaviour policy and is the NULL control: with pi ~= mu " + "the weights must be ~1 and IS must not move Q.") + 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-mode", default="classifier", + choices=["classifier", "likelihood"], + help="classifier = discriminative density ratio (SHOWN BROKEN: " + "an identity control puts two same-data policies at 0.945-" + "0.977 separability, so the logit reads network identity). " + "likelihood = genuine pi/mu_hat with tractable Gaussians.") + 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("--reward-mode", default="dense", choices=["dense","terminal"], + 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="flow", choices=["flow", "gauss"]) + 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() + + # 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) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + args.d_z = cfg["d_z"] + rng = np.random.default_rng(args.seed + 7) + report = {"config": vars(args)} + + only_succ = (args.pi_mode == "succ") + print(f"=== pi_0: behaviour cloning ({'successes only' if only_succ else 'ALL data (null control)'}) ===", + flush=True) + pol = train_bc(d, enc, args, dev, only_success=only_succ, steps=args.bc_steps) + + print("=== step 1: per-decision density ratio by classification ===", flush=True) + rc = args.ratio_chunk or d.chunk + if args.ratio_mode == "likelihood": + ratio, pol_dec = train_likelihood_ratio( + d, enc, args, dev, steps=args.ratio_steps, + only_success=only_succ, chunk_len=rc) + elif rc != d.chunk: + print(f"=== fitting a DECISION-level policy (chunk {rc}) for the ratio ===", + flush=True) + print(f"=== fitting a DECISION-level policy (chunk {rc}) for the ratio ===", + flush=True) + pol_dec = train_bc(d, enc, args, dev, only_success=only_succ, + steps=args.bc_steps, chunk_len=rc) + ratio = train_ratio(d, enc, pol_dec, args, dev, steps=args.ratio_steps) + else: + pol_dec = pol + ratio = train_ratio(d, enc, pol_dec, args, dev, steps=args.ratio_steps) + + print("=== step 2/3: endpoint weight (Rao-Blackwellized) ===", flush=True) + wend = train_endpoint_ratio(d, enc, ratio, args, dev, steps=args.wend_steps) + + # ---------------- calibration: E_mu[w] should be ~1 ---------------- + b = d.sample(4096, rng, args.beta_q, args.beta_q, "val", dev) + with torch.no_grad(): + z = enc(b["x_now"]); zf = enc(b["x_fut"]) + w = wend(z, b["a_now"], zf, b["task"]) * getattr(wend, "calib", 1.0) + pre = precompute_decision_logratio(d, enc, ratio, dev, rc=rc) + W = torch.from_numpy(chunk_logW_fast(pre, b["t_idx"], b["fut_idx"])).to(dev) + W = W.clamp(-4, 4).exp() + ess = float((w.sum() ** 2) / (w.pow(2).sum() * len(w))) + report["calibration"] = { + "calib_scale": float(getattr(wend, "calib", 1.0)), + "E_mu[W_chunk]": float(W.mean()), "E_mu[w_endpoint]": float(w.mean()), + "w_p05": float(w.quantile(0.05)), "w_p50": float(w.quantile(0.5)), + "w_p95": float(w.quantile(0.95)), "ess_frac": ess, + "corr_w_vs_W": float(np.corrcoef(w.cpu().numpy(), W.cpu().numpy())[0, 1]), + } + print(f"[gate] E_mu[w]={w.mean():.3f} (target 1.0) ESS={ess:.3f} " + f"corr(what,W)={report['calibration']['corr_w_vs_W']:.3f}", flush=True) + + # ---------------- the falsifiable gate ---------------- + # pi_synth := mu restricted to successful episodes. Its occupancy is directly + # estimable, so the IS-corrected value can be checked against a reference + # rather than merely asserted. + fb = d.sample_frames(2048, rng, "val", dev) + with torch.no_grad(): + zq = enc(fb["x"]) + q_is, ess_q = q_recursive(zq, fb["a"], fb["task"], rew=rew, flow=flow, rms=rms, + pol=pol, wend=wend, beta=args.beta_q, gamma=args.gamma, + depth=args.depth, n_particles=args.particles, + use_is=True) + q_no, _ = q_recursive(zq, fb["a"], fb["task"], rew=rew, flow=flow, rms=rms, + pol=pol, wend=wend, beta=args.beta_q, gamma=args.gamma, + depth=args.depth, n_particles=args.particles, + use_is=False) + succ = fb["succ"].cpu().numpy() + dq = float((q_is - q_no).abs().mean() / q_no.abs().mean().clamp_min(1e-6)) + report["horizon"] = effective_horizon(args.beta_q, args.gamma, args.depth) + print(f"[horizon] depth={args.depth} -> {report['horizon']['mean_hops']:.2f} hops, " + f"~{report['horizon']['effective_frames']:.0f} frames, " + f"gamma_eff={report['horizon']['gamma_effective']:.4f} " + f"(nominal {args.gamma}); truncated mass " + f"{report['horizon']['truncation_mass']:.3f}", flush=True) + report["value"] = { + "pi_mode": args.pi_mode, + "rel_shift_IS_vs_noIS": dq, + "gate_expectation": ("null: weights ~1 and rel_shift should be SMALL" + if args.pi_mode == "all" else + "signal: pi is better than mu, Q should move UP"), + "auc_success_IS": auc(q_is.cpu().numpy(), succ), + "auc_success_noIS": auc(q_no.cpu().numpy(), succ), + "q_mean_IS": float(q_is.mean()), "q_mean_noIS": float(q_no.mean()), + "ess_particles": float(ess_q.mean()), + "depth": args.depth, "beta": args.beta_q, "gamma": args.gamma, + } + print(f"[gate] pi_mode={args.pi_mode} success-AUC IS={report['value']['auc_success_IS']:.4f} " + f"noIS={report['value']['auc_success_noIS']:.4f} " + f"rel|dQ|={dq:.4f} particle ESS={float(ess_q.mean()):.3f}", flush=True) + + torch.save({"pol": pol.state_dict(), "ratio": ratio.state_dict(), + "wend": wend.state_dict(), "config": vars(args)}, out / "is_stack.pt") + (out / "report.json").write_text(json.dumps(report, indent=2)) + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/run_slurm.sh b/frozen/rsm_libero_freeze_20261002/run_slurm.sh new file mode 100644 index 0000000000000000000000000000000000000000..c88879dad292987e4d35040ea227def9abb64f2d --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/run_slurm.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# Launch an RSM/OPE arm on MIT slurm. +# ARM=critic bash rsm_libero/run_slurm.sh +# ARM=ope bash rsm_libero/run_slurm.sh +# ARM=awr bash rsm_libero/run_slurm.sh +# QoS note: vision-pulkitag-main is off limits per standing instruction; lab-free +# has no GPU cap and reaches csail-shared-h200 (24h wall clock max there). +set -euo pipefail +ROOT=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q +PY=$ROOT/.venv/bin/python +CACHE=${CACHE:-/data/pulkitag/users/rli14/rsm_libero_cache/full} +OUTROOT=${OUTROOT:-/data/pulkitag/users/rli14/rsm_libero_runs} +ARM=${ARM:-critic} +TAG=${TAG:-$(date +%m%d)_${ARM}} +QOS=${QOS:-lab-free} +PART=${PART:-csail-shared-h200} +TIME=${TIME:-23:00:00} +MEM=${MEM:-400G} +OUT=$OUTROOT/$TAG +mkdir -p "$OUT" "$OUT/slurm" + +case "$ARM" in + critic) CMD="$PY $ROOT/rsm_libero/train_rsm.py --cache $CACHE --out $OUT \ + --steps ${STEPS:-60000} --batch ${BATCH:-512} --beta-lo 0.90 --beta-hi 0.995 \ + --beta-q ${BETAQ:-0.98} --w-actcon ${ACTCON:-0} --seed ${SEED:-0}" ;; + ope) CMD="$PY $ROOT/rsm_libero/run_ope.py --cache $CACHE --critic ${CRITIC:?set CRITIC} \ + --out $OUT --beta-q ${BETAQ:-0.98} --gamma ${GAMMA:-0.99} \ + --depth ${DEPTH:-2} --seed ${SEED:-0}" ;; + awr) CMD="$PY $ROOT/rsm_libero/awr.py --cache $CACHE --critic ${CRITIC:?set CRITIC} \ + --out $OUT --rounds ${ROUNDS:-2} --depth ${DEPTH:-2} \ + --use-is ${USE_IS:-1} --seed ${SEED:-0}" ;; + *) echo "unknown ARM=$ARM" >&2; exit 2 ;; +esac + +sbatch --job-name="rsm_$TAG" --account=vision-pulkitag --qos="$QOS" \ + --partition="$PART" --gres=gpu:1 --cpus-per-task=8 --mem="$MEM" --time="$TIME" \ + --output="$OUT/slurm/%j.out" --error="$OUT/slurm/%j.err" \ + --wrap="cd $ROOT/rsm_libero && $CMD" +echo "submitted $ARM -> $OUT" diff --git a/frozen/rsm_libero_freeze_20261002/stats_full.sbatch b/frozen/rsm_libero_freeze_20261002/stats_full.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7ccb22f381770333bfc4422c2bfe069a2e698a98 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/stats_full.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=stats_full +#SBATCH --account=vision-pulkitag +#SBATCH --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.err +# Compute feat_stats{,_demos}.npz for the one-space cache ONCE, so the six trainers +# launched behind this (--dependency=afterok) read them instead of racing to write. +set -uo pipefail +cd /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python - <<'PY' +import sys; sys.path.insert(0,".") +from data import LiberoRSMData +for np_ in ("all","demos"): + d=LiberoRSMData("/data/pulkitag/users/rli14/rsm_libero_cache/full_r256",chunk=10,seed=0,in_ram=False,reward_mode="dense",norm_pool=np_) + print("[stats] ok", np_, d.feat_dim, flush=True) +PY +echo "[stats] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_freeze_20261002/stats_r256.sbatch b/frozen/rsm_libero_freeze_20261002/stats_r256.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..ca53d75dff772979ccd8ee154606ea82880c9dda --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/stats_r256.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=stats_r256 +#SBATCH --account=vision-pulkitag +#SBATCH --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.err +# Compute feat_stats{,_demos}.npz for the one-space cache ONCE, so the six trainers +# launched behind this (--dependency=afterok) read them instead of racing to write. +set -uo pipefail +cd /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python - <<'PY' +import sys; sys.path.insert(0,".") +from data import LiberoRSMData +for np_ in ("all","demos"): + d=LiberoRSMData("/data/pulkitag/users/rli14/rsm_libero_cache/full_demo_r256",chunk=10,seed=0,in_ram=False,reward_mode="dense",norm_pool=np_) + print("[stats] ok", np_, d.feat_dim, flush=True) +PY +echo "[stats] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_freeze_20261002/subgoals_from_npz.py b/frozen/rsm_libero_freeze_20261002/subgoals_from_npz.py new file mode 100644 index 0000000000000000000000000000000000000000..6259dfde2adb9be1c774aa4c1d98775c9c65a7e1 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/subgoals_from_npz.py @@ -0,0 +1,24 @@ +"""Subgoal labels for a pack whose per-episode npz already carry a per-frame `subgoals` +count (written by eval_closed_loop.py --collect from the live BDDL predicates). Emits the +/task{t}.npz (ep, vals, K) layout that data.py reward_mode=subgoal reads. + +usage: subgoals_from_npz.py --cache --out +""" +import argparse, numpy as np +from pathlib import Path +ap = argparse.ArgumentParser(); ap.add_argument("--cache", required=True); ap.add_argument("--out", required=True) +a = ap.parse_args() +m = np.load(f"{a.cache}/meta.npz", allow_pickle=True) +out = Path(a.out); out.mkdir(parents=True, exist_ok=True) +for t in range(len(m["tasks"])): + eps, vals, K = [], [], None + for e in np.where((m["ep_task"] == t) & ~m["ep_demo"].astype(bool))[0]: + z = np.load(str(m["ep_src"][e]), allow_pickle=True) + v = np.asarray(z["subgoals"], np.int8)[::int(m["stride"])] + n = int(m["ep_to"][e] - m["ep_from"][e]) + if len(v) < n: v = np.concatenate([v, np.full(n - len(v), v[-1] if len(v) else 0, np.int8)]) + eps.append(int(e)); vals.append(v[:n]); K = int(z["K"]) + if eps: + np.savez_compressed(out / f"task{t}.npz", ep=np.array(eps), vals=np.array(vals, dtype=object), K=K) + f = np.concatenate(vals); print(f"[sg] task {t}: {len(eps)} eps, K={K}, mean subgoal frac {f.mean()/K:.3f}", flush=True) +print("[sg] DONE") diff --git a/frozen/rsm_libero_freeze_20261002/sweep_horizon.py b/frozen/rsm_libero_freeze_20261002/sweep_horizon.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e46709ded09c6920c3f42519508c350c6ac774 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/sweep_horizon.py @@ -0,0 +1,140 @@ +"""Sweep query discount x recursion depth on a TRAINED critic. No retraining. + +The critic is fit on a beta BAND, so one checkpoint can be read at any query +beta. That makes the central tradeoff cheap to map: + + short hops -> the action still determines where you land, but the read is + myopic and never reaches the terminal reward + long hops -> the read reaches further, but the successor tends to ignore + the action chunk entirely + +Reports the action gap bucketed by time-to-episode-end, because a pooled number +averages the signal away: at beta=0.98 depth=1 the gap is +0.063 within 50 +frames of the end and ~0 beyond it, while the pooled value is +0.008. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, effective_horizon, train_bc +from model import BCHead +from train_rsm import auc + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--betas", default="0.96,0.98,0.99,0.995") + ap.add_argument("--depths", default="1,2,3") + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--n", type=int, default=2048) + 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("--reward-mode", default="dense", choices=["dense","terminal"], + 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="flow", choices=["flow", "gauss"]) + ap.add_argument("--bc-steps", type=int, default=3000) + ap.add_argument("--batch", type=int, default=512) + args = ap.parse_args() + + # 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" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode=args.reward_mode) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + rng = np.random.default_rng(args.seed + 5) + # Continuation policy for the recursion boundary. This MUST be on-support: an + # untrained head emits off-manifold action chunks at every hop, and the frozen + # reward decoder then scores the resulting latents arbitrarily -- the same + # support-exploitation artifact that turned the cross-task action gap + # negative. A quick behaviour clone keeps the boundary actions in + # distribution so the depth>1 numbers mean something. + args.d_z = cfg["d_z"] + args.seed = args.seed + pol = train_bc(d, enc, args, dev, only_success=False, steps=args.bc_steps) + + fb = d.sample_frames(args.n, rng, "val", dev) + with torch.no_grad(): + z = enc(fb["x"]) + te = fb["to_end"].cpu().numpy() + succ = fb["succ"].cpu().numpy() + # Two negatives, deliberately: + # within-task -- an on-support alternative; the fair action-ranking test + # cross-task -- the old batch-wide permutation, kept as a CONTROL. Once + # the flow is genuinely action-conditioned, an off-support + # action yields an off-manifold latent that the frozen + # reward decoder scores arbitrarily, so a "preference" for + # it measures support violation, not action quality. + tk_np_all = fb["task"].cpu().numpy() + perm_cross = torch.randperm(args.n, device=dev) + pw = np.arange(args.n) + for ti in np.unique(tk_np_all): + idx = np.nonzero(tk_np_all == ti)[0] + if len(idx) > 1: + pw[idx] = rng.permutation(idx) + perm_within = torch.from_numpy(pw).to(dev) + rows = [] + for beta in [float(b) for b in args.betas.split(",")]: + for depth in [int(x) for x in args.depths.split(",")]: + if beta >= args.gamma and depth > 1: + continue + with torch.no_grad(): + q_log, ess = q_recursive(z, fb["a"], fb["task"], rew=rew, flow=flow, + rms=rms, pol=pol, wend=None, beta=beta, + gamma=args.gamma, depth=depth, + n_particles=args.particles, use_is=False) + q_win, _ = q_recursive(z, fb["a"][perm_within], fb["task"], rew=rew, + flow=flow, rms=rms, pol=pol, wend=None, + beta=beta, gamma=args.gamma, depth=depth, + n_particles=args.particles, use_is=False) + q_crs, _ = q_recursive(z, fb["a"][perm_cross], fb["task"], rew=rew, + flow=flow, rms=rms, pol=pol, wend=None, + beta=beta, gamma=args.gamma, depth=depth, + n_particles=args.particles, use_is=False) + gl = (q_log - q_win).cpu().numpy() + gc = (q_log - q_crs).cpu().numpy() + ql = q_log.cpu().numpy() + h = effective_horizon(beta, args.gamma, depth) + row = {"beta": beta, "depth": depth, + "eff_frames": h["effective_frames"], + "gamma_eff": h["gamma_effective"], + "gap_pooled": float(gl.mean()), + "win_pooled": float((gl > 0).mean()), + "gap_pooled_crosstask": float(gc.mean()), + "win_pooled_crosstask": float((gc > 0).mean()), + "state_auc": auc(ql, succ)} + for name, lo_, hi_ in (("0-50", 0, 50), ("50-100", 50, 100), + ("100-200", 100, 200), ("200+", 200, 1e9)): + m = (te >= lo_) & (te < hi_) + if m.sum() >= 16: + row[f"gap_{name}"] = float(gl[m].mean()) + row[f"win_{name}"] = float((gl[m] > 0).mean()) + rows.append(row) + print(f"beta={beta:<6} depth={depth} eff={h['effective_frames']:5.0f}f " + f"pooled gap={row['gap_pooled']:+.5f} win={row['win_pooled']:.3f} " + f"auc={row['state_auc']:.3f} " + f"0-50 win={row.get('win_0-50', float('nan')):.2f} " + f"| xtask win={row['win_pooled_crosstask']:.3f}", flush=True) + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + (out / "horizon_sweep.json").write_text(json.dumps(rows, indent=2)) + print(f"\nwrote {out/'horizon_sweep.json'}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/sync_to_ibm.sh b/frozen/rsm_libero_freeze_20261002/sync_to_ibm.sh new file mode 100644 index 0000000000000000000000000000000000000000..0bec8e7cd62ab681c3aaeda00c5dac6af8ae351c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/sync_to_ibm.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# Push this lane's code (and the feature stats it depends on) to Blue Vela and +# print the launch lines. Idempotent: safe to re-run. +# +# ACCESS: bluevela is reached only through a reverse tunnel on katsudon:3104 that +# is itself an LSF job named `claude_tunnel`. When that job ends the whole route +# dies and NOTHING here can revive it, because relaunching the job requires a +# bluevela shell, which requires the tunnel. A human with a live bluevela session +# must resubmit it. This script checks first and says so rather than hanging. +set -euo pipefail # -e: a failed rsync must NOT print the success notes +SRC=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +DST=/proj/dmfexp/zwhong/rsm_libero +CACHE_STATS=/data/pulkitag/users/rli14/rsm_libero_cache/full_demo/feat_stats.npz +SSHQ=(-o BatchMode=yes + + -J katsudon.csail.mit.edu -p 3104) +HOST=zwhong@127.0.0.1 + +if ! ssh -o BatchMode=yes katsudon.csail.mit.edu \ + 'ss -ltn 2>/dev/null | grep -q ":3104 "'; then + echo "TUNNEL DOWN: no listener on katsudon:3104." + echo "The LSF job 'claude_tunnel' (queue normal, group grp_runtime) has ended." + echo "Someone with a live bluevela shell must resubmit it; then re-run this." + exit 3 +fi + +# The tunnel being up does not mean we can authenticate. The cert can be valid +# and ACCEPTED by the server while the private key stays passphrase-locked with +# nothing in the agent, in which case every rsync fails and, without -e, this +# script used to print its launch notes anyway and look like it had worked. +if ! ssh "${SSHQ[@]}" "$HOST" true 2>/dev/null; then + echo "TUNNEL UP BUT AUTH FAILS." + ssh-keygen -L -f "$HOME/.ssh/id_rsa_zwhong-cert.pub" 2>/dev/null \ + | grep -E "Valid|Principals" -A1 | head -4 + echo "If the cert is still in date, the private key is passphrase-locked and" + echo "the agent is empty. Load it once: ssh-add ~/.ssh/id_rsa_zwhong" + exit 4 +fi +echo "[sync] tunnel up and authenticated; pushing code" +rsync -az --delete -e "ssh ${SSHQ[*]}" \ + --include='*.py' --include='*.sh' --include='*.sbatch' --include='*.md' \ + --exclude='*' "$SRC/" "$HOST:$DST/code/" +# DO NOT push feature statistics. The IBM cache is a DIFFERENT pack (4500 eps / +# 1.82M frames / 51.1% success) from the MIT one (5000 / 1.93M / 54.5%), and both +# are 4104-d, so the evaluator's dimension guard cannot catch a mismatched file. +# Copying MIT stats over IBM's silently mis-centres every run there. Each cache +# fits its own on first use. +# +# Note the one case where a checkpoint DOES transfer safely: --norm-pool demos +# computes statistics over demonstration frames only, and both packs contain the +# same 500 demos, so demo-pool stats agree across them. +echo "[sync] NOT pushing feature stats: each cache must fit its own" + +cat <<'NOTE' + +[sync] done. On bluevela the arms launch as (adjust --cache to the IBM cache): + + PY=/bin/python + C=/proj/dmfexp/zwhong/rsm_libero/cache/full_demo + R=/proj/dmfexp/zwhong/rsm_libero/runs/mit_port + + $PY code/bc_arm.py --cache $C --out $R/A --pool demos --policy-features raw \ + --feat-scale center --chunk 10 --bc-steps 60000 --in-ram 1 --seed 0 + $PY code/bc_arm.py --cache $C --out $R/B --pool succ --policy-features raw \ + --feat-scale center --chunk 10 --bc-steps 60000 --in-ram 1 --seed 0 + $PY code/train_rsm.py --cache $C --out $R/critic10 --chunk 10 --d-z 256 \ + --enc-width 1024 --flow-width 1024 --flow-depth 4 --batch 512 --steps 20000 \ + --warmup-reward 2000 --beta-lo 0.85 --beta-hi 0.97 --beta-q 0.90 \ + --w-actcon 0.5 --append-proprio 1 --in-ram 1 --eval-every 1000 --seed 0 + $PY code/iql.py --cache $C --critic $R/critic10/ckpt_best.pt --out $R/C ... + $PY code/awr.py --cache $C --critic $R/critic10/ckpt_best.pt --out $R/D ... + +If the IBM cache lacks feat_stats.npz for its own dim, delete the copied file and +let LiberoRSMData refit it there -- stats must match the cache they index. +NOTE diff --git a/frozen/rsm_libero_freeze_20261002/test_dwm.py b/frozen/rsm_libero_freeze_20261002/test_dwm.py new file mode 100644 index 0000000000000000000000000000000000000000..0b0cd2105e0a9f8f68a306c47978e8a543c87e96 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/test_dwm.py @@ -0,0 +1,262 @@ +"""CPU unit tests for the DWM successor model (synthetic token cache, tiny ViT). + + cd rsm_libero && python3 -m pytest -x -q test_dwm.py +""" +from __future__ import annotations +import json, os, subprocess, sys +from pathlib import Path +import numpy as np +import pytest +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from dwm_model import (DWM, DWMReward, Normalizer, TokenRSMData, make_synthetic_cache, + pool_tokens, sample_future_dwm, N_TOK, D_TOK) +from dwm_readout import load_critic_dwm, verify_pooling + +TINY = dict(depth=1, heads=2, dim_head=8, mlp_dim=32, dropout=0.0, emb_dropout=0.0) +TINY_FLAGS = ["--depth", "1", "--heads", "2", "--dim-head", "8", "--mlp", "32", "--dropout", "0"] + + +@pytest.fixture(scope="module") +def cache(tmp_path_factory): + root = tmp_path_factory.mktemp("syncache") + make_synthetic_cache(root, n_ep=6, ep_len=(20, 28), seed=0) + return root + + +@pytest.fixture(scope="module") +def data(cache): + return TokenRSMData(cache, chunk=8, seed=0) + + +def test_cache_layout(cache, data): + tok = np.load(cache / "tokens" / "tok.f16.npy", mmap_mode="r") + assert tok.shape[1:] == (N_TOK, D_TOK) and tok.dtype == np.float16 + info = json.loads((cache / "tokens" / "TOKENS.json").read_text()) + assert info["shape"] == list(tok.shape) + assert data.n_pr == 9 and data.adim == 7 + assert data.stats["mu"].shape == (N_TOK, D_TOK) + + +def test_pooling_matches_pooled_cache(cache): + r = verify_pooling(cache, n=64) + assert r["dim"] == 1545, r + assert r["fp16_ok"], r + + +def test_shapes(data): + m = DWM(N_TOK, D_TOK, 9, 56, **TINY) + r = DWMReward(N_TOK, D_TOK, 9) + assert m.dim == 424 and m.n_seq == N_TOK + 1 + rng = np.random.default_rng(0) + b = data.sample(3, rng, 0.9, 0.99, "train") + norm = Normalizer(data.stats) + tn, pn = norm.tok(b["tok_now"]), norm.pr(b["pr_now"]) + assert tn.shape == (3, N_TOK, D_TOK) and pn.shape == (3, 9) and b["a_now"].shape == (3, 56) + xk, xp, k = torch.randn_like(tn), torch.randn_like(pn), torch.rand(3) + v_tok, v_pr = m(tn, pn, b["a_now"], b["beta"], xk, xp, k) + assert v_tok.shape == (3, N_TOK, D_TOK) and v_pr.shape == (3, 9) + assert torch.isfinite(v_tok).all() and torch.isfinite(v_pr).all() + assert r(tn, pn).shape == (3,) + # the geometric future never leaves the episode and beta is in the band + assert (b["fut_idx"] >= b["t_idx"]).all() and (b["fut_idx"] < data.ep_to[b["ep"]]).all() + assert (b["beta"] >= 0.9).all() and (b["beta"] <= 0.99).all() + # full-size configuration: ~20 M as the plan states + full = DWM(N_TOK, D_TOK, 9, 56) + n = sum(p.numel() for p in full.parameters()) + assert 18e6 < n < 24e6, n + + +def test_flow_loss_decreases(data): + torch.manual_seed(0) + m = DWM(N_TOK, D_TOK, 9, 56, **TINY) + norm = Normalizer(data.stats) + opt = torch.optim.AdamW(m.parameters(), lr=1e-3) + rng = np.random.default_rng(1) + b = data.sample(6, rng, 0.9, 0.99, "train") # one fixed batch: the loss must fall + tn, tf = norm.tok(b["tok_now"]), norm.tok(b["tok_fut"]) + pn, pf = norm.pr(b["pr_now"]), norm.pr(b["pr_fut"]) + y_tok = (tf - tn) / 1.0; y_pr = (pf - pn) + g = torch.Generator().manual_seed(0) + k = torch.rand(6, generator=g); nt = torch.randn(y_tok.shape, generator=g); npr = torch.randn(y_pr.shape, generator=g) + xk = (1 - k)[:, None, None] * y_tok + k[:, None, None] * nt + xp = (1 - k)[:, None] * y_pr + k[:, None] * npr + losses = [] + for it in range(40): + v_tok, v_pr = m(tn, pn, b["a_now"], b["beta"], xk, xp, k) + loss = (v_tok - (y_tok - nt)).pow(2).mean() + (v_pr - (y_pr - npr)).pow(2).mean() + opt.zero_grad(); loss.backward(); opt.step() + losses.append(float(loss)) + assert losses[-1] < 0.7 * losses[0], losses[::10] + + +def test_sample_future_runs(data): + torch.manual_seed(0) + m = DWM(N_TOK, D_TOK, 9, 56, **TINY).eval() + norm = Normalizer(data.stats) + rng = np.random.default_rng(2) + b = data.sample(2, rng, 0.9, 0.99, "val") + tn, pn = norm.tok(b["tok_now"]), norm.pr(b["pr_now"]) + rms_tok = torch.ones(N_TOK, D_TOK); rms_pr = torch.ones(9) + xt, xp = sample_future_dwm(m, tn, pn, b["a_now"], b["beta"], rms_tok, rms_pr, n_steps=3, n=4, micro=3) + assert xt.shape == (8, N_TOK, D_TOK) and xp.shape == (8, 9) + assert torch.isfinite(xt).all() + # common random numbers: same x0 -> identical samples + x0 = (torch.randn(8, N_TOK, D_TOK), torch.randn(8, 9)) + a1, _ = sample_future_dwm(m, tn, pn, b["a_now"], b["beta"], rms_tok, rms_pr, 3, n=4, x0=x0) + a2, _ = sample_future_dwm(m, tn, pn, b["a_now"], b["beta"], rms_tok, rms_pr, 3, n=4, x0=x0) + assert torch.equal(a1, a2) + + +def n_particles_is_one(n): + return n == 1 + + +def _run_trainer(cache, out, steps, nproc=1, extra=()): + cmd = [sys.executable, "-m", "torch.distributed.run", "--standalone", f"--nproc_per_node={nproc}", + str(HERE / "train_rsm_dwm.py"), "--cache", str(cache), "--out", str(out), + "--batch", "8", "--micro", "4", "--steps", str(steps), "--eval-every", "3", + "--eval-rows", "8", "--eval-frames", "8", "--eval-minmse-n", "2", "--flow-steps", "2", + "--save-every", "3", "--warm-cache", "0", "--wandb-mode", "disabled", "--print-every", "1", + *TINY_FLAGS, *extra] + env = dict(os.environ, OMP_NUM_THREADS="2", CUDA_VISIBLE_DEVICES="") + p = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=900) + assert p.returncode == 0, p.stdout[-3000:] + "\n" + p.stderr[-3000:] + return p.stdout + + +HIST_KEYS = {"step", "reward_auc", "cfm_val", "per_task", "by_horizon", "q_action_gap", "q_action_winrate", + "q_success_auc", "q_mean", "identity", "minmse_train", "minmse_val", "meanmse_train", + "meanmse_val", "staymse_train", "staymse_val", "meanmse", "staymse"} + + +def test_ddp_launch_and_resume(cache, tmp_path): + out = tmp_path / "run" + log = _run_trainer(cache, out, steps=6, nproc=1) + assert "[dwm] params:" in log and "[dwm] EVAL 3:" in log and "[dwm] DONE" in log + hist = json.loads((out / "history.json").read_text()) + assert [h["step"] for h in hist] == [3, 6] + assert HIST_KEYS <= set(hist[-1]), HIST_KEYS - set(hist[-1]) + for f in ("ckpt.pt", "ckpt_s3.pt", "ckpt_s6.pt", "ckpt_best.pt"): + assert (out / f).exists(), f + assert all(np.isfinite(hist[-1][k]) for k in ("cfm_val", "minmse_val", "staymse_val", "q_action_winrate")) + # resume from ckpt.pt: continues at step 7, adds one eval record + log2 = _run_trainer(cache, out, steps=9, nproc=1) + assert "RESUMED at step 6/9" in log2, log2[-2000:] + hist = json.loads((out / "history.json").read_text()) + assert [h["step"] for h in hist] == [3, 6, 9] + # timing probe path + log3 = _run_trainer(cache, tmp_path / "timing", steps=4, nproc=1, extra=("--time-steps", "3")) + assert "[dwm] TIMING" in log3 + + +def test_ddp_two_procs_gloo(cache, tmp_path): + """The sharded evaluation and all_gather path (2 CPU ranks, gloo).""" + out = tmp_path / "run2" + log = _run_trainer(cache, out, steps=3, nproc=2) + hist = json.loads((out / "history.json").read_text()) + assert len(hist) == 1 and hist[0]["eval_rows"] == 8 and hist[0]["eval_frames"] == 8 + assert (out / "ckpt.pt").exists() + + +def test_readout_interface(cache, tmp_path, data): + out = tmp_path / "run_ro" + _run_trainer(cache, out, steps=3, nproc=1) + crit = load_critic_dwm(out / "ckpt_best.pt", device="cpu") + rng = np.random.default_rng(3) + fb = data.sample_frames(4, rng, "val") + x, a, pr = fb["x"], fb["a"], fb["pr_now"] + q1 = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=1, mode="d1", proprio=pr, flow_steps=2) + assert q1.shape == (4,) and (q1 >= 0).all() and (q1 <= 1).all() + q1b = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=1, mode="d1", proprio=pr, flow_steps=2) + assert torch.equal(q1, q1b) # CRN: same seed -> same Q + q1c = crit.q(x, a, 0.95, n_particles=3, crn_seed=1, depth=1, mode="d1", proprio=pr, flow_steps=2) + assert not torch.equal(q1, q1c) + # dense-head logit averaging (the primary planning read-out): mean logit over particles, same CRN + qd, qlog = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=1, mode="d1", proprio=pr, flow_steps=2, + return_logit=True) + assert torch.equal(qd, q1) and qlog.shape == (4,) and torch.isfinite(qlog).all() + # temperature: q_logit unchanged, q moves toward 0.5 for T > 1 (monotone shrink of the logit) + qT, qlogT = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=1, mode="d1", proprio=pr, flow_steps=2, + return_logit=True, temperature=4.0) + assert torch.equal(qlogT, qlog) and ((qT - 0.5).abs() <= (qd - 0.5).abs() + 1e-6).all() + # two-stage screening: full-length outputs; non-rescored rows keep stage-1 values; rescored rows differ + x8 = torch.cat([x, x]); a8 = torch.cat([a, a * 0.5]); pr8 = torch.cat([pr, pr]) + q_s1, ql_s1 = crit.q(x8, a8, 0.95, n_particles=2, crn_seed=0, proprio=pr8, flow_steps=2, return_logit=True) + q_ts, ql_ts = crit.q(x8, a8, 0.95, n_particles=2, crn_seed=0, proprio=pr8, flow_steps=2, return_logit=True, + rescore_top=3, n_particles_rescore=5) + assert q_ts.shape == (8,) and ql_ts.shape == (8,) + top = torch.topk(ql_s1, 3).indices; keep = torch.ones(8, dtype=torch.bool); keep[top] = False + assert torch.equal(q_ts[keep], q_s1[keep]) and torch.equal(ql_ts[keep], ql_s1[keep]) + # calib.json next to the checkpoint is picked up by load_critic_dwm + (out / "calib.json").write_text('{"T": 2.5}') + crit2 = load_critic_dwm(out / "ckpt_best.pt", device="cpu") + assert crit2.temperature == 2.5 and load_critic_dwm(out / "ckpt_best.pt", device="cpu", calib=None).temperature == 1.0 + + class Hop: # hop policy on the pooled state + d_act = 56 + def __call__(self, pooled, eps): + assert pooled.shape[1] == 1545 and eps.shape[1] == 56 + return 0.1 * eps + q2, hops = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=2, mode="fold", proprio=pr, + hop_policy=Hop(), flow_steps=2, return_hops=True) + assert q2.shape == (4,) and len(hops) == 2 and hops[0].shape == (4, 3) + with pytest.raises(ValueError): + crit.q(x, a, 0.95, depth=2, mode="fold", proprio=pr) + r = crit.reward(x, pr) + assert r.shape == (4,) + xt, xp = crit.sample_future(x, a, 0.95, proprio=pr, n=2, crn_seed=0, flow_steps=2) + assert xt.shape == (8, N_TOK, D_TOK) and xp.shape == (8, 9) + assert pool_tokens(xt, xp).shape == (8, 1545) + + +def test_goal_label_and_goal_clf_readout(cache, tmp_path, data): + """--reward-mode goal on the token data; goal classifier training on the pooled cache; goal_clf read-out.""" + dg = TokenRSMData(cache, chunk=8, seed=0, reward_mode="goal") + g = np.load(cache / "goal.npz")["goal"] + assert np.array_equal(dg.r, g.astype(np.float32)) and 0 < dg.r.mean() < 1 + for e in range(dg.n_ep): # goal frames only inside successful episodes + if not dg.ep_success[e]: + assert dg.r[dg.ep_from[e]:dg.ep_to[e]].sum() == 0 + # trainer accepts the mode + out = tmp_path / "run_goal" + log = _run_trainer(cache, out, steps=3, nproc=1, extra=("--reward-mode", "goal")) + assert "goal label from" in log + # standalone classifier on the pooled cache + outc = tmp_path / "goal_clf" + cmd = [sys.executable, str(HERE / "train_goal_clf.py"), "--cache", str(cache), "--out", str(outc), + "--steps", "30", "--batch", "64", "--eval-every", "15", "--wandb-mode", "disabled"] + p = subprocess.run(cmd, capture_output=True, text=True, env=dict(os.environ, CUDA_VISIBLE_DEVICES=""), timeout=600) + assert p.returncode == 0, p.stdout[-2000:] + p.stderr[-2000:] + ck = torch.load(outc / "clf.pt", map_location="cpu", weights_only=False) + assert ck["config"]["d_in"] == 1545 and ck["config"]["label"] == "env_success_replay" + assert ck["norm"]["mu"].shape == (1545,) + # read-out with the goal classifier + crit = load_critic_dwm(out / "ckpt_best.pt", device="cpu") + rng = np.random.default_rng(5) + fb = data.sample_frames(4, rng, "val") + q, ql = crit.q(fb["x"], fb["a"], 0.95, n_particles=2, crn_seed=0, proprio=fb["pr_now"], flow_steps=2, + reward="goal_clf", reward_path=outc / "clf.pt", return_logit=True) + assert q.shape == (4,) and ql.shape == (4,) and (q >= 0).all() and (q <= 1).all() and torch.isfinite(ql).all() + q2 = crit.q(fb["x"], fb["a"], 0.95, n_particles=2, crn_seed=0, proprio=fb["pr_now"], flow_steps=2, reward="goal_clf") + assert torch.equal(q, q2) # cached classifier, same CRN -> same Q + r = crit.reward(fb["x"], fb["pr_now"], reward="goal_clf") + assert r.shape == (4,) + + +def test_calib_and_timing_scripts(cache, tmp_path): + out = tmp_path / "run_cal" + _run_trainer(cache, out, steps=3, nproc=1) + env = dict(os.environ, CUDA_VISIBLE_DEVICES="") + p = subprocess.run([sys.executable, str(HERE / "calib_dwm.py"), "--cache", str(cache), "--ckpt", str(out / "ckpt_best.pt"), + "--max-frames", "64"], capture_output=True, text=True, env=env, timeout=600) + assert p.returncode == 0, p.stdout[-2000:] + p.stderr[-2000:] + c = json.loads((out / "calib.json").read_text()) + assert c["T"] > 0 and c["bce_after"] <= c["bce_before"] + 1e-6 and "ece_after" in c + p = subprocess.run([sys.executable, str(HERE / "dwm_readout_timing.py"), "--cache", str(cache), "--ckpt", str(out / "ckpt_best.pt"), + "--n-cand", "20", "--reps", "1", "--micro", "16"], capture_output=True, text=True, env=env, timeout=900) + assert p.returncode == 0, p.stdout[-2000:] + p.stderr[-2000:] + r = json.loads((out / "readout_timing.json").read_text()) + assert "two_stage_4_top16_64_s" in r and r["flat_4_particles_s"] > 0 diff --git a/frozen/rsm_libero_freeze_20261002/test_lewm_port.py b/frozen/rsm_libero_freeze_20261002/test_lewm_port.py new file mode 100644 index 0000000000000000000000000000000000000000..5788305d7539faf2754c4073a3407fb75355be61 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/test_lewm_port.py @@ -0,0 +1,143 @@ +"""Checks on the LeWM torch port (gen_q#268). CPU-only, seconds to run. + +The port is of a JAX reference this venv cannot execute (no jax), so its correctness has to be +ASSERTED rather than assumed. These are the four things that, if wrong, would silently turn LeWM +into a different method and make its column in the flagship table meaningless: + + 1. SIGReg is the Epps-Pulley statistic the reference computes -- checked against an independent + numpy implementation on the same random projections, and against its two limiting behaviours + (small on a standard normal, large on a collapsed representation). + 2. The AdaLN-zero block is the IDENTITY at initialisation. That is what "zero" means; if the + conditioning head were default-initialised, the predictor would start as noise and the recipe + -- which has no target network to stabilise it -- would not train. + 3. The prediction target is NOT detached. The reference comments this explicitly ("NO detach + (recipe)"): the encoder is pulled by the loss through the target as well as the prediction, and + collapse is prevented by SIGReg alone. Detaching is the single most natural "cleanup" someone + would apply, so the test pins it. + 4. The read-out round-trips: a checkpoint in train_lewm.py's format loads, scores, stays in [0,1], + and `fold` at depth 1 equals `d1`. + +usage: python test_lewm_port.py (or pytest test_lewm_port.py) +""" +import numpy as np +import torch + +from lewm_model import CTX, N_PREDS, AdaLNBlock, Encoder, LeWM, RewardProbe, sigreg_stat + + +def _sigreg_numpy(emb, A, knots=17): + """Independent implementation, transcribed from the reference's jnp version.""" + T, B, D = emb.shape + t = np.linspace(0.0, 3.0, knots) + dt = 3.0 / (knots - 1) + w = np.full((knots,), 2 * dt) + w[0] = dt + w[-1] = dt + phi = np.exp(-t ** 2 / 2.0) + weights = w * phi + x_t = (emb @ A)[..., None] * t + err = (np.cos(x_t).mean(-3) - phi) ** 2 + np.sin(x_t).mean(-3) ** 2 + return float(((err @ weights) * B).mean()) + + +def test_sigreg_matches_reference(): + g = torch.Generator().manual_seed(0) + emb = torch.randn(4, 64, 32, generator=g, dtype=torch.float64) + A = torch.randn(32, 128, generator=g, dtype=torch.float64) + A = A / A.norm(dim=0, keepdim=True) + got = float(sigreg_stat(emb, A=A, num_proj=128)) + want = _sigreg_numpy(emb.numpy(), A.numpy()) + assert abs(got - want) < 1e-8, f"SIGReg {got} != independent {want}" + + +def test_sigreg_penalises_collapse(): + g = torch.Generator().manual_seed(1) + normal = torch.randn(4, 256, 32, generator=g, dtype=torch.float64) + collapsed = torch.zeros(4, 256, 32, dtype=torch.float64) + 3.0 + A = torch.randn(32, 256, generator=g, dtype=torch.float64) + A = A / A.norm(dim=0, keepdim=True) + s_n = float(sigreg_stat(normal, A=A, num_proj=256)) + s_c = float(sigreg_stat(collapsed, A=A, num_proj=256)) + assert s_c > 10 * s_n, f"SIGReg does not penalise collapse: normal {s_n}, collapsed {s_c}" + + +def test_adaln_zero_is_identity_at_init(): + torch.manual_seed(0) + blk = AdaLNBlock(32, heads=4, mlp_dim=64) + x = torch.randn(3, CTX, 32) + c = torch.randn(3, CTX, 32) + mask = torch.tril(torch.ones(CTX, CTX, dtype=torch.bool))[None, None] + y = blk(x, c, mask) + assert torch.allclose(y, x, atol=0, rtol=0), \ + f"AdaLN-zero block is not the identity at init (max |dy| = {float((y - x).abs().max())})" + + +def test_encoder_stage_count(): + assert Encoder(16, in_ch=6, res=84).n_stages == 5 # 84->42->21->11->6->3 + assert Encoder(16, in_ch=3, res=64).n_stages == 4 # 64->32->16->8->4 + assert Encoder(16, in_ch=6, res=84).out_res <= 4 + + +def test_target_is_not_detached(): + """The encoder gradient must differ from the detached-target variant -- i.e. the loss really does + pull the target. If someone adds .detach(), this test is the one that fails.""" + torch.manual_seed(0) + m = LeWM(size="s", a_dim=14, in_ch=6, res=32, ctx=CTX) + frames = torch.randint(0, 255, (2, CTX + N_PREDS, 6, 32, 32), dtype=torch.uint8) + acts = torch.randn(2, CTX + N_PREDS, 14) + + def enc_grad(detach): + m.zero_grad(set_to_none=True) + pred, emb = m(frames, acts) + tgt = emb[:, N_PREDS:] + (pred - (tgt.detach() if detach else tgt)).pow(2).mean().backward() + return m.encoder.fc2.weight.grad.detach().clone() + + g_live = enc_grad(False) + g_det = enc_grad(True) + assert not torch.allclose(g_live, g_det, atol=1e-12), \ + "encoder gradient is identical with and without a detached target: the target is detached" + assert float(g_live.abs().sum()) > 0, "no gradient reaches the encoder at all" + + +def test_readout_round_trip(tmp=None): + import tempfile, os + import lewm_readout + torch.manual_seed(0) + a_dim, res, B = 56, 32, 5 + m = LeWM(size="s", a_dim=a_dim, in_ch=6, res=res, ctx=CTX) + pr = RewardProbe(m.emb_dim) + blob = {"model": "lewm", "lewm": m.state_dict(), "probe": pr.state_dict(), + "config": {"chunk": 8}, "d_act": a_dim, "step": 1, "q_action_winrate": 0.5, + "cams": ["agentview_image", "robot0_eye_in_hand_image"], + "arch": {"size": "s", "emb_dim": m.emb_dim, "a_dim": a_dim, "in_ch": 6, "res": res, + "ctx": CTX, "chunk": 8, "adim": 7}} + d = tempfile.mkdtemp() + p = os.path.join(d, "ckpt.pt") + torch.save(blob, p) + crit = lewm_readout.load_critic_lewm(p, device="cpu") + img = torch.randint(0, 255, (B, 6, res, res), dtype=torch.uint8) + a = torch.randn(B, a_dim).clamp(-1, 1) + q1, ql = crit.q((img, None), a, mode="d1", depth=1, gamma=0.99, return_logit=True) + qf, _ = crit.q((img, None), a, mode="fold", depth=1, gamma=0.99, return_logit=True) + q4, _ = crit.q((img, None), a, mode="fold", depth=4, gamma=0.99, return_logit=True) + for name, q in (("d1", q1), ("fold1", qf), ("fold4", q4)): + assert q.shape == (B,), f"{name}: shape {tuple(q.shape)}" + assert torch.isfinite(q).all(), f"{name}: non-finite" + assert bool((q >= 0).all() and (q <= 1).all()), f"{name}: outside [0,1]" + assert torch.allclose(q1, qf, atol=1e-6), "fold at depth 1 must equal d1" + # deterministic: the same inputs twice give the same answer bit for bit + q1b, _ = crit.q((img, None), a, mode="d1", depth=1, gamma=0.99, return_logit=True) + assert torch.equal(q1, q1b), "LeWM read-out is not deterministic" + # float frames in [0,1] (what the planner hands it) must match the uint8 path + qf_float, _ = crit.q((img.float() / 255.0, None), a, mode="d1", depth=1, gamma=0.99, + return_logit=True) + assert torch.allclose(q1, qf_float, atol=1e-5), "float-in-[0,1] frames disagree with uint8" + + +if __name__ == "__main__": + fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")] + for f in fns: + f() + print(f" ok {f.__name__}") + print(f"\nall {len(fns)} LeWM port checks passed") diff --git a/frozen/rsm_libero_freeze_20261002/their_ctl.sbatch b/frozen/rsm_libero_freeze_20261002/their_ctl.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..1d2f530ffbb1a1d69f255f666da6b7adf16194cc --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/their_ctl.sbatch @@ -0,0 +1,16 @@ +#!/bin/bash +#SBATCH --job-name=their_ctl +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=64G +#SBATCH --time=12:00:00 +#SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/mit/%x_%j.out +#SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/mit/%x_%j.err +set -uo pipefail +export PYTHONUNBUFFERED=1 +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +export FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')" +cd /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python their_trainer_control.py +RC=$?; echo "[ctl] rc=$RC"; exit $RC diff --git a/frozen/rsm_libero_freeze_20261002/their_trainer_control.py b/frozen/rsm_libero_freeze_20261002/their_trainer_control.py new file mode 100644 index 0000000000000000000000000000000000000000..5488c588ca9bff7d497d3c9e1577c5b57019df53 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/their_trainer_control.py @@ -0,0 +1,46 @@ +"""CONTROL: run the lane's own BC trainer to its full budget. + +Their bcdemos checkpoint records a held-out ODE-sampled MSE of 0.0032 at step +110000. Our pipeline plateaus near 0.042 at 120000. A 20k-step bisect showed both +paths equal (0.0495 theirs vs 0.0471 ours), so the question is whether their +number is reachable at all at the full budget, or whether it came from somewhere +else. Same loader, same head, same loss, same optimiser, logged every 5000 steps. +""" +import importlib.util, sys, numpy as np, torch + +W = ("/data/pulkitag/hamer_diffusion_policy_project/projects/" + "continual_learning_for_manipulation/.claude/worktrees/" + "08312026_jvq_recap_worktree/scripts/rlinf_jvq") +sys.path.insert(0, W) +_s = importlib.util.spec_from_file_location("lh", W + "/09032026_latent_head_bc.py") +lh = importlib.util.module_from_spec(_s); sys.modules["lh"] = lh; _s.loader.exec_module(lh) + +CACHE = "/data/pulkitag/users/rli14/libero10_demo_ogpo_cache_srv" +CH, BS, STEPS, DEV = 10, 1024, 120000, "cuda" + +def main(): + z, p, a, task, val = lh.load_cache(CACHE, CH) + tr = torch.nonzero(~val).squeeze(1); va = torch.nonzero(val).squeeze(1) + print(f"[ctl] {len(z)} frames, {len(tr)} train / {len(va)} val", flush=True) + torch.manual_seed(0) + m = lh.Head(4096, 8, len(lh.FS15), 1024, 4, CH).to(DEV) + opt = torch.optim.Adam(m.parameters(), lr=3e-4) + best = float("inf") + for step in range(1, STEPS + 1): + idx = tr[torch.randint(0, len(tr), (BS,))] + zb, pb, tb = z[idx].to(DEV), p[idx].to(DEV), task[idx].to(DEV) + ab = a[idx].to(DEV) + adv = torch.full((BS,), 2, dtype=torch.long, device=DEV) + k = torch.rand(BS, device=DEV); eps = torch.randn_like(ab) + x_k = (1 - k)[:, None, None] * ab + k[:, None, None] * eps + loss = ((m(zb, pb, tb, adv, x_k, k).view_as(ab) - (ab - eps)) ** 2).mean() + opt.zero_grad(); loss.backward(); opt.step() + if step % 5000 == 0 or step == STEPS: + v = lh.val_mse(m, z[va], p[va], task[va], a[va], DEV) + best = min(best, v) + print(f"[ctl] {step} cfm={float(loss):.5f} val_mse={v:.5f} best={best:.5f}", + flush=True) + print(f"[ctl] DONE best={best:.5f} (their checkpoint records 0.00319)", flush=True) + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/thr_test.py b/frozen/rsm_libero_freeze_20261002/thr_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5167a92bcfd741037061bcdd47c96a049f70b280 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/thr_test.py @@ -0,0 +1,32 @@ +"""Throughput comparison. thr_all = SR*max/mean_steps_all conflates success rate with +speed; the paired steps-to-success on episodes BOTH arms solved isolates speed alone.""" +import json, sys, statistics as st +from math import sqrt, erfc +E="/data/pulkitag/users/rli14/rsm_libero_runs/eval" +def load(f): + r=json.load(open(f"{E}/{f}.json")); d={} + for t,eps in r["episodes_detail"].items(): + for e in eps: d[(t,e["episode"])]=(bool(e["success"]), e["steps"]) + return r, d +pairs=[] +for i in range(1,len(sys.argv),2): pairs.append((sys.argv[i],sys.argv[i+1])) +TA=TB=SA=SB=0.0; dif=[]; wins=loss=0; n=0 +print(f"{'pair':26s} {'thr_all A':>10s} {'thr_all B':>10s} {'d%':>7s} {'thrS A':>8s} {'thrS B':>8s}") +for a,b in pairs: + RA,DA=load(a); RB,DB=load(b) + TA+=RA["throughput_all"]; TB+=RB["throughput_all"] + SA+=RA["throughput_succ"]; SB+=RB["throughput_succ"]; n+=1 + d=(RA["throughput_all"]-RB["throughput_all"])/RB["throughput_all"]*100 + print(f"{a[:26]:26s} {RA['throughput_all']:10.3f} {RB['throughput_all']:10.3f} " + f"{d:+7.1f} {RA['throughput_succ']:8.3f} {RB['throughput_succ']:8.3f}") + both=[k for k in set(DA)&set(DB) if DA[k][0] and DB[k][0]] + for k in both: + dd=DA[k][1]-DB[k][1]; dif.append(dd) + wins+= dd<0; loss+= dd>0 +print(f"\nMEAN thr_all {TA/n:.3f} vs {TB/n:.3f} {(TA-TB)/TB*100:+.1f}%") +print(f"MEAN thr_succ {SA/n:.3f} vs {SB/n:.3f} {(SA-SB)/SB*100:+.1f}%") +print(f"\nSPEED on {len(dif)} episodes BOTH arms solved (same init):") +print(f" mean {st.mean(dif):+.1f} steps median {st.median(dif):+.0f}") +print(f" A faster on {wins}, slower on {loss}, tied on {len(dif)-wins-loss}") +z=(wins-loss)/sqrt(max(wins+loss,1)); p=erfc(abs(z)/sqrt(2)) +print(f" sign test z={z:.2f} p={p:.3f} {'SIGNIFICANT' if p<0.05 else 'not significant'}") diff --git a/frozen/rsm_libero_freeze_20261002/train_goal_clf.py b/frozen/rsm_libero_freeze_20261002/train_goal_clf.py new file mode 100644 index 0000000000000000000000000000000000000000..d67bb31a4222c03dc17bb6f0674b6525464c382f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/train_goal_clf.py @@ -0,0 +1,122 @@ +"""Standalone GOAL-STATE classifier on the pooled z-scored state (orchestrator, 2026-09-18). +PRIVILEGED-INFORMATION ABLATION: the label is env success obtained by state replay, which RISE and its +baselines never see (they use the 0/1 expert-membership reward). Not the primary read-out. + + p(goal | x) with x = clip((feat - mu) / max(sd, sd_floor), -z_clip, z_clip), feat = [z(1536) | proprio(9)] + (the cache's STATE DEFINITION, via data.LiberoRSMData), label = cache//goal.npz (env success by replay). + +MLP 1545 -> 512 x 2 -> 1, balanced BCE, AdamW 3e-4 wd 0.01, 20k steps at batch 4096, held-out AUC and +false-positive rate (p > 0.5 on goal = 0 frames) on the val episodes. Saves /clf.pt with +{"net", "config", "norm": {mu, sd, z_clip, sd_floor}} so dwm_readout can score sampled futures without the cache. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json, time +from pathlib import Path +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from data import LiberoRSMData +from train_rsm import auc + + +def build_net(d_in=1545, width=512, depth=2): + layers, d = [], d_in + for _ in range(depth): + layers += [nn.Linear(d, width), nn.SiLU()]; d = width + layers += [nn.Linear(d, 1)] + return nn.Sequential(*layers) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True); ap.add_argument("--out", required=True) + ap.add_argument("--goal-file", default="", help="default /goal.npz") + ap.add_argument("--width", type=int, default=512); ap.add_argument("--depth", type=int, default=2) + ap.add_argument("--steps", type=int, default=20000); ap.add_argument("--batch", type=int, default=4096) + ap.add_argument("--lr", type=float, default=3e-4); ap.add_argument("--wd", type=float, default=0.01) + ap.add_argument("--eval-every", type=int, default=2000); ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", "")) + ap.add_argument("--wandb-project", default=_os.environ.get("RSM_WANDB_PROJECT", "rsm_rise")) + ap.add_argument("--wandb-name", default=""); ap.add_argument("--wandb-mode", default="online") + args = ap.parse_args() + torch.manual_seed(args.seed); rng = np.random.default_rng(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=8, seed=args.seed, in_ram=True, reward_mode="dense") + gf = Path(args.goal_file) if args.goal_file else Path(args.cache) / "goal.npz" + g = np.load(gf, allow_pickle=True); goal = g["goal"].astype(np.float32) + assert len(goal) == int(d.ep_to[-1]), f"goal.npz has {len(goal)} frames, cache {int(d.ep_to[-1])}" + d.r = goal # per-frame label the sampler returns as r + p = float(goal.mean()); pos_w = torch.tensor(max((1 - p) / max(p, 1e-6), 1.0), device=dev) + print(f"[goal_clf] {d.n_ep} eps ({len(d.train_eps)} train / {len(d.val_eps)} val), dim={d.feat_dim}, " + f"goal frames {p:.4f} (pos_weight {float(pos_w):.1f}), z_clip={getattr(d, 'z_clip', 0)}", flush=True) + wb = None + if args.wandb_entity and args.wandb_mode != "disabled": + try: + import wandb, hashlib + wb = wandb.init(entity=args.wandb_entity, project=args.wandb_project, name=args.wandb_name or out.name, + id=hashlib.md5(str(out.resolve()).encode()).hexdigest()[:16], resume="allow", + mode=args.wandb_mode, dir=str(out), + config={**vars(args), "label": "env_success_replay", + "privileged": "env success via state replay (ablation; not the primary arm)"}) + print(f"[goal_clf] wandb: {wb.url}", flush=True) + except Exception as e: + print(f"[goal_clf] wandb disabled: {e}", flush=True) + net = build_net(d.feat_dim, args.width, args.depth).to(dev) + opt = torch.optim.AdamW(net.parameters(), lr=args.lr, weight_decay=args.wd) + + # fixed held-out set: ALL val frames (episode-level split), for AUC / FPR + val_idx = np.concatenate([np.arange(d.ep_from[e], d.ep_to[e]) for e in d.val_eps]) + xv = torch.from_numpy(d._feat(val_idx)).to(dev); yv = torch.from_numpy(goal[val_idx]).to(dev) + + def evaluate(): + net.eval() + with torch.no_grad(): + lg = torch.cat([net(xv[i:i + 8192]).squeeze(-1) for i in range(0, len(xv), 8192)]) + pr = torch.sigmoid(lg) + net.train() + y = yv.cpu().numpy(); pn = pr.cpu().numpy() + neg, pos = y < 0.5, y >= 0.5 + return {"val_auc": auc(pn, y), "val_fpr@0.5": float((pn[neg] > 0.5).mean()) if neg.any() else float("nan"), + "val_tpr@0.5": float((pn[pos] > 0.5).mean()) if pos.any() else float("nan"), + "val_mean_p_on_goal0": float(pn[neg].mean()) if neg.any() else float("nan"), + "val_mean_p_on_goal1": float(pn[pos].mean()) if pos.any() else float("nan"), + "val_bce": float(F.binary_cross_entropy_with_logits(lg, yv)), "n_val": int(len(y)), + "n_val_goal1": int(pos.sum())} + hist = []; t0 = time.time() + for step in range(1, args.steps + 1): + b = d.sample_frames(args.batch, rng, "train", dev) + logit = net(b["x"]).squeeze(-1) + loss = F.binary_cross_entropy_with_logits(logit, b["r"], pos_weight=pos_w) + opt.zero_grad(); loss.backward(); gn = float(torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0)); opt.step() + if wb is not None and step % 100 == 0: + wb.log({"train/bce": float(loss), "train/gradnorm": gn}, step=step) + if step % args.eval_every == 0 or step == args.steps: + r = evaluate(); r["step"] = step; hist.append(r) + print(f"[goal_clf] {step} bce={float(loss):.4f} val_auc={r['val_auc']:.4f} fpr@0.5={r['val_fpr@0.5']:.4f} " + f"tpr@0.5={r['val_tpr@0.5']:.4f} mean_p(goal0)={r['val_mean_p_on_goal0']:.4f} " + f"({step/(time.time()-t0):.1f} it/s)", flush=True) + if wb is not None: + wb.log({f"eval/{k}": v for k, v in r.items() if k != "step"}, step=step) + (out / "history.json").write_text(json.dumps(hist, indent=1)) + torch.save({"net": net.state_dict(), + "config": {"d_in": d.feat_dim, "width": args.width, "depth": args.depth, + "sd_floor": 0.01, "z_clip": float(getattr(d, "z_clip", 0.0)), + "label": "env_success_replay", + "privileged": "env success via state replay (ablation; RISE baselines use the 0/1 expert-membership reward)", + "task": d.tasks[0], "cache": str(args.cache), + "step": step, "goal_file": str(gf)}, + "norm": {"mu": torch.from_numpy(np.asarray(d.norm_mu, np.float32)), + "sd": torch.from_numpy(np.asarray(d.norm_sd, np.float32)), + "z_clip": float(getattr(d, "z_clip", 0.0)), "sd_floor": 0.01}, + "last_eval": r}, out / "clf.pt") + print("[goal_clf] DONE " + json.dumps(hist[-1]), flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/train_lewm.py b/frozen/rsm_libero_freeze_20261002/train_lewm.py new file mode 100644 index 0000000000000000000000000000000000000000..4ba8d6c9d0c0904963356c696a8d998b025acd25 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/train_lewm.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Train LeWM (LeWorldModel) as a best-of-N scorer for the single-actor flagship (gen_q#268). + +The objective is the reference recipe, unchanged (see lewm_model.py for the port and its declared +deviations): JEPA next-embedding prediction with an AdaLN-zero causal predictor, collapse prevented +by SIGReg alone -- no stop-gradient, no EMA target -- AdamW 5e-5 / wd 1e-3 with a global-norm clip +of 1.0, lambda_sig 0.09. + + loss = || pred_proj(predictor(emb[:, :ctx], act[:, :ctx])) - emb[:, 1:] ||^2 + + 0.09 * sigreg(emb) + +REWARD PROBE. Trained alongside on DETACHED embeddings with its own AdamW(3e-4) and a +class-balanced BCE against the provenance/membership label -- the same label RSM's membership head, +TD-Flow and DINO-WM all read. Detaching is what makes this equivalent to the reference's two-phase +fit (world model first, probe on frozen embeddings second) while costing one pass instead of two: +the probe cannot shape the representation, so the world model that results is the same one the +reference's phase 1 produces. The probe is fitted on BOTH the encoder embedding of a real frame and +the PREDICTED embedding of the next one, because scoring applies it to predicted embeddings and a +probe fitted only on encoder outputs would be evaluated off its own training distribution -- that +mismatch would weaken the baseline for a reason that has nothing to do with the world model. + +CHECKPOINT SELECTION is the rule every other scorer in the table uses: keep the checkpoint that best +RANKS ACTIONS on held-out episodes (the true chunk against a shuffled one), not the last one. + +usage: train_lewm.py --cache cache/ --out runs//wm/lewm [--size m] [--steps 100000] +""" +from __future__ import annotations + +import argparse +import json +import os as _os +import time +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F + +from lewm_data import StreamingFrameData +from lewm_model import (CLIP, CTX, LAMBDA, LEWM_SIZES, LR, N_PREDS, PROBE_LR, WD, LeWM, RewardProbe, + sigreg_stat) + + +def auc(score, label): + s = np.asarray(score, np.float64).ravel() + y = np.asarray(label, np.float64).ravel() > 0.5 + if y.all() or (~y).all(): + return float("nan") + r = s.argsort().argsort().astype(np.float64) + 1.0 + n1 = float(y.sum()) + n0 = float(len(y) - n1) + return float((r[y].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--hdf5", default="", help="source HDF5; default = cache/PACK.json src") + ap.add_argument("--out", required=True) + ap.add_argument("--size", default="m", choices=list(LEWM_SIZES), help="m = the official ~15M config") + ap.add_argument("--chunk", type=int, default=8, help="action chunk the world model is conditioned on") + ap.add_argument("--ctx", type=int, default=CTX) + ap.add_argument("--res", type=int, default=84) + ap.add_argument("--batch", type=int, default=128) + ap.add_argument("--steps", type=int, default=100000, + help="the reference default is 60000; 100000 matches every other scorer in the " + "flagship table, and a baseline given MORE than its own recipe's budget is " + "the safe direction to err in") + ap.add_argument("--lr", type=float, default=LR) + ap.add_argument("--wd", type=float, default=WD) + ap.add_argument("--clip", type=float, default=CLIP) + ap.add_argument("--lambda-sig", type=float, default=LAMBDA) + ap.add_argument("--num-proj", type=int, default=1024, help="SIGReg random projections") + ap.add_argument("--probe-lr", type=float, default=PROBE_LR) + ap.add_argument("--dropout", type=float, default=0.0) + ap.add_argument("--resident", type=int, default=96, help="episodes held in RAM (no image pack)") + ap.add_argument("--refresh-every", type=int, default=8, help="steps between episode swaps") + ap.add_argument("--eval-every", type=int, default=2500) + ap.add_argument("--eval-rows", type=int, default=1024) + ap.add_argument("--save-every", type=int, default=10000) + ap.add_argument("--resume", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--log-every", type=int, default=100) + ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", "")) + ap.add_argument("--wandb-project", default=_os.environ.get("RSM_WANDB_PROJECT", "rsm_rise")) + ap.add_argument("--wandb-name", default="") + ap.add_argument("--wandb-mode", default="online", choices=["online", "offline", "disabled"]) + args = ap.parse_args() + + torch.manual_seed(args.seed) + rng = np.random.default_rng(args.seed) + dev = "cuda" if torch.cuda.is_available() else "cpu" + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + + wb = None + if args.wandb_entity and args.wandb_mode != "disabled": + try: + import hashlib + + import wandb + _rid = hashlib.md5(str(out.resolve()).encode()).hexdigest()[:16] + wb = wandb.init(entity=args.wandb_entity, project=args.wandb_project, + name=args.wandb_name or out.name, id=_rid, resume="allow", + mode=args.wandb_mode, config=vars(args), dir=str(out)) + print(f"[lewm] wandb: {wb.url}", flush=True) + except Exception as e: + print(f"[lewm] wandb disabled: {e}", flush=True) + + d = StreamingFrameData(args.cache, args.hdf5, chunk=args.chunk, ctx=args.ctx, n_preds=N_PREDS, + resident=args.resident, refresh_every=args.refresh_every, seed=args.seed, + res=args.res) + d_act = d.d_act + model = LeWM(size=args.size, a_dim=d_act, in_ch=6, res=args.res, ctx=args.ctx, + dropout=args.dropout).to(dev) + probe = RewardProbe(model.emb_dim).to(dev) + opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd) + popt = torch.optim.AdamW(probe.parameters(), lr=args.probe_lr) + n_par = sum(p.numel() for p in model.parameters()) + print(f"[lewm] size={args.size} emb={model.emb_dim} params={n_par/1e6:.1f}M d_act={d_act} " + f"enc_stages={model.encoder.n_stages} enc_res={model.encoder.out_res} dev={dev}", flush=True) + + pos = float(d.ep_success.mean()) + pos_w = torch.tensor(max((1 - pos) / max(pos, 1e-6), 1.0), device=dev) + + start_step, best_win, hist = 0, -1.0, [] + ck = out / "ckpt.pt" + if args.resume and ck.exists(): + c = torch.load(ck, map_location=dev, weights_only=False) + model.load_state_dict(c["lewm"]) + probe.load_state_dict(c["probe"]) + if "opt" in c: + opt.load_state_dict(c["opt"]) + if "popt" in c: + popt.load_state_dict(c["popt"]) + start_step = int(c["step"]) + best_win = c.get("best_win", -1.0) + hist = c.get("hist", []) + rng = np.random.default_rng(args.seed + 9973 * start_step) + print(f"[lewm] RESUMED at step {start_step}/{args.steps} (best win {best_win:.3f})", flush=True) + if start_step >= args.steps: + print("[lewm] already complete", flush=True) + return + + @torch.no_grad() + def evaluate(): + model.eval(); probe.eval() + b = d.sample(min(args.eval_rows, 512), rng, "val", dev) + pred, emb = model(b["frames"], b["actions"]) + pl = float((pred - emb[:, N_PREDS:]).pow(2).mean()) + # does the probe on the PREDICTED embedding rank the true chunk above a shuffled one? + hist_emb = emb[:, : args.ctx] + a_true = b["actions"][:, : args.ctx] + perm = torch.randperm(a_true.shape[0], device=dev) + z_true = model.step_emb(hist_emb, a_true) + z_shuf = model.step_emb(hist_emb, a_true[perm]) + q_true = torch.sigmoid(probe(z_true)) + q_shuf = torch.sigmoid(probe(z_shuf)) + win = float((q_true > q_shuf).float().mean()) + gap = float((q_true - q_shuf).mean()) + pr = torch.sigmoid(probe(emb[:, args.ctx])).float().cpu().numpy() + a_ = auc(pr, b["label"].cpu().numpy()) + std = float(emb.reshape(-1, emb.shape[-1]).std(0).min()) + model.train(); probe.train() + return {"pred_mse_val": pl, "probe_auc": a_, "action_win": win, "action_gap": gap, + "emb_std_min": std} + + t0 = time.time() + model.train(); probe.train() + for step in range(start_step + 1, args.steps + 1): + b = d.sample(args.batch, rng, "train", dev) + pred, emb = model(b["frames"], b["actions"]) + # NOT detached: the target is the live encoder's own output. This is the recipe. + tgt = emb[:, N_PREDS:] + l_pred = (pred - tgt).pow(2).mean() + l_sig = sigreg_stat(emb.permute(1, 0, 2), num_proj=args.num_proj) + loss = l_pred + args.lambda_sig * l_sig + opt.zero_grad(set_to_none=True) + loss.backward() + gn = float(torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)) + opt.step() + + # ---- reward probe on DETACHED embeddings (see the module docstring) ---- + with torch.no_grad(): + z_enc = emb[:, args.ctx].detach() + z_pred = pred[:, -1].detach() + lg = probe(z_enc) + lg2 = probe(z_pred) + l_probe = 0.5 * (F.binary_cross_entropy_with_logits(lg, b["label"], pos_weight=pos_w) + + F.binary_cross_entropy_with_logits(lg2, b["label"], pos_weight=pos_w)) + popt.zero_grad(set_to_none=True) + l_probe.backward() + gn_p = float(torch.nn.utils.clip_grad_norm_(probe.parameters(), args.clip)) + popt.step() + + if step % 500 == 0: + print(f"[lewm] {step} pred={float(l_pred):.5f} sig={float(l_sig):.5f} " + f"probe={float(l_probe):.4f} gradnorm={gn:.3f} gradnorm_probe={gn_p:.3f} " + f"({step/(time.time()-t0):.2f} it/s)", flush=True) + if wb is not None and (step % args.log_every == 0 or step == 1): + wb.log({"train/loss": float(loss), "train/l_pred": float(l_pred), + "train/l_sigreg": float(l_sig), "train/l_probe": float(l_probe), + "train/gradnorm": gn, "train/gradnorm_probe": gn_p, + "train/it_per_s": step / max(time.time() - t0, 1e-6)}, step=step) + + if step % args.eval_every == 0 or step == args.steps: + e = evaluate() + hist.append({"step": step, **e}) + (out / "history.json").write_text(json.dumps(hist, indent=1)) + print(f"[lewm] EVAL {step}: pred_mse={e['pred_mse_val']:.5f} probe_auc={e['probe_auc']:.4f} " + f"ACTION win={e['action_win']:.3f} gap={e['action_gap']:+.5f} " + f"emb_std_min={e['emb_std_min']:.4f}", flush=True) + if wb is not None: + wb.log({f"eval/{k}": v for k, v in e.items()}, step=step) + blob = {"model": "lewm", "lewm": model.state_dict(), "probe": probe.state_dict(), + "config": vars(args), "arch": {"size": args.size, "emb_dim": model.emb_dim, + "a_dim": d_act, "in_ch": 6, "res": args.res, + "ctx": args.ctx, "chunk": args.chunk, + "adim": d.adim}, + "d_act": d_act, "step": step, "q_action_winrate": e["action_win"], + "cams": list(d.cams), "hdf5": d.hdf5, "cache": str(d.root)} + blob_r = dict(blob) + blob_r["opt"] = opt.state_dict(); blob_r["popt"] = popt.state_dict() + blob_r["best_win"] = max(best_win, e["action_win"]); blob_r["hist"] = hist + tmp = out / "ckpt.pt.tmp" + torch.save(blob_r, tmp) + _os.replace(tmp, out / "ckpt.pt") + if args.save_every and step % args.save_every == 0: + torch.save(blob, out / f"ckpt_s{step}.pt") + # A collapsed representation can rank actions by accident; require a live embedding. + healthy = e["emb_std_min"] > 1e-3 + if e["action_win"] > best_win and healthy: + best_win = e["action_win"] + torch.save(blob, out / "ckpt_best.pt") + print(f"[lewm] new BEST action winrate {best_win:.3f} at step {step}", flush=True) + elif not healthy: + print(f"[lewm] emb_std_min {e['emb_std_min']:.2e}: representation near collapse, " + f"NOT eligible as best", flush=True) + d.close() + print("[lewm] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/train_rsm.py b/frozen/rsm_libero_freeze_20261002/train_rsm.py new file mode 100644 index 0000000000000000000000000000000000000000..320944e67d17c03764ba59920c6dd3ee9d1e431c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/train_rsm.py @@ -0,0 +1,1251 @@ +"""Joint reward-latent + action-conditioned occupancy training (RSM) on LIBERO-10. + +No TD target, no return regression: the occupancy target is a REAL logged future +frame drawn at k ~ Geom(1-beta), and reward enters only at read-out. + +Diagnostics follow COLLAPSE_ANALYSIS: batch losses can look healthy while the +critic is useless, so the headline validation metric is the ACTION-ranking gap +(does Q prefer the logged chunk over a foreign chunk at the same state), not the +state-ranking AUC. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import os as _os +import argparse, json, time +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from model import (Encoder, RewardHead, OccFlow, ema_update) +from model import mlp, IdentityEncoder, PCAEncoder +from data import LiberoRSMData + + +def auc(score, label): + score = np.asarray(score, np.float64); label = np.asarray(label) > 0.5 + if label.all() or (~label).all(): + return float("nan") + order = np.argsort(score) + ranks = np.empty(len(score), np.float64); ranks[order] = np.arange(1, len(score) + 1) + npos = int(label.sum()); nneg = len(label) - npos + return float((ranks[label].sum() - npos * (npos + 1) / 2) / (npos * nneg)) + + +@torch.no_grad() +def sample_future(flow, enc_z, a, task, beta, rms, n_steps=8, n=1, x0=None): + """Euler ODE sample of the residual, returned as an absolute latent. + x0: optional initial noise [rows, D] -- lets a caller share the same draws across + candidates (common random numbers) so a comparison of Q values is paired.""" + B, D = enc_z.shape + if n > 1: + enc_z = enc_z.repeat_interleave(n, 0); a = a.repeat_interleave(n, 0) + task = task.repeat_interleave(n, 0); beta = beta.repeat_interleave(n, 0) + x = torch.randn(enc_z.shape[0], D, device=enc_z.device) if x0 is None else x0 + for s in range(n_steps): + k = torch.full((enc_z.shape[0],), 1.0 - s / n_steps, device=enc_z.device) + x = x + flow(enc_z, a, task, beta, x, k) / n_steps + return enc_z + x * rms + + +# ------------------------------------------------------------------------------------------------ +# TD-FLOW (gen_q#268): the occupancy target by BOOTSTRAPPING instead of Monte Carlo. +# +# Both rules fit the same object, m_beta(. | s, a), the beta-discounted successor measure, which +# obeys the Bellman equation ON MEASURES +# +# m_beta(. | s,a) = (1 - beta) P(. | s,a) + beta E_{s' ~ P(.|s,a)}[ m_beta(. | s', pi(s')) ]. +# +# RSM samples the LEFT-hand side directly: data.py returns s_{t+k} with k ~ Geom(1-beta) truncated +# at the episode end, an exact draw from m_beta along the behaviour trajectory (no bootstrap +# anywhere). TD-Flow samples the RIGHT-hand side using the previous iterate (an EMA target field +# theta_bar), which is Farebrother, Wiltzer, Bellemare, Castro, Pires & Tomar, "Temporal Difference +# Flows" (arXiv:2503.09817): +# +# X1 ~ (1 - beta) delta_{s'} + beta * delta_{psi_1(X0 | s', a'; theta_bar)} (eq. 6/7) +# +# and regresses the SAME rectified-flow loss onto that X1. Ported from the ocbench TDFlowAgent +# (projs/gen_q branch baseline/tdflow-ocbench, impls/agents/tdflow.py), which subclasses RSMAgent +# and overrides ONLY the occupancy target; this port keeps the same discipline -- identical velocity +# field and architecture, identical residual/RMS normaliser, identical reward head, identical beta +# sampling INCLUDING data.py's per-anchor truncation cap, identical chunking, optimiser and steps. +# The only thing that moves is what `delta` regresses onto. +# +# FLOW FRAME. OccFlow predicts the NORMALISED RESIDUAL y = (z_fut - z_now) / rms, so the flow's +# data space is a residual w.r.t. whatever state it is conditioned on. A sample or a path produced +# at (s', a') must therefore be TRANSLATED into the (s, a) frame before it can be a target for the +# field conditioned on (s, a). The map is a pure translation by (z_next - z_now)/rms, which is why +# velocities transfer unchanged and only positions shift (same argument as TDFlowAgent's +# _to_flow_frame / _from_flow_frame). All of this code therefore works in ABSOLUTE latents and +# lets the existing `delta = z_tgt - z_now` line do the framing. +TDFLOW_VARIANTS = ("td", "td_c", "td2") + + +def _euler_to_tau(flow_, z, a, task, beta, x0, tau, n_steps): + """`sample_future`'s Euler integrator stopped at a PER-SAMPLE time tau instead of at 1. + + Same field, same left-endpoint Euler rule, same n_steps; only the step size is per-sample + (tau / n_steps), so each row lands on psi_tau rather than psi_1. Returned in the FLOW's + coordinates (normalised residual), not as an absolute latent -- td2 regresses velocities there. + Used by the td2 variant only; td / td_c never need an interior point. + """ + x = x0 + dt = tau / n_steps + for s_ in range(n_steps): + k = 1.0 - s_ * dt + x = x + flow_(z, a, task, beta, x, k) * dt[:, None] + return x + + +@torch.no_grad() +def tdflow_occupancy_target(flow_b, z_now, z_next, a_next, task, beta, rms, z0, + n_steps=8, sample_clip=0.0): + """One draw from (1 - beta) delta_{s'} + beta * psi_1(. | s', a'; theta_bar), as an ABSOLUTE latent. + + `z0` is the flow's source noise. Passing the SAME noise that the interpolation will use is the + coupled variant td-cfm(c) (eq. 7) -- the natural coupling the sampler hands us for free and a + strictly better estimator of the same loss; passing a fresh independent draw is plain td-cfm + (eq. 6). The caller decides, so this function is variant-agnostic. + + The Bernoulli(beta) coin IS the Bellman mixture: at beta = 0.95 roughly 95% of a batch takes the + bootstrap branch and 5% regresses onto the true one-step successor, which is the only term that + carries ground truth. That is the paper's regime and the reason a target network is needed. + + `nan_to_num` mirrors the eval-side read-outs: an early, untrained field can emit non-finite + velocities and ONE non-finite target would poison the whole batch's gradient. `sample_clip` + (train_rsm.py --sample-clip 10 on every deployed arm) additionally holds the bootstrap inside + the state box the z-scored features actually live in; the Monte-Carlo target is a REAL logged + frame and so is bounded by construction, and without this the TD target is the one term in the + loss that is not. + """ + boot = sample_future(flow_b, z_next, a_next, task, beta, rms, n_steps=n_steps, n=1, x0=z0) + boot = torch.nan_to_num(boot, nan=0.0, posinf=0.0, neginf=0.0) + if sample_clip > 0: + boot = boot.clamp(-sample_clip, sample_clip) + take_boot = torch.rand(beta.shape[0], device=beta.device) < beta + z_tgt = torch.where(take_boot[:, None], boot, z_next) + return z_tgt, take_boot + + +def _wbce(logit, target, w, pos_w): + """BCE-with-logits, optionally with PER-FRAME sample weights (gen_q #271 scheme C). + + w is None or all-ones -> exactly F.binary_cross_entropy_with_logits(..., pos_weight=pos_w), + bit-for-bit the pre-#271 loss. Otherwise the per-frame losses are averaged with weights + w (sum(w*l)/sum(w)), so the scale of the reward term -- and hence its balance against the + flow/inverse-dynamics terms -- does not move when w_neg is raised. + """ + if w is None: + return F.binary_cross_entropy_with_logits(logit, target, pos_weight=pos_w) + w = w.reshape(logit.shape) + l = F.binary_cross_entropy_with_logits(logit, target, pos_weight=pos_w, reduction="none") + return (l * w).sum() / w.sum().clamp_min(1e-8) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--d-z", type=int, default=256) + ap.add_argument("--enc-width", type=int, default=1024) + ap.add_argument("--flow-width", type=int, default=1024) + ap.add_argument("--flow-depth", type=int, default=4) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--k-success", type=int, default=10) + ap.add_argument("--stratify-success", type=int, default=0, + help="1: hold out the same FRACTION of rewarded and unrewarded episodes. An\n" + "unstratified 10%% split of real_cooking_v5 put 2 of its 50 rewarded\n" + "episodes in val, so a sparse reward label leaves ~80 positive val frames\n" + "and any sampled val AUC is noise (gen_q#261). Required for every new real\n" + "cell; left 0 by default so existing runs resume on their original split.") + ap.add_argument("--beta-lo", type=float, default=0.90) + ap.add_argument("--beta-hi", type=float, default=0.995) + ap.add_argument("--beta-q", type=float, default=0.98, help="query beta for diagnostics") + ap.add_argument("--eval-nnl1-k", type=int, default=0, + help="K>0: at every eval run the SUCCESSOR-FIT sanity check. For B anchor frames " + "draw K successors at the anchor's own training beta and report " + "min_j |z_sample - z_j|_1 / dim against (a) that trajectory's OWN FUTURE " + "(nnl1_in) and (b) a DIFFERENT trajectory (nnl1_cross, the control) and " + "(c) random pool frames scored against the own future (nnl1_rand, chance). " + "nnl1_ratio = in/cross: ~1 means the model learned the MARGINAL, not the " + "successor conditional. Also logs reward-head MAE/AUC on the same frames. " + "Candidates come from a fixed strided pool built once (--eval-nnl1-pool).") + ap.add_argument("--eval-nnl1-b", type=int, default=256, help="anchor frames per NN-L1 eval") + ap.add_argument("--eval-nnl1-pool", type=int, default=20000, + help="frames in the fixed strided candidate pool (kept on GPU, fp16)") + ap.add_argument("--eval-nnl1-m", type=int, default=128, + help="candidates compared per anchor per side (subsampled from the pool)") + ap.add_argument("--beta-trunc-eps", type=float, default=0.02, + help="data.py caps beta per anchor at eps**(1/L) (L = frames remaining) so the\n" + "truncated geometric leaves a CONSTANT eps tail and beta means one thing\n" + "(gen_q#262). Set eps >= beta_hi to DISABLE the cap (then beta_cap >= beta_hi\n" + "for every L) and recover the pre-fix behaviour -- the A/B control arm.") + ap.add_argument("--batch", type=int, default=512) + ap.add_argument("--steps", type=int, default=40000) + ap.add_argument("--warmup-reward", type=int, default=2000) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--ema", type=float, default=0.995) + ap.add_argument("--var-floor", type=float, default=0.1) + ap.add_argument("--w-reward", type=float, default=1.0) + ap.add_argument("--flow-steps", type=int, default=8) + ap.add_argument("--w-actcon", type=float, default=0.0, + help="action-contrastive weight. RECIPE.md applies this on Ant/cubes " + "and not on PointMaze: it is needed exactly when the successor " + "would otherwise ignore the action. Turn it on if the action gap " + "is flat, which is the COLLAPSE_ANALYSIS failure mode.") + ap.add_argument("--w-invdyn", type=float, default=0.0, + help="inverse-dynamics auxiliary on the encoder: predict the " + "action chunk from (z_t, z_t+k). Needed because the " + "visual latent barely reflects the action, so the " + "occupancy is nearly independent of it.") + ap.add_argument("--eval-every", type=int, default=2000) + 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-loss", default="mse", choices=["mse", "bce"], + help="reward-head loss for the subgoal/soft modes: mse (regression) " + "or bce (classifier; class-balanced for subgoal_ind)") + ap.add_argument("--save-every", type=int, default=0, + help="save ckpt_s.pt every N steps (checkpoint selection on validation inits)") + 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("--reward-npy", default="", + help="path to a float32 [n_frames] .npy of per-frame reward labels that " + "REPLACES --reward-mode entirely (rsm_rise #261 reward-head study)") + ap.add_argument("--action-augment", type=float, default=0.0, + help="RISE state-space kNN COUNTERFACTUAL ACTION AUGMENTATION (rsm_rise #279): " + "distance_threshold in the metric --augment-table was built in. 0 = OFF, and " + "with it off the sampler draws EXACTLY what it always did. See the block in " + "data.py for why the model needs counterfactual (s, a) pairs at all.") + ap.add_argument("--augment-mode", default="contrastive", choices=["contrastive", "invariant"], + help="contrastive = the counterfactual action carries the NEIGHBOUR's own future " + "(RISE's intent lifted to an occupancy model). invariant = the neighbour's " + "action is asserted to lead to the ANCHOR's future (the literal transcription " + "of next_obs = original next_obs); safe only if the neighbourhood is smaller " + "than the action gap the value must resolve.") + ap.add_argument("--augment-table", default="", + help="npz from scripts/real/build_aug_knn.py (rows/nbr_row/nbr_dist). Built ONCE, " + "uncapped by any threshold, so a whole threshold sweep reads one file. " + "Default: /aug_knn_feat.npz") + ap.add_argument("--augment-frac-cap", type=float, default=0.0, + help="upper bound on the AUGMENTED SHARE of each batch (0 = off = pure " + "proportional mixing). Proportional mixing is still the default -- RISE's " + "epoch%%2 alternation is the 457x-replay pathology -- but on this corpus the " + "k=15 pool is 15x the logged corpus, so proportional put 93%% of gradient " + "steps on counterfactual rows. This cap isolates aug_frac from the " + "relabelling as the explanatory variable (rsm_rise #279 run 5).") + ap.add_argument("--augment-neighbors", type=int, default=15, + help="RISE's num_neighbors: the cap is applied to the NEAREST different-episode " + "frames FIRST, then the threshold, exactly as RISE does it.") + ap.add_argument("--weight-npy", default="", + help="path to a float32 [n_frames] .npy of per-frame REWARD-LOSS sample " + "weights (gen_q #271 scheme C: w_neg on the S5/S6 hard negatives). " + "Affects the reward BCE only; unset = all ones = the old loss.") + ap.add_argument("--resume", type=int, default=1, + help="continue from /ckpt.pt if present. A 500k-step run " + "cannot fit one slurm window, so the run MUST be " + "restartable or the chain silently retrains from zero.") + ap.add_argument("--w-rrank", type=float, default=0.0, + help="weight on the READ-OUT RANKING loss (the port uses 2.0). " + "Ranks the success logit of a hop sampled under the REAL " + "action above one sampled under a shuffled action. This is " + "the action win rate we have only ever MEASURED; this term " + "optimises it. Hops are stop-grad, so it trains the reward " + "tower only and cannot corrupt the occupancy field. Distinct " + "from --w-actcon, which contrasts flow-matching ERRORS rather " + "than the success logits the Q read-out consumes.") + ap.add_argument("--rrank-tau", type=float, default=0.1) + ap.add_argument("--cache2", default="", help="second pack mixed into training batches (see below)") + ap.add_argument("--mix2", type=float, default=0.25, help="fraction of each training batch from --cache2") + ap.add_argument("--subgoal-dir2", default="", help="subgoal labels for --cache2") + ap.add_argument("--subgoal-dir", default="", + help="per-frame satisfied-subgoal labels from label_subgoals.py. " + "Required for --reward-mode subgoal, which is the only mode " + "whose target is a function of the state.") + ap.add_argument("--success-mask", default="", + help="admissibility mask from merge_verify.py. Logged successes " + "that do not reproduce in the eval environment are treated " + "as failures, so no reward is built for them.") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", ""), + help="W&B entity; '' (the default) disables W&B logging entirely. " + "rsm_rise sets RSM_WANDB_ENTITY=richardrl via its own wandb_env.sh; " + "nothing else changes, so other users of this script are unaffected.") + 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"]) + ap.add_argument("--wandb-id-salt", default="", + help="mixed into the run id (md5 of --out [+ salt]). A relaunch into the SAME --out after " + "deleting it would otherwise resume the old W&B run, whose step counter is ahead, " + "and W&B silently drops every log below that step.") + ap.add_argument("--log-every", type=int, default=100, + help="train-loss / grad-norm logging period (steps)") + ap.add_argument("--enc", default="mlp", choices=["mlp", "identity"], + help="identity: no learned encoder -- lat(x) = x (the z-scored cache feature, " + "d_z = feature dim), no EMA target, variance floor 0, reward warm-up 0. " + "For frozen foundation-model features modelled directly (rsm_rise DINO).") + ap.add_argument("--eval-minmse-n", type=int, default=0, + help="N>0: at every eval draw N futures per row (sample_future n=N) on a train " + "and a val batch of 2048 rows and log minmse_{train,val} = mean_rows min_i " + "|x'_i - x_{t+K}|^2/d in the latent the flow predicts in (identity: the " + "z-scored state), plus meanmse_* and staymse_* (x' = x_t). The fit criterion.") + ap.add_argument("--pca-dim", type=int, default=0, + help="k>0: fixed PCA map of the (z-scored) state to k dims, fitted on training frames " + "(model.PCAEncoder, stored in the checkpoint). Flow and reward head work in PCA " + "space; minmse is reported there AND mapped back to the full state (minmse_full_*).") + ap.add_argument("--pca-fit-frames", type=int, default=40000, help="training frames (strided) used to fit the PCA") + ap.add_argument("--flow-dropout", type=float, default=0.0, help="dropout inside the flow's residual blocks") + ap.add_argument("--flow-norm", type=int, default=0, + help="1: LayerNorm in the flow's residual blocks and before its output (model.OccFlow norm=True)") + ap.add_argument("--wd", type=float, default=0.01, help="AdamW weight decay (was hard-coded 0.01)") + ap.add_argument("--sample-clip", type=float, default=0.0, + help="clamp the sampled future latent to +-this in the diagnostics (0 = off). With " + "--enc identity the state itself is clip(+-z_clip), so clamping the sample to the " + "same box only removes off-manifold divergence of the Euler integration.") + ap.add_argument("--x-noise", type=float, default=0.0, + help="Gaussian noise (z-scored units) added to the CONDITIONING state x_now seen by " + "the flow and reward head during training (targets stay clean). Regulariser " + "against memorising episode identity: mug M generalised only within the " + "same-episode radius (NN dist 0.39) while other episodes sit at ~0.6, so val " + "velocities exploded (cfm_val 112 vs 0.95 train at step 5000). 0 = off.") + ap.add_argument("--flow-expectile", type=float, default=0.5, + help="expectile tau for the flow-matching (occupancy) loss. 0.5 = OFF and takes the " + "exact old code path (plain mean squared error on the velocity residual). With " + "tau > 0.5 the loss is 2*|tau - 1(u<0)|*u^2 with u = target - prediction, so " + "UNDER-prediction of the velocity toward the successor state is penalised more " + "than over-prediction: an optimistic successor/value estimate in the sense of " + "IQL-style expectile regression. tau < 0.5 is the pessimistic direction. The " + "factor 2 makes tau=0.5 numerically identical to the mse, so the tau knob does " + "not change the effective flow-loss weight.") + ap.add_argument("--append-proprio", type=int, default=0, + help="append normalised proprio to the LATENT, not just the " + "encoder input. Feeding it as 8 of 4104 input dims did " + "nothing: the encoder is trained by a reward loss that " + "does not depend on joint state, so it drops them. " + "Appending forces the successor to PREDICT the " + "action-sensitive channel (action-proprio |r| 0.98 vs " + "action-latent 0.49).") + # ---- TD-Flow occupancy target (gen_q#268) ---- + ap.add_argument("--occupancy-target", default="mc", choices=["mc", "td"], + help="mc (DEFAULT, unchanged): the occupancy target is the logged future " + "s_{t+k}, k ~ Geom(1-beta) truncated at the episode end -- Monte Carlo, no " + "bootstrap. td: the Bellman right-hand side sampled off an EMA target " + "field, (1-beta) delta_{s'} + beta psi_1(. | s', a'; theta_bar) " + "(Farebrother et al. 2025, arXiv:2503.09817). EVERYTHING else -- velocity " + "field, architecture, beta band and its per-anchor truncation cap, reward " + "head, chunking, optimiser, steps -- is identical, so an `mc` run and a " + "`td` run of the same cell differ in the occupancy target and nothing else.") + ap.add_argument("--tdflow-variant", default="td_c", choices=list(TDFLOW_VARIANTS), + help="td_c (DEFAULT) = Coupled TD-CFM, eq. 7: the interpolation source IS the " + "noise that generated the bootstrap sample. td = TD-CFM, eq. 6: a fresh " + "independent source. td2 = TD^2-CFM, eq. 8: the bootstrap term regresses " + "the live velocity onto the TARGET FIELD's velocity at a random interior " + "time along the target's own ODE path, so the loss FORM changes too.") + ap.add_argument("--tdflow-target", default="ema", choices=["ema", "live"], + help="which parameters the bootstrap reads. ema (DEFAULT): a target copy of " + "the flow, EMA-updated at --tdflow-tau, as Algorithm 1 requires. live: no " + "target network -- a diagnosis knob, not a reportable arm.") + ap.add_argument("--tdflow-tau", type=float, default=-1.0, + help="EMA rate of the target occupancy field; <0 means use --ema (0.995), the " + "same rate the encoder target already uses.") + ap.add_argument("--tdflow-mc-warmup", type=int, default=0, + help="force the (1-beta) one-step branch for the first N updates. OFF by " + "default: an arm that uses it is a HYBRID, not a clean TD-Flow baseline, " + "and any table row carrying it must say so.") + args = ap.parse_args() + + torch.manual_seed(args.seed); rng = np.random.default_rng(args.seed) + dev = "cuda" if torch.cuda.is_available() else "cpu" + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + + # ---- W&B (entity richardrl / project rsm_rise by default; resumable by run id) ---- + wb = None + if args.wandb_entity and args.wandb_mode != "disabled": + try: + import wandb, hashlib + _rid = hashlib.md5((str(out.resolve()) + args.wandb_id_salt).encode()).hexdigest()[:16] + wb = wandb.init(entity=args.wandb_entity, project=args.wandb_project, + name=args.wandb_name or out.name, id=_rid, resume="allow", + mode=args.wandb_mode, config=vars(args), dir=str(out)) + print(f"[rsm] wandb: {wb.url}", flush=True) + except Exception as e: # never let logging kill a run + print(f"[rsm] wandb disabled: {e}", flush=True) + wb = None + + # A W&B TRANSPORT ERROR MUST NEVER KILL A TRAINING RUN. Added 2026-09-24 (AUG_SUCC run 39): + # job 1900910 lost all four of its 100k cells at step ~35k when the wandb service process died + # during the cluster-wide outage and the bare wb.log() raised ConnectionResetError out of main(). + # The init above already had this intent ("never let logging kill a run"); the log sites did not. + _wb_on = [wb is not None] + + def _wb_log(payload, step): + if not _wb_on[0]: + return + try: + wb.log(payload, step=step) + except Exception as e: + _wb_on[0] = False + print(f"[rsm] wandb log FAILED ({type(e).__name__}: {e}); W&B off for the rest of this " + f"run, training continues", flush=True) + + def _flat(prefix, obj, acc): + """flatten nested dicts of floats for wandb.log""" + if isinstance(obj, dict): + for k, v in obj.items(): + _flat(f"{prefix}/{k}" if prefix else str(k), v, acc) + elif isinstance(obj, (int, float)): + acc[prefix] = float(obj) + return acc + + d = LiberoRSMData(args.cache, chunk=args.chunk, k_success=args.k_success, seed=args.seed, + stratify_success=bool(args.stratify_success), + success_gamma=args.success_gamma, + in_ram=bool(args.in_ram), reward_mode=args.reward_mode, + success_mask=args.success_mask, + reward_npy=args.reward_npy, + weight_npy=args.weight_npy, + action_augment=args.action_augment, + augment_mode=args.augment_mode, + augment_table=args.augment_table, + augment_neighbors=args.augment_neighbors, + augment_frac_cap=args.augment_frac_cap, + subgoal_dir=args.subgoal_dir) + if args.cache2: + # Second pack mixed into TRAINING batches only (validation stays on --cache so the + # history is comparable). Use: on-policy rollouts of the proposers the critic has to + # rank -- the base corpus is 99% pi0.5 rollouts, so the BC-demos policy's actions are + # off-support for a critic fit on it alone (proposer_bias_diag: Q nearly flat over + # demo-style chunks, 2x the spread over rollout-style chunks -> the arg-max over a + # mixed pool is a winner's curse, not a value judgement). + d2 = LiberoRSMData(args.cache2, chunk=args.chunk, k_success=args.k_success, seed=args.seed, + stratify_success=bool(args.stratify_success), + success_gamma=args.success_gamma, in_ram=bool(args.in_ram), + reward_mode=args.reward_mode, subgoal_dir=args.subgoal_dir2, + normalize=False) + d2.norm_mu, d2.norm_sd = d.norm_mu, d.norm_sd # ONE feature transform + assert d2.feat_dim == d.feat_dim and d2.n_task == d.n_task, "cache2 layout differs" + print(f"[rsm] cache2: {d2.n_ep} eps, positives={d2.r.mean():.4f}, mixed at {args.mix2:.2f} " + f"of every training batch", flush=True) + + class _Mix: + def __init__(self, a, b, p): self.a, self.b, self.p = a, b, p + def __getattr__(self, k): return getattr(self.a, k) + def sample(self, batch, rng, lo, hi, split="train", device="cuda", beta_trunc_eps=0.02, + with_next=False, augment=True): + if split != "train": + return self.a.sample(batch, rng, lo, hi, split, device, beta_trunc_eps, with_next, + augment) + nb = int(round(batch * self.p)); na = batch - nb + ba = self.a.sample(na, rng, lo, hi, split, device, beta_trunc_eps, with_next, augment) + bb = self.b.sample(nb, rng, lo, hi, split, device, beta_trunc_eps, with_next, augment) + out = {} + for k in ba: + if k not in bb: continue # one side augmented, the other not + if k == "aug_frac": # a scalar diagnostic, not a row field + out[k] = (na * ba[k] + nb * bb[k]) / max(batch, 1); continue + if torch.is_tensor(ba[k]): out[k] = torch.cat([ba[k], bb[k]], 0) + elif k == "aug_mask": out[k] = np.concatenate([ba[k], bb[k]]) + else: out[k] = np.concatenate([ba[k], bb[k] + (self.a.n_ep if k == "ep" else self.a.ep_to[-1])]) + return out + d = _Mix(d, d2, args.mix2) + print(f"[rsm] {d.n_ep} eps ({len(d.train_eps)} train / {len(d.val_eps)} val), " + f"{d.n_task} tasks, dim={d.feat_dim}, positives={d.r.mean():.4f}", flush=True) + + @torch.no_grad() + def minmse_eval(lat_fn, flow_, enc_, enc_t_, rms_, split, n_samp, rows=2048, chunk_rows=256): + """--eval-minmse-n: per-row min over N sampled futures of the per-dim MSE to the + real logged x_{t+K}, in the latent the flow predicts in (identity: z-scored state).""" + b = d.sample(rows, rng, args.beta_lo, args.beta_hi, split, dev, args.beta_trunc_eps, + augment=False) # the training gate must stay on LOGGED pairs (see data.py) + z_now = lat_fn(b["x_now"], enc_); z_fut = lat_fn(b["x_fut"], enc_t_) + back = getattr(enc_, "back", None) # PCA: map samples back to the full state space + mins, means, mins_f, means_f = [], [], [], [] + for i in range(0, rows, chunk_rows): + sl = slice(i, i + chunk_rows) + xs = sample_future(flow_, z_now[sl], b["a_now"][sl], b["task"][sl], b["beta"][sl], + rms_, args.flow_steps, n=n_samp) + if args.sample_clip > 0 and back is None: + xs = xs.clamp(-args.sample_clip, args.sample_clip) + err = (xs.view(-1, n_samp, xs.shape[-1]) - z_fut[sl][:, None]).pow(2).mean(-1) # [rows, N] + mins.append(err.min(1).values); means.append(err.mean(1)) + if back is not None: + xf = back(xs) + if args.sample_clip > 0: + xf = xf.clamp(-args.sample_clip, args.sample_clip) + errf = (xf.view(-1, n_samp, xf.shape[-1]) - b["x_fut"][sl][:, None]).pow(2).mean(-1) + mins_f.append(errf.min(1).values); means_f.append(errf.mean(1)) + out = {"minmse": float(torch.cat(mins).mean()), "meanmse": float(torch.cat(means).mean()), + "staymse": float((z_now - z_fut).pow(2).mean(-1).mean())} + if back is not None: # full 1545-d space, comparable with identity runs (includes the PCA reconstruction floor) + out.update({"minmse_full": float(torch.cat(mins_f).mean()), "meanmse_full": float(torch.cat(means_f).mean()), + "staymse_full": float((b["x_now"] - b["x_fut"]).pow(2).mean(-1).mean()), + "pcafloor_full": float((back(z_fut) - b["x_fut"]).pow(2).mean(-1).mean())}) + return out + + # ------------------------------------------------------------------ SUCCESSOR-FIT SANITY + # Does the flow actually fit the DINO features as a SUCCESSOR CONDITIONAL, or only as the + # corpus marginal? For B anchors we draw K successors at that anchor's own training beta and + # measure min_j |z_sample - z_j|_1 / dim over + # (a) the anchor trajectory's OWN FUTURE -> nnl1_in + # (b) one DIFFERENT trajectory -> nnl1_cross <-- the essential control + # (c) own future, but scoring RANDOM pool frames instead of samples -> nnl1_rand (chance) + # nnl1_ratio = nnl1_in / nnl1_cross. A model that learned the marginal scores the same against + # any trajectory, so ratio ~ 1. Candidates are a fixed strided pool built once and parked on + # the GPU in fp16, so each eval is a handful of batched cdist calls. + _nn = {"pool": None, "secs": 0.0} + + def _nnl1_build_pool(): + stride = max(1, int(d.ep_to[-1]) // max(args.eval_nnl1_pool, 1)) + # ALL episodes: a val anchor's own future lives in a val episode, so a train-only pool + # would leave every val anchor with no in-trajectory candidates. The pool is only ever + # read as NN candidates for a diagnostic, never trained on. + idx = np.concatenate([np.arange(int(d.ep_from[i]), int(d.ep_to[i]), stride, dtype=np.int64) + for i in range(d.n_ep)]) + ep_of = np.zeros(len(idx), np.int64) + for i in range(d.n_ep): + m = (idx >= d.ep_from[i]) & (idx < d.ep_to[i]) + ep_of[m] = i + with torch.no_grad(): + Z = [] + for j in range(0, len(idx), 2048): + Z.append(lat(torch.from_numpy(d._feat(idx[j:j + 2048])).to(dev), enc_t).half()) + Z = torch.cat(Z) + by_ep = {} + for i in np.unique(ep_of): + by_ep[int(i)] = np.nonzero(ep_of == i)[0] + print(f"[rsm] nnl1 pool: {len(idx)} frames (stride {stride}) from " + f"{len(by_ep)} episodes, {Z.numel()*2/1e6:.0f} MB fp16 on {dev}", flush=True) + # OPTIONAL per-frame segment id (rsm_rise real caches write seg.i16.npy). On the cooking + # corpus every episode is one ROUTE made of 1-2 SEGMENTS separated by an operator subgoal + # marker, and no route demonstrates the full 0->..->3->4 task: the 4-stage path only exists + # by stitching two episodes. Whether a successor sample can cross a segment boundary at all + # is therefore the composition question, so NN-L1 is split into "same segment" (easy) and + # "a LATER segment" (across the stitch boundary). + segf = None + try: + segf = np.load(Path(args.cache) / "seg.i16.npy") + if len(segf) != int(d.ep_to[-1]): + print(f"[rsm] seg.i16.npy length {len(segf)} != {int(d.ep_to[-1])}; ignored", flush=True) + segf = None + except Exception: + segf = None + eps_all = np.array(sorted(by_ep.keys()), np.int64) + tr = set(int(x) for x in d.train_eps) + return {"Z": Z, "t": idx, "ep": ep_of, "by_ep": by_ep, "eps": eps_all, + "seg": (segf[idx] if segf is not None else None), "segf": segf, + "eps_by_split": {"train": np.array([e for e in eps_all if int(e) in tr], np.int64), + "val": np.array([e for e in eps_all if int(e) not in tr], np.int64)}} + + @torch.no_grad() + def nnl1_eval(split="train"): + t_start = time.time() + if _nn["pool"] is None: + _nn["pool"] = _nnl1_build_pool() + P = _nn["pool"] + B, K, M = args.eval_nnl1_b, args.eval_nnl1_k, args.eval_nnl1_m + b = d.sample(B, rng, args.beta_lo, args.beta_hi, split, dev, args.beta_trunc_eps, + augment=False) # diagnostic: LOGGED pairs only, comparable to the R_M cell + z_now = lat(b["x_now"], enc) + t_np, ep_np = b["t_idx"], b["ep"] + # candidate index matrices: [B,M] into the pool + in_idx = np.zeros((B, M), np.int64); cr_idx = np.zeros((B, M), np.int64) + sg_idx = np.zeros((B, M), np.int64); nx_idx = np.zeros((B, M), np.int64) + sg_ok = np.zeros(B, bool); nx_ok = np.zeros(B, bool) + keep = np.zeros(B, bool) + for i in range(B): + e = int(ep_np[i]) + cand = P["by_ep"].get(e) + if cand is None: + continue + fut = cand[P["t"][cand] > int(t_np[i])] # strictly future, same trajectory + if len(fut) == 0: + continue + pool_eps = P["eps_by_split"].get(split, P["eps"]) + if len(pool_eps) < 2: + pool_eps = P["eps"] + others = pool_eps[pool_eps != e] + if len(others) == 0: + continue + oc = P["by_ep"][int(rng.choice(others))] # one DIFFERENT trajectory, all of it + in_idx[i] = rng.choice(fut, size=M, replace=len(fut) < M) + cr_idx[i] = rng.choice(oc, size=M, replace=len(oc) < M) + keep[i] = True + if P["seg"] is not None: + s_now = int(P["segf"][int(t_np[i])]) + same = fut[P["seg"][fut] == s_now] + later = fut[P["seg"][fut] > s_now] + if len(same): + sg_idx[i] = rng.choice(same, size=M, replace=len(same) < M); sg_ok[i] = True + if len(later): + nx_idx[i] = rng.choice(later, size=M, replace=len(later) < M); nx_ok[i] = True + if keep.sum() < 8: + _nn["secs"] += time.time() - t_start + return {} + kp = np.nonzero(keep)[0] + zk = z_now[torch.from_numpy(kp).to(dev)] + bk = {k: (v[torch.from_numpy(kp).to(dev)] if torch.is_tensor(v) else v[kp]) + for k, v in b.items() if torch.is_tensor(v) or np.ndim(v) > 0} # skip scalar diagnostics + nB = len(kp) + xs = sample_future(flow, zk, bk["a_now"], bk["task"], bk["beta"], rms, + args.flow_steps, n=K) + if args.sample_clip > 0: + xs = xs.clamp(-args.sample_clip, args.sample_clip) + dimf = xs.shape[-1] + xs = xs.view(nB, K, dimf).float() + rnd = P["Z"][torch.from_numpy(rng.choice(len(P["t"]), size=nB * K)).to(dev)] \ + .view(nB, K, dimf).float() + outs = {} + for tag, cidx, qry in (("in", in_idx[kp], xs), ("cross", cr_idx[kp], xs), + ("rand", in_idx[kp], rnd)): + acc = [] + for j in range(0, nB, 32): # chunk so cdist stays small + sl = slice(j, min(j + 32, nB)) + C = P["Z"][torch.from_numpy(cidx[sl]).to(dev)].float() # [c,M,dim] + acc.append(torch.cdist(qry[sl], C, p=1).div_(dimf).min(-1).values) # [c,K] + outs[f"nnl1_{tag}"] = float(torch.cat(acc).mean()) + # "STAY" reference, scored BOTH ways. sample_future returns z_now + rms*residual, so every + # sample is anchored at the anchor latent; that alone makes in < cross even for an untrained + # flow (verified: ratio 0.80 after 20 steps). The honest baseline is therefore the ratio the + # trivial "stay" predictor already achieves. The model has learned successor structure only + # if nnl1_ratio is materially BELOW nnl1_ratio_stay -- nnl1_ratio < 1 on its own proves + # nothing. + for tag, cidx in (("stay", in_idx[kp]), ("stay_cross", cr_idx[kp])): + acc = [] + for j in range(0, nB, 32): + sl = slice(j, min(j + 32, nB)) + C = P["Z"][torch.from_numpy(cidx[sl]).to(dev)].float() + acc.append(torch.cdist(zk[sl].float()[:, None], C, p=1).div_(dimf).min(-1).values) + outs[f"nnl1_{tag}"] = float(torch.cat(acc).mean()) + outs["nnl1_ratio"] = outs["nnl1_in"] / max(outs["nnl1_cross"], 1e-12) + outs["nnl1_ratio_stay"] = outs["nnl1_stay"] / max(outs["nnl1_stay_cross"], 1e-12) + outs["nnl1_ratio_vs_stay"] = outs["nnl1_ratio"] / max(outs["nnl1_ratio_stay"], 1e-12) + # within-segment vs across the subgoal (stitch) boundary + if P["seg"] is not None: + for tag, ok_all, cidx_all in (("sameseg", sg_ok, sg_idx), ("nextseg", nx_ok, nx_idx)): + sel = np.nonzero(ok_all[kp])[0] + if len(sel) < 8: + continue + acc = [] + for j in range(0, len(sel), 32): + ss = sel[j:j + 32] + C = P["Z"][torch.from_numpy(cidx_all[kp][ss]).to(dev)].float() + q = xs[torch.from_numpy(ss).to(dev)] + acc.append(torch.cdist(q, C, p=1).div_(dimf).min(-1).values) + outs[f"nnl1_{tag}"] = float(torch.cat(acc).mean()) + outs[f"nnl1_{tag}_n"] = int(len(sel)) + outs["nnl1_ratio_rand"] = outs["nnl1_in"] / max(outs["nnl1_rand"], 1e-12) + outs["nnl1_n_anchors"] = int(nB) + # ---- reward-head calibration on the SAME anchor frames ---- + pr = torch.sigmoid(rew(zk, bk["task"])).float().cpu().numpy().ravel() + lab = bk["r_now"].float().cpu().numpy().ravel() + outs["rhead_mae"] = float(np.abs(pr - lab).mean()) + outs["rhead_auc"] = auc(pr, lab) + outs["rhead_pos_rate"] = float((lab > 0.5).mean()) + outs["rhead_pred_mean"] = float(pr.mean()) + outs["rhead_pred_mean_pos"] = float(pr[lab > 0.5].mean()) if (lab > 0.5).any() else float("nan") + outs["rhead_pred_mean_neg"] = float(pr[lab <= 0.5].mean()) if (lab <= 0.5).any() else float("nan") + _nn["secs"] += time.time() - t_start + return outs + + d_act = args.chunk * d.adim + if args.pca_dim > 0: + args.enc = "pca" + if args.enc in ("identity", "pca"): + # The cache feature already carries proprio (data.py concatenates it), so appending + # it a second time would only duplicate 9 dims; the encoder-side knobs are no-ops. + if args.append_proprio: + print("[rsm] --enc identity: --append-proprio ignored (proprio is already in the feature)", flush=True) + args.append_proprio = 0 + if args.var_floor != 0 or args.warmup_reward != 0: + print(f"[rsm] --enc identity: forcing --var-floor 0 (was {args.var_floor}) and " + f"--warmup-reward 0 (was {args.warmup_reward})", flush=True) + args.var_floor = 0.0; args.warmup_reward = 0 + args.d_z = int(d.feat_dim) if args.enc == "identity" else int(args.pca_dim) + print(f"[rsm] --enc {args.enc}: latent = {'z-scored feature' if args.enc == 'identity' else 'fixed PCA of it'}, d_z={args.d_z}", flush=True) + n_pr = d.proprio.shape[1] if (args.append_proprio and d.proprio is not None) else 0 + pr_mu = pr_sd = None + if n_pr: + pr_s = np.asarray(d.proprio[::37], np.float32) + pr_mu = torch.tensor(pr_s.mean(0), device=dev) + pr_sd = torch.tensor(pr_s.std(0) + 1e-6, device=dev) + print(f"[rsm] appending {n_pr} proprio dims to the latent", flush=True) + d_lat = args.d_z + n_pr + if args.enc == "identity": + enc = IdentityEncoder(d.feat_dim).to(dev) + enc_t = enc # no parameters: target == online, EMA is a no-op + elif args.enc == "pca": + enc = PCAEncoder(d.feat_dim, args.pca_dim).to(dev) + _tr = np.concatenate([np.arange(d.ep_from[e], d.ep_to[e]) for e in d.train_eps]) + _tr = _tr[:: max(1, len(_tr) // args.pca_fit_frames)] + _evr = enc.fit(torch.from_numpy(d._feat(_tr)).to(dev)) + print(f"[rsm] PCA fitted on {len(_tr)} training frames: {args.pca_dim} dims explain " + f"{100*_evr:.1f}% of the variance", flush=True) + enc_t = enc # fixed map: no parameters, no EMA (resume reloads the stored map) + else: + enc = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) + enc_t = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) + enc_t.load_state_dict(enc.state_dict()) + for p in enc_t.parameters(): + p.requires_grad_(False) + rew = RewardHead(d_lat, d.n_task).to(dev) + flow = OccFlow(d_lat, d_act, d.n_task, width=args.flow_width, + depth=args.flow_depth, norm=bool(args.flow_norm), dropout=args.flow_dropout).to(dev) + # TD-Flow's theta_bar: the SAME module class and constructor arguments as the online field, so + # the only difference between the two is how their weights got there. Built only for + # --occupancy-target td, so the MC path allocates nothing extra and its step cost is unchanged. + flow_t, tdf_tau = None, (args.ema if args.tdflow_tau < 0 else args.tdflow_tau) + if args.occupancy_target == "td": + flow_t = OccFlow(d_lat, d_act, d.n_task, width=args.flow_width, + depth=args.flow_depth, norm=bool(args.flow_norm), + dropout=args.flow_dropout).to(dev) + flow_t.load_state_dict(flow.state_dict()) + for _p in flow_t.parameters(): + _p.requires_grad_(False) + flow_t.eval() # dropout/norm in inference mode: theta_bar is only ever sampled from + print(f"[rsm] OCCUPANCY TARGET = TD-Flow ({args.tdflow_variant}), target params " + f"{args.tdflow_target} (tau={tdf_tau}), flow_steps={args.flow_steps}, " + f"mc_warmup={args.tdflow_mc_warmup}", flush=True) + + def lat(x, enc_fn): + z = enc_fn(x) + if not n_pr: + return z + return torch.cat([z, (x[:, -n_pr:] - pr_mu) / pr_sd], -1) + invdyn = mlp([2 * d_lat, 1024, 1024, d_act], norm=True).to(dev) + _trainable = (list(enc.parameters()) + list(rew.parameters()) + + list(flow.parameters()) + list(invdyn.parameters())) + opt = torch.optim.AdamW(_trainable, lr=args.lr, weight_decay=args.wd) + + # running per-dimension RMS of the residual (the RECIPE normalisation) + rms = torch.ones(d_lat, device=dev) + hist = [] + best_win = -1.0 + t0 = time.time() + + start_step = 0 + _ck = out / "ckpt.pt" + if args.resume and _ck.exists(): + _c = torch.load(_ck, map_location=dev, weights_only=False) + enc.load_state_dict(_c["enc"]); enc_t.load_state_dict(_c["enc_t"]) + rew.load_state_dict(_c["rew"]); flow.load_state_dict(_c["flow"]) + if flow_t is not None: + # Without theta_bar a restart bootstraps off the ONLINE field for the first ~1/(1-tau) + # steps, which is the one configuration Algorithm 1 forbids. Older TD blobs (or an + # mc->td switch) have no flow_t; fall back to the online weights and say so. + if "flow_t" in _c: + flow_t.load_state_dict(_c["flow_t"]) + else: + flow_t.load_state_dict(flow.state_dict()) + print("[rsm] resume: checkpoint carries no flow_t; theta_bar reinitialised from " + "the online field", flush=True) + if "invdyn" in _c: + invdyn.load_state_dict(_c["invdyn"]) + if "opt" in _c: + opt.load_state_dict(_c["opt"]) + rms = _c["rms"].to(dev) + best_win = _c.get("best_win", -1.0) + hist = _c.get("hist", []) + start_step = int(_c["step"]) + # decorrelate the stream from the pre-restart draws + rng = np.random.default_rng(args.seed + 9973 * start_step) + print(f"[rsm] RESUMED at step {start_step}/{args.steps} " + f"(best action winrate {best_win:.3f})", flush=True) + if start_step >= args.steps: + print("[rsm] already complete; nothing to do", flush=True) + return + + # AUG_SUCC (gen_q#279): aug_frac goes to W&B, but a preempted+resumed run makes W&B DROP every + # scalar below the pre-restart high-water step ("steps must be monotonically increasing"), so the + # starvation curve the brief asks for develops holes exactly when the run gets preempted. Keep a + # running mean on the side and persist it into history.json, which is resume-proof. + _augf_sum, _augf_n = 0.0, 0 + + for step in range(start_step + 1, args.steps + 1): + # with_next = the TD path only: it adds s_{t+1} and the logged chunk there to the batch and + # draws NOTHING from `rng`, so the MC path's draws are bit-for-bit what they always were. + b = d.sample(args.batch, rng, args.beta_lo, args.beta_hi, "train", dev, args.beta_trunc_eps, + args.occupancy_target == "td") + z = lat(b["x_now"], enc) + with torch.no_grad(): + z_fut_t = lat(b["x_fut"], enc_t) + z_clean = z + if args.x_noise > 0: + # perturb what the networks CONDITION on; the residual target below is built from the + # clean state so the flow still integrates to real futures at sampling time + z = z + args.x_noise * torch.randn_like(z) + # ---- reward head (class-balanced: positives are ~0.5% of frames) ---- + logit = rew(z, b["task"]) + if args.reward_loss == "bce" and args.reward_mode in ("soft", "subgoal", "subgoal_ind"): + # CLASSIFIER head. subgoal / soft: BCE against the [0,1] target (unweighted -- + # the minimiser is still E[r|z], but the loss is the proper scoring rule for a + # probability and does not flatten near 0/1 the way the squared error does). + # subgoal_ind: class-balanced BCE on the goal indicator, i.e. a goal + # classifier with positives up-weighted to the base rate. + if args.reward_mode == "subgoal_ind": + pos_w = torch.tensor(max((1 - d.r.mean()) / max(d.r.mean(), 1e-6), 1.0), + device=dev) + l_rew = _wbce(logit, b["r_now"], b.get("w_now"), pos_w) + else: + l_rew = _wbce(logit, b["r_now"], b.get("w_now"), None) + elif args.reward_mode in ("soft", "subgoal", "subgoal_ind"): + # Continuous per-state target in [0,1] -> REGRESS it. Class-balanced BCE + # would be wrong twice over: the base rate no longer means anything on a + # continuous target, and weighted BCE on a soft target t converges to + # w*t/(w*t + 1 - t), not t. The occupancy identity needs the read-out to + # be E[r|z] on the nose, so a monotone-but-biased head re-introduces + # exactly the type error this reward mode exists to remove. + l_rew = (torch.sigmoid(logit) - b["r_now"]).pow(2).mean() + else: + pos_w = torch.tensor(max((1 - d.r.mean()) / max(d.r.mean(), 1e-6), 1.0), + device=dev) + l_rew = _wbce(logit, b["r_now"], b.get("w_now"), pos_w) + + # ---- inverse dynamics: force ACTION information into the latent ---- + # Root cause of the flat/inverted action gap. This lane already measured + # that over 5 frames the executed action correlates with the proprio delta + # at |r| up to 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-frame chunk produces. The encoder is then trained on reward alone, so + # nothing stops it discarding what little action signal survives, and + # p(z'|z,A) ends up almost independent of A -- a value that ranks states + # but not actions, which is exactly what every critic here showed + # (win rate 0.52-0.57, decaying below chance). + # Predicting the action chunk from (z_t, z_t+k) makes the latent keep it. + l_inv = torch.zeros((), device=dev) + if args.w_invdyn > 0: + z_fut_live = lat(b["x_fut"], enc) # grad flows into the encoder + l_inv = (invdyn(torch.cat([z, z_fut_live], -1)) + - b["a_now"]).pow(2).mean() + + # ---- occupancy: flow-match the NORMALISED residual ---- + # OCCUPANCY TARGET (gen_q#268). `mc` (the default) keeps the Monte-Carlo future s_{t+k}; + # `td` replaces it with a draw from the Bellman right-hand side off theta_bar. The MC + # branch is the original code, unmoved, and consumes the identical RNG stream: only the TD + # branch draws anything extra, and it draws k/noise EARLY because the coupled variant needs + # the interpolation source to be the bootstrap's source. + z_tgt, td_diag = z_fut_t, {} + if args.occupancy_target == "td": + z_next_t = lat(b["x_next"], enc_t).detach() + flow_b = flow_t if args.tdflow_target == "ema" else flow + k = torch.rand(args.batch, device=dev) + noise = torch.randn(args.batch, d_lat, device=dev) + z0 = noise if args.tdflow_variant in ("td_c", "td2") else \ + torch.randn(args.batch, d_lat, device=dev) + if args.tdflow_variant == "td2": + # eq. 8 keeps the (1-beta) branch as ordinary CFM onto the TRUE one-step successor + # and replaces the bootstrap branch with velocity matching against theta_bar, so + # here the target is s' and the second term enters the loss below. + z_tgt = z_next_t + else: + z_tgt, _take = tdflow_occupancy_target( + flow_b, z_clean.detach(), z_next_t, b["a_next"], b["task"], b["beta"], rms, z0, + n_steps=args.flow_steps, sample_clip=args.sample_clip) + if step <= args.tdflow_mc_warmup: + z_tgt = z_next_t # hybrid warm-up: one-step branch only + td_diag["boot_frac"] = float(_take.float().mean()) + # The MC-vs-TD gap, measured per step on the same anchors: how far the bootstrapped + # target sits from the logged future that the MC arm would have regressed onto. + td_diag["tgt_mse_vs_mc"] = float((z_tgt - z_fut_t).pow(2).mean()) + td_diag["tgt_absmax"] = float(z_tgt.abs().max()) + # The reference for tgt_mse_vs_mc is NOT zero: the occupancy is a distribution, so a + # correct bootstrap is an independent draw and differs from the MC draw by the + # distribution's own spread (scripts/mc_target_spread.py measures it: 0.55-0.69 on these + # caches, and a converged MC model's own sample sits at 1.27x it). These two make the + # failure mode of the ratio readable per step: over-dispersion shows up as tgt_std + # climbing away from mc_std. + td_diag["tgt_std"] = float(z_tgt.std()) + td_diag["mc_std"] = float(z_fut_t.std()) + delta = (z_tgt - z_clean.detach()) if step <= args.warmup_reward else (z_tgt - z_clean) + # RMS IS A PROPERTY OF THE DATA, NOT OF THE TARGET (gen_q#268, fixed 2026-09-21 08:5x UTC). + # `rms` is the per-dimension scale the flow's data space is expressed in: the field predicts + # the velocity of (z_fut - z_now)/rms, and sample_future multiplies its output back by rms. + # Fitting it on the TD target therefore closes a loop -- a slightly over-dispersed bootstrap + # raises rms, which scales the next bootstrap up, which raises rms again -- with no fixed + # point short of the --sample-clip box. Measured on the first TD runs + # (scripts/tdflow_target_diag.py, status/tdflow/target_diag.json): rms drifted 0.88 (the MC + # twin's converged value) -> 1.66 at step 15000 on one task and -> 3.21 on another, and the + # TD target's std reached 3.09 against the Monte-Carlo target's 1.01, i.e. 15x the MSE two + # independent MC draws differ by. The clamp was NOT binding (clip_frac 0.004), so this was + # divergence, not saturation. + # The MC future is drawn on the TD path anyway (for the td_tgt_mse_vs_mc diagnostic), so the + # normaliser can be fitted on the REAL logged residual on both paths -- which is also what + # "same residual / horizon normalisers" in the TDFlowAgent contract requires. On the MC path + # rms_src IS delta, so this is a no-op there. + rms_src = delta if args.occupancy_target == "mc" else (z_fut_t - z_clean).detach() + with torch.no_grad(): + cur = rms_src.pow(2).mean(0).sqrt().clamp_min(1e-3) + rms.mul_(0.99).add_(cur, alpha=0.01) + y = delta / rms + if args.occupancy_target == "mc": + k = torch.rand(args.batch, device=dev) + noise = torch.randn_like(y) + x_k = (1 - k)[:, None] * y + k[:, None] * noise + v = flow(z if step > args.warmup_reward else z.detach(), + b["a_now"], b["task"], b["beta"], x_k, k) + if args.occupancy_target == "td" and args.tdflow_variant == "td2": + # ell_td2 = (1-beta) || v_theta(X_t | s,a) - (Delta - X0) ||^2 + # + beta || v_theta(Xc_t | s,a) - v_thetabar(Xc'_t | s', a') ||^2 + # with Xc'_t = psi_tau(X0 | s', a'; theta_bar) the target's own path stopped at a random + # tau, and Xc_t the same point expressed in THIS state's flow frame (a translation by + # (z' - z)/rms, see the frame note on tdflow_occupancy_target). The weights are the + # per-row Bellman mixture, not a batch mean, so a low-beta row still regresses mostly + # on ground truth. --flow-expectile does not apply to this variant: the loss form + # itself is the paper's, and an asymmetric weight on top of it would be a third method. + _u_row = (v - (y - noise)).pow(2).mean(-1) + tau_t = torch.rand(args.batch, device=dev) + with torch.no_grad(): + xc_p = _euler_to_tau(flow_b, z_next_t, b["a_next"], b["task"], b["beta"], + noise, tau_t, args.flow_steps) + xc_p = torch.nan_to_num(xc_p, nan=0.0, posinf=0.0, neginf=0.0) + v_tgt = torch.nan_to_num( + flow_b(z_next_t, b["a_next"], b["task"], b["beta"], xc_p, 1.0 - tau_t), + nan=0.0, posinf=0.0, neginf=0.0) + xc = xc_p + (z_next_t - z_clean.detach()) / rms + v_live = flow(z if step > args.warmup_reward else z.detach(), + b["a_now"], b["task"], b["beta"], xc, 1.0 - tau_t) + l_cfm = ((1.0 - b["beta"]) * _u_row + + b["beta"] * (v_live - v_tgt).pow(2).mean(-1)).mean() + elif args.flow_expectile == 0.5: + l_cfm = (v - (y - noise)).pow(2).mean() + else: + # expectile regression on the velocity residual (u = target - prediction); + # tau > 0.5 up-weights u > 0, i.e. the model predicting too little motion. + _tau = args.flow_expectile + _u = (y - noise) - v + _w = torch.where(_u >= 0, _tau, 1.0 - _tau) + l_cfm = (2.0 * _w * _u.pow(2)).mean() + + # Action-contrastive: the velocity conditioned on the TRUE chunk must + # explain the true target better than one conditioned on another chunk + # from the batch. Without this the successor can ignore A entirely, which + # yields a value that ranks states but not actions. + l_ac = torch.zeros((), device=dev) + if args.w_actcon > 0: + u = y - noise + perm = torch.randperm(args.batch, device=dev) + v_neg = flow(z if step > args.warmup_reward else z.detach(), + b["a_now"][perm], b["task"], b["beta"], x_k, k) + e_pos = (v - u).pow(2).mean(-1) + e_neg = (v_neg - u).pow(2).mean(-1) + l_ac = F.softplus(e_pos - e_neg).mean() + + # ---- variance floor: stops the latent collapsing under the EMA target ---- + std = z.std(0) + l_var = F.relu(args.var_floor - std).mean() + + # ---- read-out ranking on sampled hops (port: reward_rank_weight=2.0) ---- + l_rr = torch.zeros((), device=dev) + if args.w_rrank > 0: + with torch.no_grad(): + perm = torch.randperm(b["a"].shape[0], device=dev) + a_shuf = b["a"][perm] + hop_d = sample_future(flow, z.detach(), b["a"], b["task"], + b["beta"], rms, args.flow_steps, n=1) + hop_r = sample_future(flow, z.detach(), a_shuf, b["task"], + b["beta"], rms, args.flow_steps, n=1) + logit_d = rew(hop_d, b["task"]) + logit_r = rew(hop_r, b["task"]) + l_rr = -F.logsigmoid((logit_d - logit_r) / max(args.rrank_tau, 1e-6)).mean() + + loss = (args.w_reward * l_rew + l_cfm + 10.0 * l_var + + args.w_actcon * l_ac + args.w_invdyn * l_inv + + args.w_rrank * l_rr) + opt.zero_grad(); loss.backward() + # total grad norm BEFORE clipping (clip_grad_norm_ returns it), plus per-module norms + gn_total = float(torch.nn.utils.clip_grad_norm_(_trainable, 1.0)) + opt.step() + ema_update(enc_t, enc, args.ema) + if flow_t is not None: + # theta_bar <- tau theta_bar + (1-tau) theta, the same rule and the same rate the + # encoder target uses. Stepped AFTER opt.step() so theta_bar always lags the online + # field by exactly one update, as Algorithm 1 has it. + ema_update(flow_t, flow, tdf_tau) + + if args.action_augment > 0: + _augf_sum += float(b.get("aug_frac", 0.0)); _augf_n += 1 + if step % 500 == 0: + print(f"[rsm] {step} rew={float(l_rew):.4f} cfm={float(l_cfm):.4f} " + f"ac={float(l_ac):.4f} gradnorm={gn_total:.3f} " + f"std_min={float(std.min()):.3f} ({step/(time.time()-t0):.1f} it/s)" + + (f" aug={float(b.get('aug_frac', 0.0)):.3f}" if args.action_augment > 0 else "") + + ("".join(f" td_{_k}={_v:.4g}" for _k, _v in td_diag.items()) if td_diag else ""), + flush=True) + if wb is not None and (step % args.log_every == 0 or step == 1): + def _mod_gn(m): + sq = [p.grad.detach().float().pow(2).sum() for p in m.parameters() if p.grad is not None] + return float(torch.stack(sq).sum().sqrt()) if sq else 0.0 + _log = {"train/loss": float(loss), "train/l_rew": float(l_rew), + "train/l_cfm": float(l_cfm), "train/l_var": float(l_var), + "train/l_actcon": float(l_ac), "train/l_invdyn": float(l_inv), + "train/l_rrank": float(l_rr), + "train/gradnorm": gn_total, "train/gradnorm_clipped": min(gn_total, 1.0), + "train/gradnorm_enc": _mod_gn(enc), "train/gradnorm_rew": _mod_gn(rew), + "train/gradnorm_flow": _mod_gn(flow), + # THE STARVATION CHECK. A threshold that admits almost no pairs is visible in + # this curve from step 1 rather than discovered after the run. + "train/aug_frac": float(b.get("aug_frac", 0.0)), + "train/latent_std_min": float(std.min()), "train/rms_mean": float(rms.mean()), + "train/lr": opt.param_groups[0]["lr"], + "train/it_per_s": step / max(time.time() - t0, 1e-6)} + # TD-Flow diagnostics; empty dict (and so no extra keys) on the MC path. + _log.update({f"train/td_{_k}": _v for _k, _v in td_diag.items()}) + _wb_log(_log, step) + + if step % args.eval_every == 0 or step == args.steps: + enc.eval(); rew.eval(); flow.eval() + with torch.no_grad(): + vb = d.sample(2048, rng, args.beta_lo, args.beta_hi, "val", dev, args.beta_trunc_eps) + zv = lat(vb["x_now"], enc) + r_auc = auc(rew(zv, vb["task"]).cpu().numpy(), vb["r_now"].cpu().numpy()) + zf = lat(vb["x_fut"], enc_t) + yv = (zf - zv) / rms + kv = torch.rand(2048, device=dev); nv = torch.randn_like(yv) + xk = (1 - kv)[:, None] * yv + kv[:, None] * nv + cfm_v = float((flow(zv, vb["a_now"], vb["task"], vb["beta"], xk, kv) + - (yv - nv)).pow(2).mean()) + + # ---- headline: does Q RANK ACTIONS at a fixed state? ---- + fb = d.sample_frames(1024, rng, "val", dev) + zq = lat(fb["x"], enc) + beta_q = torch.full((1024,), args.beta_q, device=dev) + # WITHIN-TASK permutation: a cross-task chunk is off-support, and + # once the successor is action-conditioned the frozen reward head + # scores off-manifold latents arbitrarily. Comparing against it + # measures support violation rather than action quality. + tkp = fb["task"].cpu().numpy() + pw = np.arange(1024) + for _ti in np.unique(tkp): + _ix = np.nonzero(tkp == _ti)[0] + if len(_ix) > 1: + pw[_ix] = rng.permutation(_ix) + perm = torch.from_numpy(pw).to(dev) + def q_of(a_chunk): + zp = sample_future(flow, zq, a_chunk, fb["task"], beta_q, rms, + args.flow_steps, n=4) + if args.sample_clip > 0: + zp = zp.clamp(-args.sample_clip, args.sample_clip) + p = torch.sigmoid(rew(zp, fb["task"].repeat_interleave(4, 0))) + return p.view(1024, 4).mean(1) + q_log = q_of(fb["a"]) + q_for = q_of(fb["a"][perm]) + gap = float((q_log - q_for).mean()) + gap_win = float((q_log > q_for).float().mean()) + q_succ_auc = auc(q_log.cpu().numpy(), fb["succ"].cpu().numpy()) + + # ---- does the read-out actually ESTIMATE Qbar? ---- + # Qbar(s,a) = E_{z'~d_beta(.|s,a)}[r(z')] = E_{k~Geom(1-beta)}[r(s_{t+k})]. + # With a per-state reward the right-hand side is computable directly + # from the logged trajectory (final frame absorbing), so this is a + # ground-truth check of the identity rather than a proxy. It is only + # meaningful when r IS a function of the state: under reward-mode=soft + # the target is a return and no state-indexed RHS exists. + tk_np = fb["task"].cpu().numpy() + _ep = fb["ep"]; _t = fb["t_idx"] + _kk = rng.geometric(1.0 - args.beta_q, size=(256, len(_ep))) - 1 + _ix = np.minimum(_t[None, :] + _kk, d.ep_to[_ep][None, :] - 1) + q_mc = d.r[_ix].mean(0) + _qh = q_log.cpu().numpy() + identity = { + "q_mc_mean": float(q_mc.mean()), + "q_hat_mean": float(_qh.mean()), + "mse": float(((_qh - q_mc) ** 2).mean()), + "corr": float(np.corrcoef(_qh, q_mc)[0, 1]) if _qh.std() > 1e-8 else 0.0, + "spearman": float(np.corrcoef( + np.argsort(np.argsort(_qh)), np.argsort(np.argsort(q_mc)))[0, 1]), + # a read-out that ignored the state would match the mean but + # carry no correlation; this is the null it has to beat + "mse_const": float(((q_mc.mean() - q_mc) ** 2).mean()), + } + # Pooled corr is dominated by TASK identity: mean subgoal fraction + # ranges 0.00 (task 5) to 0.41 (task 8) across tasks, so a read-out + # that only knew which task it was looking at already scores ~0.45. + # Within-task is the number that says the read-out tracks the state. + _wt = [] + for _ti in np.unique(tk_np): + _m = tk_np == _ti + if _m.sum() < 32 or _qh[_m].std() < 1e-8 or q_mc[_m].std() < 1e-8: + continue + _wt.append(float(np.corrcoef(_qh[_m], q_mc[_m])[0, 1])) + identity["corr_within_task"] = float(np.mean(_wt)) if _wt else 0.0 + identity["n_tasks_scored"] = len(_wt) + + # per-task breakdown: success rates in this corpus span 0.000 + # (STUDY_SCENE1, 0/2962 rollouts) to 0.957, so a pooled number + # hides which tasks the critic actually works on. + gl = (q_log - q_for).cpu().numpy() + ql = q_log.cpu().numpy(); sc = fb["succ"].cpu().numpy() + # Time-to-end buckets. At beta=0.98 a depth-2 read covers ~75 + # frames, so the value can only be informative near the end of an + # episode; this shows where the action signal actually lives + # instead of averaging it away. + te = fb["to_end"].cpu().numpy() + by_horizon = {} + for name, lo_, hi_ in (("0-50", 0, 50), ("50-100", 50, 100), + ("100-200", 100, 200), ("200+", 200, 1e9)): + m = (te >= lo_) & (te < hi_) + if m.sum() < 16: + continue + by_horizon[name] = {"n": int(m.sum()), + "action_gap": float(gl[m].mean()), + "action_winrate": float((gl[m] > 0).mean()), + "q_mean": float(ql[m].mean())} + + per_task = {} + for ti in np.unique(tk_np): + m = tk_np == ti + per_task[int(ti)] = {"n": int(m.sum()), + "action_gap": float(gl[m].mean()), + "success_auc": auc(ql[m], sc[m]), + "succ_rate": float(sc[m].mean())} + mm = {} + if args.eval_nnl1_k > 0: + for _sp in ("train", "val"): + for _k, _v in nnl1_eval(_sp).items(): + mm[f"{_k}_{_sp}"] = _v + mm["nnl1_secs_total"] = _nn["secs"] + mm["nnl1_frac_walltime"] = _nn["secs"] / max(time.time() - t0, 1e-9) + if args.eval_minmse_n > 0: + for _sp in ("train", "val"): + _r = minmse_eval(lat, flow, enc, enc_t, rms, _sp, args.eval_minmse_n) + for _k, _v in _r.items(): + mm[f"{_k}_{_sp}"] = _v + enc.train(); rew.train(); flow.train() + + rec = {"step": step, "reward_auc": r_auc, "cfm_val": cfm_v, + "per_task": per_task, "by_horizon": by_horizon, + "latent_std_min": float(std.min().detach()), + "q_action_gap": gap, "q_action_winrate": gap_win, + "q_success_auc": q_succ_auc, "q_mean": float(q_log.mean()), + "identity": identity, **mm} + if args.action_augment > 0: + # mean realised augmented fraction over the steps since the last eval + rec["aug_frac"] = _augf_sum / max(_augf_n, 1) + _augf_sum, _augf_n = 0.0, 0 + hist.append(rec) + if "nnl1_in_train" in mm and "nnl1_in_val" in mm: + print(f"[rsm] NNL1(K={args.eval_nnl1_k},B={mm['nnl1_n_anchors_train']}) " + f"train in={mm['nnl1_in_train']:.4f} cross={mm['nnl1_cross_train']:.4f} " + f"rand={mm['nnl1_rand_train']:.4f} stay={mm['nnl1_stay_train']:.4f} " + f"ratio(in/cross)={mm['nnl1_ratio_train']:.3f} " + f"stay_ratio={mm['nnl1_ratio_stay_train']:.3f} " + f"vs_stay={mm['nnl1_ratio_vs_stay_train']:.3f} | " + f"val in={mm['nnl1_in_val']:.4f} cross={mm['nnl1_cross_val']:.4f} " + f"ratio={mm['nnl1_ratio_val']:.3f}", flush=True) + if "nnl1_sameseg_train" in mm or "nnl1_nextseg_train" in mm: + print(f"[rsm] NNL1-SEG train sameseg=" + f"{mm.get('nnl1_sameseg_train', float('nan')):.4f} " + f"(n={mm.get('nnl1_sameseg_n_train', 0)}) nextseg=" + f"{mm.get('nnl1_nextseg_train', float('nan')):.4f} " + f"(n={mm.get('nnl1_nextseg_n_train', 0)}) " + f"[nextseg >> sameseg => one hop cannot cross a subgoal boundary]", + flush=True) + print(f"[rsm] RHEAD train mae={mm['rhead_mae_train']:.4f} " + f"auc={mm['rhead_auc_train']:.4f} pos={mm['rhead_pos_rate_train']:.3f} " + f"pred(pos/neg)={mm['rhead_pred_mean_pos_train']:.3f}/" + f"{mm['rhead_pred_mean_neg_train']:.3f} | val mae={mm['rhead_mae_val']:.4f} " + f"auc={mm['rhead_auc_val']:.4f} || hook cost " + f"{mm['nnl1_frac_walltime']*100:.3f}% of wall time " + f"({mm['nnl1_secs_total']:.1f}s)", flush=True) + if mm: + print(f"[rsm] MINMSE(n={args.eval_minmse_n}) train={mm['minmse_train']:.4f} " + f"val={mm['minmse_val']:.4f} | mean train={mm['meanmse_train']:.4f} " + f"val={mm['meanmse_val']:.4f} | stay train={mm['staymse_train']:.4f} " + f"val={mm['staymse_val']:.4f}", flush=True) + if "minmse_full_train" in mm: + print(f"[rsm] MINMSE_FULL(1545-d) train={mm['minmse_full_train']:.4f} val={mm['minmse_full_val']:.4f} " + f"| mean train={mm['meanmse_full_train']:.4f} val={mm['meanmse_full_val']:.4f} " + f"| stay train={mm['staymse_full_train']:.4f} val={mm['staymse_full_val']:.4f} " + f"| pca floor train={mm['pcafloor_full_train']:.4f} val={mm['pcafloor_full_val']:.4f}", flush=True) + if wb is not None: + _wb_log(_flat("eval", {k: v for k, v in rec.items() if k != "step"}, {}), step) + print(f"[rsm] EVAL {step}: reward_auc={r_auc:.4f} cfm={cfm_v:.4f} " + f"ACTION gap={gap:+.5f} win={gap_win:.3f} | state auc={q_succ_auc:.4f}", + flush=True) + print(f"[rsm] IDENTITY Qbar: corr={identity['corr']:.3f} " + f"spearman={identity['spearman']:.3f} mse={identity['mse']:.5f} " + f"within-task={identity['corr_within_task']:.3f} " + f"(const-null mse {identity['mse_const']:.5f}) " + f"qhat={identity['q_hat_mean']:.4f} vs mc={identity['q_mc_mean']:.4f}", + flush=True) + print("[rsm] by time-to-end: " + " ".join( + f"{k}:gap={v['action_gap']:+.5f}/win={v['action_winrate']:.2f}(n={v['n']})" + for k, v in by_horizon.items()), flush=True) + (out / "history.json").write_text(json.dumps(hist, indent=1)) + blob = {"cam_res": getattr(d, "cam_res", "UNKNOWN"), + "encoder": getattr(d, "encoder", "pi05_base_pytorch"), + "enc": enc.state_dict(), "enc_t": enc_t.state_dict(), + "rew": rew.state_dict(), "flow": flow.state_dict(), + # theta_bar: resume-only. Every read-out (is_ope.load_critic, rsm_scorer) reads + # "flow", so a TD blob loads and scores exactly like an MC blob of the same cell. + **({"flow_t": flow_t.state_dict()} if flow_t is not None else {}), + "rms": rms.cpu(), "config": vars(args), "n_pr": n_pr, + "tasks": d.tasks, "d_act": d_act, "step": step, + "q_action_winrate": gap_win, + # is_ope.load_critic reads these: identity checkpoints carry no encoder + # weights, so the feature width has to be recorded explicitly. + "enc_kind": args.enc, "d_in": int(d.feat_dim), "d_lat": int(d_lat)} + # resume state: without the optimiser moments a restart restarts Adam + # cold and undoes progress, and without best_win the chain forgets + # which checkpoint was the best ranker. + blob_r = dict(blob) + blob_r["opt"] = opt.state_dict() + blob_r["invdyn"] = invdyn.state_dict() + blob_r["best_win"] = max(best_win, gap_win) + blob_r["hist"] = hist + # 2026-09-22: the RESUME blob is ~3x the size of the scoring blob (it carries the AdamW + # moments) and it is written FIRST, so on a full/flaky filesystem its failure used to take + # the whole run down BEFORE the small scoring checkpoint was written -- 5000 good steps + # thrown away for a write error (observed on ess6000-1 at 348.6T/350T: "unexpected pos + # 30895936 vs 30895824"). Resume state is a convenience; the scoring checkpoint is the + # product. So: warn and carry on, and leave the previous ckpt.pt in place (the partial + # write goes to .tmp and is removed, so resume falls back to the last good blob). + _tmp = out / "ckpt.pt.tmp" + try: + torch.save(blob_r, _tmp) + _os.replace(_tmp, out / "ckpt.pt") # atomic: a kill mid-write is safe + except Exception as e: # noqa: BLE001 + print(f"[rsm] WARNING: resume checkpoint not written at step {step}: " + f"{type(e).__name__}: {e} -- training continues, resume falls back to the " + f"previous ckpt.pt", flush=True) + try: + _tmp.unlink() + except OSError: + pass + if args.save_every and step % args.save_every == 0: + try: + torch.save(blob, out / f"ckpt_s{step}.pt") # for validation-set selection + except Exception as e: # noqa: BLE001 + print(f"[rsm] WARNING: ckpt_s{step}.pt not written: {type(e).__name__}: {e}", + flush=True) + # Keep the checkpoint that best RANKS ACTIONS, not the last one. The + # critic exists to supply an advantage, and action ranking is not + # monotone in training: this run peaked at win 0.615 / gap +0.103 at + # step 14000 and decayed to 0.516 / +0.023 by 20000 as off-support + # optimism crept back, so keeping the last checkpoint throws away the + # only thing AWR consumes. Selection is on the held-out split. + # A checkpoint is eligible as BEST only if the occupancy is still healthy. + # qsg_r (subset, 2026-09-13) oscillated 0.22-0.93 in cfm_val, spiked to + # 3.7 at 120k and 38.3 at 130k -- and was selected as best at 130k because + # action win-rate happened to peak on the diverging flow. Ranking by a + # diverging occupancy is not the method. + _cf = [h["cfm_val"] for h in hist[:-1] if "cfm_val" in h] + _healthy = (len(_cf) < 3) or (cfm_v <= 2.0 * float(np.median(_cf))) + if not _healthy: + print(f"[rsm] cfm_val {cfm_v:.3f} > 2x running median " + f"{float(np.median(_cf)):.3f}: occupancy unstable, NOT eligible as best", + flush=True) + if gap_win > best_win and _healthy: + best_win = gap_win + torch.save(blob, out / "ckpt_best.pt") + print(f"[rsm] new BEST action winrate {gap_win:.3f} " + f"(gap {gap:+.5f}) at step {step}", flush=True) + print("[rsm] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/train_rsm_dwm.py b/frozen/rsm_libero_freeze_20261002/train_rsm_dwm.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd50da63f76cc8fb3e5eb04adf1e1bbc8f1f19b --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/train_rsm_dwm.py @@ -0,0 +1,765 @@ +"""DWM successor-model trainer: DINO-WM's ViT predictor, trained by conditional flow matching +to output beta-discounted successors in DINOv2 token space (LAUNCH_MATRIX rev. 4, Stage 1). + +Interface-compatible with train_rsm.py: same flags where they exist, same console prints, +same history.json keys (plus the min-MSE fit criterion), same W&B convention, same +ckpt.pt / ckpt_best.pt / ckpt_s.pt files. Multi-GPU by torchrun (DDP, one node): + + torchrun --standalone --nproc_per_node 8 train_rsm_dwm.py --cache cache/ \ + --out runs//rsm/DWM --batch 4096 --steps 100000 ... + +Run without torchrun for a single process. The token cache is memory-mapped, so the 8 +ranks share one page-cache copy of tok.f16.npy. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, copy, datetime, json, queue, threading, time +from pathlib import Path +import numpy as np +import torch +import torch.distributed as dist +import torch.nn.functional as F + +from model import ema_update +from train_rsm import auc +from dwm_model import (DWM, DWMReward, Normalizer, TokenRSMData, sample_future_dwm, + N_TOK, D_TOK, RHO_FLOOR, Y_CLIP, SD_FLOOR, Z_CLIP) + + +# --------------------------------------------------------------------------- # +# distributed helpers +# --------------------------------------------------------------------------- # +def ddp_setup(): + if "WORLD_SIZE" in _os.environ and int(_os.environ["WORLD_SIZE"]) > 1: + backend = "nccl" if torch.cuda.is_available() else "gloo" + dist.init_process_group(backend, timeout=datetime.timedelta(minutes=120)) + rank, world = dist.get_rank(), dist.get_world_size() + local = int(_os.environ.get("LOCAL_RANK", 0)) + else: + rank, world, local = 0, 1, 0 + if torch.cuda.is_available(): + torch.cuda.set_device(local) + dev = torch.device("cuda", local) + else: + dev = torch.device("cpu") + return rank, world, local, dev + + +def _all_reduce_mean(t): + if dist.is_initialized(): + dist.all_reduce(t, op=dist.ReduceOp.SUM); t /= dist.get_world_size() + return t + + +def _gather_cat(t): + """all_gather equal-sized shards -> concatenated on every rank (order = rank order).""" + if not dist.is_initialized(): + return t + out = [torch.empty_like(t) for _ in range(dist.get_world_size())] + dist.all_gather(out, t.contiguous()) + return torch.cat(out, 0) + + +def _barrier(): + if dist.is_initialized(): + dist.barrier() + + +# --------------------------------------------------------------------------- # +# background batch prefetch (memmap gather + pinned H2D overlap the ViT step) +# --------------------------------------------------------------------------- # +class Prefetcher: + def __init__(self, data, rng, batch, beta_lo, beta_hi, device, n_slots=3, onestep=False): + self.d, self.rng, self.batch = data, rng, batch + # onestep (DINO-WM, gen_q#268): the target frame is the anchor plus ONE action chunk, not a + # draw from the beta-discounted occupancy. The anchor draw itself is untouched, so a + # latent-MSE run and a flow run see the same episodes and the same anchors. + self.onestep = onestep + self.lo, self.hi, self.dev = beta_lo, beta_hi, device + self.n = n_slots + self.slots = [None] * n_slots; self.events = [None] * n_slots + self.q = queue.Queue(maxsize=n_slots - 1) + self.stop = False + self.pin = device.type == "cuda" + self.th = threading.Thread(target=self._run, daemon=True); self.th.start() + + def _run(self): + i = 0 + while not self.stop: + s = i % self.n + if self.stop: + break + ev = self.events[s] + if ev is not None: + ev.synchronize() + e, t, fut, beta = self.d.draw(self.batch, self.rng, self.lo, self.hi, "train") + if self.onestep: + fut, beta = _onestep_future(self.d, e, t) + b = self.d.gather(e, t, fut, beta) + tens = {k: v for k, v in b.items() if torch.is_tensor(v)} + meta = {k: v for k, v in b.items() if not torch.is_tensor(v)} + if self.slots[s] is None: + self.slots[s] = {k: (torch.empty_like(v).pin_memory() if self.pin else torch.empty_like(v)) + for k, v in tens.items()} + for k, v in tens.items(): + self.slots[s][k].copy_(v) + self.q.put((s, meta)) + i += 1 + # leave the pinned buffers alive until the main thread's pending H2D copies are done + for ev in self.events: + if ev is not None: + try: + ev.synchronize() + except Exception: + pass + + def next(self): + s, meta = self.q.get() + out = {k: v.to(self.dev, non_blocking=True, copy=True) for k, v in self.slots[s].items()} + if self.pin: + ev = torch.cuda.Event(); ev.record(); self.events[s] = ev + out.update(meta) + return out + + def close(self): + """Stop and JOIN the worker: returning from main while the thread is inside a numpy/torch + copy aborts the interpreter at teardown ('terminate called without an active exception').""" + self.stop = True + for _ in range(600): # drain until the thread has left its loop + try: + while True: + self.q.get_nowait() + except queue.Empty: + pass + self.th.join(timeout=0.1) + if not self.th.is_alive(): + break + + +# --------------------------------------------------------------------------- # +def _onestep_future(d, e, t): + """(fut, beta) for the DINO-WM one-step target: the frame one ACTION CHUNK ahead. + + A DINO-WM hop is one chunk of `d.chunk` frames (0.4 s at 20 Hz), which is what the action the + model is conditioned on actually covers -- whereas an RSM/DWM hop spans 1/(1-beta) frames. That + is why gen_q#268 matches the two scorers on the NUMBER of hops (L in {1,2,4,8}) and not on beta: + a latent-dynamics model has no beta. beta is returned as ZERO so the predictor's beta + conditioning is a constant on this path and carries no information; the read-out passes the same + constant, so training and scoring agree. + Clamped to the episode's last frame: a terminal anchor predicts itself rather than the first + frame of the next episode. + """ + hi = d.ep_to[e] + fut = np.minimum(t + d.chunk, hi - 1) + return fut, np.zeros(len(t), dtype=np.float64) + + +def cfm_terms(model, norm, rms_tok, rms_pr, b, k=None, noise=None, perm=None, x_noise=0.0, + dynamics="flow"): + """Flow-matching pieces on one (micro-)batch. Returns dict with per-row errors. + x_noise: Gaussian noise (z-scored units) on the CONDITIONING state only (train_rsm.py's + --x-noise); the residual target is built from the clean state.""" + tok_now = norm.tok(b["tok_now"]); tok_fut = norm.tok(b["tok_fut"]) + pr_now = norm.pr(b["pr_now"]); pr_fut = norm.pr(b["pr_fut"]) + B = tok_now.shape[0] + y_tok = ((tok_fut - tok_now) / rms_tok).clamp(-Y_CLIP, Y_CLIP) # rms floored at RHO_FLOOR + y_pr = ((pr_fut - pr_now) / rms_pr).clamp(-Y_CLIP, Y_CLIP) + tok_now_clean, pr_now_clean = tok_now, pr_now + if x_noise > 0: + tok_now = tok_now + x_noise * torch.randn_like(tok_now) + pr_now = pr_now + x_noise * torch.randn_like(pr_now) + if dynamics == "latent_mse": + return _latent_mse_terms(model, b, tok_now, pr_now, tok_now_clean, pr_now_clean, + tok_fut, pr_fut, rms_tok, rms_pr, y_tok, y_pr, perm) + if k is None: + k = torch.rand(B, device=tok_now.device) + if noise is None: + noise = (torch.randn_like(y_tok), torch.randn_like(y_pr)) + n_tok, n_pr = noise + xk_tok = (1 - k)[:, None, None] * y_tok + k[:, None, None] * n_tok + xk_pr = (1 - k)[:, None] * y_pr + k[:, None] * n_pr + u_tok, u_pr = y_tok - n_tok, y_pr - n_pr + v_tok, v_pr = model(tok_now, pr_now, b["a_now"], b["beta"], xk_tok, xk_pr, k) + e_tok = (v_tok.float() - u_tok).pow(2).mean((-1, -2)) # [B] + e_pr = (v_pr.float() - u_pr).pow(2).mean(-1) if u_pr.shape[1] else torch.zeros_like(e_tok) + out = {"e_tok": e_tok, "e_pr": e_pr, "tok_now": tok_now, "pr_now": pr_now, + "tok_fut": tok_fut, "pr_fut": pr_fut, "y_tok": y_tok, "y_pr": y_pr} + if perm is not None: + v_tok2, v_pr2 = model(tok_now, pr_now, b["a_now"][perm], b["beta"], xk_tok, xk_pr, k) + out["e_tok_neg"] = (v_tok2.float() - u_tok).pow(2).mean((-1, -2)) + out["e_pr_neg"] = (v_pr2.float() - u_pr).pow(2).mean(-1) if u_pr.shape[1] else torch.zeros_like(e_tok) + return out + + +def _latent_mse_terms(model, b, tok_now, pr_now, tok_now_clean, pr_now_clean, tok_fut, pr_fut, + rms_tok, rms_pr, y_tok, y_pr, perm): + """DINO-WM's objective: DETERMINISTIC next-latent prediction under latent MSE (gen_q#268). + + Same predictor, same frozen DINOv2 patch features, same normaliser, same reward head -- the ONLY + thing that changes against the flow path is what the network regresses: + + flow : v_theta(x_k | s, a, beta, k) -> the conditional flow-matching velocity of the + normalised residual toward a draw from the beta-discounted occupancy + latent_mse : f_theta(s, a) -> the next latent one action chunk ahead, scored by + || f_theta(s,a) - s' ||^2 in the z-scored DINO latent space + + The predictor is queried at ONE fixed point of its flow-time/noise inputs (x_k = 0, k = 0), so + the "future" half of its token sequence is a learned query attending to the current frame's + patch tokens under the action embedding -- which is exactly DINO-WM's structure: a causal + transformer predicting the next frame's patch features from this frame's plus the action. + + HISTORY LENGTH. DINO-WM conditions on 3 frames; this port conditions on 1, and that is forced by + the evaluation protocol rather than chosen: the planner hands a scorer the SINGLE current frame + (`obs_t = {k: v[:, -1] ...}` in rsm_planner.plan_get_action), so a history-3 world model could + not be evaluated here at all without changing what every other scorer sees. It is a declared + deviation, not a silent one. + + The residual parameterisation (predict rms * v and add the current latent) is kept from the flow + path so the two share their conditioning and their output scale; it is a reparameterisation of + the same prediction and the LOSS is in the latent space, unclamped, as latent MSE requires. + """ + zeros_tok = torch.zeros_like(y_tok) + zeros_pr = torch.zeros_like(y_pr) + kz = torch.zeros(tok_now.shape[0], device=tok_now.device) + bz = torch.zeros_like(b["beta"]) + + def _pred(a): + v_tok, v_pr = model(tok_now, pr_now, a, bz, zeros_tok, zeros_pr, kz) + p_tok = tok_now_clean.float() + rms_tok * v_tok.float() + p_pr = (pr_now_clean.float() + rms_pr * v_pr.float()) if v_pr.shape[1] else v_pr.float() + return p_tok, p_pr + + p_tok, p_pr = _pred(b["a_now"]) + e_tok = (p_tok - tok_fut.float()).pow(2).mean((-1, -2)) + e_pr = (p_pr - pr_fut.float()).pow(2).mean(-1) if p_pr.shape[1] else torch.zeros_like(e_tok) + out = {"e_tok": e_tok, "e_pr": e_pr, "tok_now": tok_now, "pr_now": pr_now, + "tok_fut": tok_fut, "pr_fut": pr_fut, "y_tok": y_tok, "y_pr": y_pr} + if perm is not None: + n_tok, n_pr = _pred(b["a_now"][perm]) + out["e_tok_neg"] = (n_tok - tok_fut.float()).pow(2).mean((-1, -2)) + out["e_pr_neg"] = ((n_pr - pr_fut.float()).pow(2).mean(-1) if n_pr.shape[1] + else torch.zeros_like(e_tok)) + return out + + +def per_row_cfm(e_tok, e_pr, n_tok=N_TOK): + """One CFM number per row: mean over the 515 'tokens' of the per-token MSE.""" + return (n_tok * e_tok + e_pr) / (n_tok + 1) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True, help="cache/; reads tokens/tok.f16.npy from it") + ap.add_argument("--tokens", default="", help="override: directory holding tok.f16.npy") + ap.add_argument("--tok-rows", default="", + help="row-index .npy mapping THIS cache's frames into --tokens' file, for a " + "cache that is a row slice of a parent (cache/square_sub_20100 of " + "cache/square_expert_suboptimal). Avoids a multi-GB copy of the parent's " + "token file; token normalisation is then fitted on our rows and cached in " + "OUR cache dir, not the parent's.") + ap.add_argument("--out", required=True) + ap.add_argument("--depth", type=int, default=6) + ap.add_argument("--heads", type=int, default=16) + ap.add_argument("--dim-head", type=int, default=64) + ap.add_argument("--mlp", type=int, default=2048) + ap.add_argument("--dropout", type=float, default=0.1, help="DINO-WM's predictor dropout") + ap.add_argument("--grad-ckpt", type=int, default=0, + help="activation checkpointing per transformer layer (memory for ~30%% compute)") + ap.add_argument("--chunk", type=int, default=8) + ap.add_argument("--beta-lo", type=float, default=0.90) + ap.add_argument("--beta-hi", type=float, default=0.995) + ap.add_argument("--beta-q", type=float, default=0.95, help="query beta for diagnostics") + ap.add_argument("--batch", type=int, default=4096, help="GLOBAL batch (split over ranks)") + ap.add_argument("--micro", type=int, default=256, help="rows per forward on one GPU (grad accumulation)") + ap.add_argument("--steps", type=int, default=100000) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--wd", type=float, default=0.01) + ap.add_argument("--ema", type=float, default=0.995) + ap.add_argument("--w-reward", type=float, default=1.0) + ap.add_argument("--flow-steps", type=int, default=8) + ap.add_argument("--w-actcon", type=float, default=0.5, + help="action-contrastive weight (train_rsm.py): softplus(e_pos - e_neg) " + "with e_neg the CFM error under a within-batch permuted chunk") + ap.add_argument("--actcon-rows", type=int, default=0, + help="rows per micro-batch that get the (second, full-gradient) negative " + "forward; 0 = all rows") + ap.add_argument("--tok-drop", type=float, default=0.0, + help="training-time dropout of whole 'now' tokens (regulariser probe)") + ap.add_argument("--x-noise", type=float, default=0.0, + help="Gaussian noise (z-scored units) on the conditioning state during training " + "(train_rsm.py's --x-noise; stream B's regulariser against episode memorisation)") + ap.add_argument("--eval-every", type=int, default=5000) + ap.add_argument("--eval-minmse-n", type=int, default=16) + ap.add_argument("--eval-rows", type=int, default=2048) + ap.add_argument("--eval-frames", type=int, default=1024) + ap.add_argument("--success-gamma", type=float, default=0.98) + ap.add_argument("--reward-loss", default="bce", choices=["bce"]) + ap.add_argument("--reward-mode", default="dense", choices=["dense", "soft", "goal"], + help="goal = env-success-by-replay per-frame label (cache//goal.npz): a goal-STATE classifier") + ap.add_argument("--goal-file", default="", help="goal.npz for --reward-mode goal (default /goal.npz)") + ap.add_argument("--save-every", type=int, default=10000) + ap.add_argument("--resume", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--in-ram", type=int, default=0, help="copy the token memmap into RAM per rank") + ap.add_argument("--warm-cache", type=int, default=1, help="sequential read of the token file " + "on local rank 0 before training (page cache)") + ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", "")) + ap.add_argument("--wandb-project", default=_os.environ.get("RSM_WANDB_PROJECT", "rsm_rise")) + ap.add_argument("--wandb-name", default="") + ap.add_argument("--wandb-mode", default="online", choices=["online", "offline", "disabled"]) + ap.add_argument("--log-every", type=int, default=100) + ap.add_argument("--print-every", type=int, default=100) + ap.add_argument("--compile", type=int, default=0, help="torch.compile the training forward") + ap.add_argument("--allow-old-pack", type=int, default=0, + help="run even if PACK.json lacks the final state-definition keys (probes only)") + # DINO-WM (gen_q#268): the DYNAMICS objective. `flow` (default) is unchanged DWM -- the + # beta-discounted successor fitted by conditional flow matching. `latent_mse` is DINO-WM: + # deterministic next-latent prediction one action chunk ahead, scored by MSE in the frozen + # DINOv2 latent space. Everything else (predictor, features, normaliser, reward head, + # optimiser, steps) is identical, so the pair isolates the dynamics model. + ap.add_argument("--dynamics", default="flow", choices=["flow", "latent_mse"], + help="flow = DWM's occupancy flow matching (DEFAULT, unchanged); " + "latent_mse = DINO-WM's deterministic next-latent prediction") + ap.add_argument("--time-steps", type=int, default=0, + help="if >0: run this many steps, print s/step and exit (throughput probe)") + args = ap.parse_args() + + rank, world, local, dev = ddp_setup() + is_main = rank == 0 + torch.manual_seed(args.seed * 1000 + rank) + out = Path(args.out) + if is_main: + out.mkdir(parents=True, exist_ok=True) + per_rank = args.batch // world + assert per_rank * world == args.batch, f"--batch {args.batch} not divisible by {world} ranks" + micro = min(args.micro, per_rank) + n_micro = per_rank // micro + assert n_micro * micro == per_rank, f"per-rank batch {per_rank} not divisible by --micro {micro}" + use_cuda = dev.type == "cuda" + ac = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) if use_cuda else (lambda: torch.autocast("cpu", enabled=False)) + + # ---- W&B (rank 0; entity/project from wandb_env.sh; resumable by run id) ---- + wb = None + if is_main and args.wandb_entity and args.wandb_mode != "disabled": + try: + import wandb, hashlib + _rid = hashlib.md5(str(out.resolve()).encode()).hexdigest()[:16] + wb = wandb.init(entity=args.wandb_entity, project=args.wandb_project, + name=args.wandb_name or out.name, id=_rid, resume="allow", + mode=args.wandb_mode, config=vars(args), dir=str(out)) + print(f"[dwm] wandb: {wb.url}", flush=True) + except Exception as e: + print(f"[dwm] wandb disabled: {e}", flush=True) + wb = None + + def _flat(prefix, obj, acc): + if isinstance(obj, dict): + for k, v in obj.items(): + _flat(f"{prefix}/{k}" if prefix else str(k), v, acc) + elif isinstance(obj, (int, float)): + acc[prefix] = float(obj) + return acc + + # ---- data ---- + # The action-contrastive auxiliary is OUR addition to the flow recipe, not part of DINO-WM. A + # latent-MSE run left at the flow default would therefore be "DINO-WM plus an auxiliary we + # invented", which is not the published comparator, so it is switched off unless the caller asks + # for it explicitly. Pass --w-actcon to override (and say so in any table that uses it). + if args.dynamics == "latent_mse" and abs(args.w_actcon - ap.get_default("w_actcon")) < 1e-12: + print(f"[dwm] --dynamics latent_mse: --w-actcon {args.w_actcon} -> 0.0 " + f"(DINO-WM is latent MSE only; pass --w-actcon explicitly to keep the auxiliary)", + flush=True) + args.w_actcon = 0.0 + if args.dynamics == "latent_mse": + print("[dwm] DYNAMICS = latent_mse (DINO-WM): deterministic next-latent prediction one " + f"chunk ({args.chunk} frames) ahead, latent MSE in the z-scored DINOv2 space; " + "beta conditioning is a constant 0 on this path", flush=True) + tokens_file = str(Path(args.tokens) / "tok.f16.npy") if args.tokens else "" + try: + _pack = json.loads((Path(args.cache) / "PACK.json").read_text()) + except Exception: + _pack = {} + if not args.allow_old_pack and not ("sd_floor" in _pack and "z_clip" in _pack): + raise SystemExit(f"[dwm] {args.cache}/PACK.json lacks 'sd_floor'/'z_clip' (the final Stage-1 state " + f"definition); refusing to launch. Pass --allow-old-pack 1 for probes.") + if _pack and is_main: + print(f"[dwm] PACK.json: sd_floor={_pack.get('sd_floor')} z_clip={_pack.get('z_clip')} " + f"(token space uses sd_floor={SD_FLOOR} z_clip={Z_CLIP} rho_floor={RHO_FLOOR} y_clip={Y_CLIP})", flush=True) + if rank != 0: + _barrier() # rank 0 fits + writes tok_stats.npz first; the others then load it + d = TokenRSMData(args.cache, chunk=args.chunk, seed=args.seed, reward_mode=args.reward_mode, + success_gamma=args.success_gamma, in_ram=bool(args.in_ram), + tokens_file=tokens_file, goal_file=args.goal_file, tok_rows=args.tok_rows) + if rank == 0: + _barrier() + if is_main: + try: + print(f"[dwm] host {_os.uname().nodename}: {len(_os.sched_getaffinity(0))} cpus in affinity mask, " + f"{torch.cuda.device_count() if use_cuda else 0} gpus visible", flush=True) + except Exception: + pass + print(f"[dwm] {d.n_ep} eps ({len(d.train_eps)} train / {len(d.val_eps)} val), " + f"{d.n_task} tasks, tokens={tuple(d.tok.shape)} proprio={d.n_pr}, " + f"positives={d.r.mean():.4f}, world={world} batch={args.batch} " + f"({per_rank}/rank, micro {micro} x {n_micro})", flush=True) + if args.warm_cache and not args.in_ram and local == 0: + t0 = time.time(); n = d.tok.shape[0]; step_rows = max(1, (1 << 28) // (N_TOK * D_TOK * 2)) + for i in range(0, n, step_rows): + _blk = np.array(d.tok[i:i + step_rows]); del _blk # copy => reads every page + print(f"[dwm] warmed page cache: {d.tok.nbytes/1e9:.1f} GB in {time.time()-t0:.0f}s", flush=True) + _barrier() + + d_act = args.chunk * d.adim + norm = Normalizer(d.stats).to(dev) + flow = DWM(N_TOK, D_TOK, d.n_pr, d_act, depth=args.depth, heads=args.heads, + dim_head=args.dim_head, mlp_dim=args.mlp, dropout=args.dropout, + emb_dropout=args.dropout, grad_ckpt=bool(args.grad_ckpt), tok_drop=args.tok_drop).to(dev) + rew = DWMReward(N_TOK, D_TOK, d.n_pr).to(dev) + n_flow = sum(p.numel() for p in flow.parameters()); n_rew = sum(p.numel() for p in rew.parameters()) + if is_main: + print(f"[dwm] params: flow {n_flow/1e6:.2f} M (ViT depth {args.depth}, {args.heads}x{args.dim_head}, " + f"mlp {args.mlp}, dim {flow.dim}, seq {2*flow.n_seq}) + reward {n_rew/1e6:.2f} M", flush=True) + flow_ema = copy.deepcopy(flow).eval(); rew_ema = copy.deepcopy(rew).eval() + for p in list(flow_ema.parameters()) + list(rew_ema.parameters()): + p.requires_grad_(False) + _trainable = list(flow.parameters()) + list(rew.parameters()) + opt = torch.optim.AdamW(_trainable, lr=args.lr, weight_decay=args.wd) + rms_tok = torch.ones(N_TOK, D_TOK, device=dev); rms_pr = torch.ones(max(d.n_pr, 1), device=dev)[:d.n_pr] + hist = []; best_win = -1.0; start_step = 0 + + _ck = out / "ckpt.pt" + if args.resume and _ck.exists(): + _c = torch.load(_ck, map_location=dev, weights_only=False) + flow.load_state_dict(_c["flow"]); rew.load_state_dict(_c["rew"]) + flow_ema.load_state_dict(_c["flow_ema"]); rew_ema.load_state_dict(_c["rew_ema"]) + if "opt" in _c: + opt.load_state_dict(_c["opt"]) + rms_tok = _c["rms_tok"].to(dev); rms_pr = _c["rms_pr"].to(dev) + best_win = _c.get("best_win", -1.0); hist = _c.get("hist", []) + start_step = int(_c["step"]) + if is_main: + print(f"[dwm] RESUMED at step {start_step}/{args.steps} (best action winrate {best_win:.3f})", + flush=True) + if start_step >= args.steps: + if is_main: + print("[dwm] already complete; nothing to do", flush=True) + return + _barrier() + + if world > 1: + ddp = torch.nn.parallel.DistributedDataParallel(flow, device_ids=[local] if use_cuda else None) + rew_d = torch.nn.parallel.DistributedDataParallel(rew, device_ids=[local] if use_cuda else None) + else: + ddp, rew_d = flow, rew + model = torch.compile(ddp, dynamic=False) if args.compile else ddp # compile on top of DDP + + # per-rank data stream, decorrelated across ranks and across restarts + rng = np.random.default_rng(args.seed + 9973 * start_step + 7919 * rank) + pf = Prefetcher(d, rng, per_rank, args.beta_lo, args.beta_hi, dev, + onestep=args.dynamics == "latent_mse") + pos_w = torch.tensor(max((1 - d.r.mean()) / max(d.r.mean(), 1e-6), 1.0), device=dev) + t0 = time.time(); t_last = time.time(); step_t = [] + + def save(step, gap_win, gap, cfm_v): + nonlocal best_win + blob = {"encoder": d.tok_info.get("encoder", "dinov2_vits14_tokens"), + "cam_res": d.tok_info.get("cam_res", 84), + # "model" is what a read-out dispatches on: a latent-MSE checkpoint must NOT be + # loaded by the flow read-out (it would Euler-integrate a network that was never + # trained as a velocity field and report the result as DINO-WM). + "model": "dinowm" if args.dynamics == "latent_mse" else "dwm", + "dynamics": args.dynamics, "hop_frames": int(args.chunk), + "flow": flow.state_dict(), "rew": rew.state_dict(), + "flow_ema": flow_ema.state_dict(), "rew_ema": rew_ema.state_dict(), + "norm": {k: torch.as_tensor(v) for k, v in d.stats.items()}, + "rms_tok": rms_tok.cpu(), "rms_pr": rms_pr.cpu(), "config": vars(args), + "arch": {"n_tok": N_TOK, "d_tok": D_TOK, "n_pr": d.n_pr, "d_act": d_act, + "depth": args.depth, "heads": args.heads, "dim_head": args.dim_head, + "mlp_dim": args.mlp, "dropout": args.dropout}, + "n_pr": d.n_pr, "tasks": d.tasks, "d_act": d_act, "step": step, + "q_action_winrate": gap_win} + blob_r = dict(blob); blob_r["opt"] = opt.state_dict() + blob_r["best_win"] = max(best_win, gap_win); blob_r["hist"] = hist + _tmp = out / "ckpt.pt.tmp"; torch.save(blob_r, _tmp); _os.replace(_tmp, out / "ckpt.pt") + if args.save_every and step % args.save_every == 0: + torch.save(blob, out / f"ckpt_s{step}.pt") + _cf = [h["cfm_val"] for h in hist[:-1] if "cfm_val" in h] + _healthy = (len(_cf) < 3) or (cfm_v <= 2.0 * float(np.median(_cf))) + if not _healthy: + print(f"[dwm] cfm_val {cfm_v:.3f} > 2x running median {float(np.median(_cf)):.3f}: " + f"occupancy unstable, NOT eligible as best", flush=True) + if gap_win > best_win and _healthy: + best_win = gap_win + torch.save(blob, out / "ckpt_best.pt") + print(f"[dwm] new BEST action winrate {gap_win:.3f} (gap {gap:+.5f}) at step {step}", flush=True) + + # ------------------------------------------------------------------ # + for step in range(start_step + 1, args.steps + 1): + b_full = pf.next() + opt.zero_grad(set_to_none=True) + acc_l = {"rew": 0.0, "cfm": 0.0, "cfm_pr": 0.0, "ac": 0.0, "loss": 0.0} + for mi in range(n_micro): + sl = slice(mi * micro, (mi + 1) * micro) + b = {k: (v[sl] if torch.is_tensor(v) else v[sl]) for k, v in b_full.items()} + last = mi == n_micro - 1 + ctx_f = ddp.no_sync() if (world > 1 and not last) else _nullctx() + ctx_r = rew_d.no_sync() if (world > 1 and not last) else _nullctx() + with ctx_f, ctx_r: + # running per-(token, channel) RMS of the residual, identical on all ranks + with torch.no_grad(): + tn = norm.tok(b["tok_now"]); tf_ = norm.tok(b["tok_fut"]) + cur = (tf_ - tn).pow(2).mean(0) + cur_pr = (norm.pr(b["pr_fut"]) - norm.pr(b["pr_now"])).pow(2).mean(0) + _all_reduce_mean(cur); _all_reduce_mean(cur_pr) + rms_tok.mul_(0.99).add_(cur.sqrt().clamp_min(RHO_FLOOR), alpha=0.01) + rms_pr.mul_(0.99).add_(cur_pr.sqrt().clamp_min(RHO_FLOOR), alpha=0.01) + with ac(): + # ---- reward head on the CURRENT frame (balanced BCE on the success label) ---- + logit = rew_d(norm.tok(b["tok_now"]), norm.pr(b["pr_now"])) + if args.reward_mode == "soft": + l_rew = F.binary_cross_entropy_with_logits(logit.float(), b["r_now"]) + else: + l_rew = F.binary_cross_entropy_with_logits(logit.float(), b["r_now"], pos_weight=pos_w) + # ---- occupancy: flow-match the normalised token residual ---- + l_ac = torch.zeros((), device=dev) + if args.w_actcon > 0 and args.actcon_rows and args.actcon_rows < micro: + # contrast on the first --actcon-rows rows (positive + negative forward), + # plain CFM on the rest: one positive forward per row either way + nr = args.actcon_rows + bs = {k: v[:nr] for k, v in b.items()} + br = {k: v[nr:] for k, v in b.items()} + c_sub = cfm_terms(model, norm, rms_tok, rms_pr, bs, perm=torch.randperm(nr, device=dev), x_noise=args.x_noise, dynamics=args.dynamics) + c_rest = cfm_terms(model, norm, rms_tok, rms_pr, br, x_noise=args.x_noise, dynamics=args.dynamics) + e_pos_c = per_row_cfm(c_sub["e_tok"], c_sub["e_pr"]) + e_neg_c = per_row_cfm(c_sub["e_tok_neg"], c_sub["e_pr_neg"]) + l_ac = F.softplus(e_pos_c - e_neg_c).mean() + c = {"e_tok": torch.cat([c_sub["e_tok"], c_rest["e_tok"]]), + "e_pr": torch.cat([c_sub["e_pr"], c_rest["e_pr"]])} + else: + perm = torch.randperm(micro, device=dev) if args.w_actcon > 0 else None + c = cfm_terms(model, norm, rms_tok, rms_pr, b, perm=perm, x_noise=args.x_noise, dynamics=args.dynamics) + if perm is not None: + e_pos_c = per_row_cfm(c["e_tok"], c["e_pr"]) + e_neg_c = per_row_cfm(c["e_tok_neg"], c["e_pr_neg"]) + l_ac = F.softplus(e_pos_c - e_neg_c).mean() + l_cfm = per_row_cfm(c["e_tok"], c["e_pr"]).mean() + l_cfm_pr = c["e_pr"].mean() + loss = args.w_reward * l_rew + l_cfm + args.w_actcon * l_ac + (loss / n_micro).backward() + for k_, v_ in (("rew", l_rew), ("cfm", l_cfm), ("cfm_pr", l_cfm_pr), ("ac", l_ac), ("loss", loss)): + acc_l[k_] += float(v_.detach()) / n_micro + gn_total = float(torch.nn.utils.clip_grad_norm_(_trainable, 1.0)) + opt.step() + ema_update(flow_ema, flow, args.ema); ema_update(rew_ema, rew, args.ema) + + if use_cuda and (step % args.print_every == 0 or args.time_steps): + torch.cuda.synchronize() + now = time.time(); step_t.append(now - t_last); t_last = now + if args.time_steps and step - start_step >= args.time_steps: + st = np.array(step_t[max(0, len(step_t) // 4):]) # drop warm-up + if is_main: + print(f"[dwm] TIMING {len(st)} steps: {st.mean():.3f} s/step (median {np.median(st):.3f}), " + f"global batch {args.batch}, world {world}, micro {micro}; " + f"projected {args.steps} steps = {args.steps*st.mean()/3600:.1f} h; " + f"peak mem {torch.cuda.max_memory_allocated()/2**30 if use_cuda else 0:.1f} GiB", flush=True) + pf.close() + if dist.is_initialized(): + dist.destroy_process_group() + return + if is_main and step % args.print_every == 0: + print(f"[dwm] {step} rew={acc_l['rew']:.4f} cfm={acc_l['cfm']:.4f} " + f"ac={acc_l['ac']:.4f} gradnorm={gn_total:.3f} " + f"rms_mean={float(rms_tok.mean()):.3f} ({np.mean(step_t[-args.print_every:]):.3f} s/step, " + f"{(step-start_step)/(time.time()-t0):.2f} it/s)", flush=True) + if wb is not None and (step % args.log_every == 0 or step == start_step + 1): + def _mod_gn(m): + sq = [p.grad.detach().float().pow(2).sum() for p in m.parameters() if p.grad is not None] + return float(torch.stack(sq).sum().sqrt()) if sq else 0.0 + wb.log({"train/loss": acc_l["loss"], "train/l_rew": acc_l["rew"], + "train/l_cfm": acc_l["cfm"], "train/l_cfm_pr": acc_l["cfm_pr"], + "train/l_actcon": acc_l["ac"], + "train/gradnorm": gn_total, "train/gradnorm_clipped": min(gn_total, 1.0), + "train/gradnorm_rew": _mod_gn(rew), "train/gradnorm_flow": _mod_gn(flow), + "train/rms_mean": float(rms_tok.mean()), "train/rms_pr_mean": float(rms_pr.mean()) if d.n_pr else 0.0, + "train/lr": opt.param_groups[0]["lr"], + "train/s_per_step": float(np.mean(step_t[-args.log_every:])), + "train/it_per_s": (step - start_step) / max(time.time() - t0, 1e-6)}, step=step) + + # ------------------------------------------------------------------ # + if step % args.eval_every == 0 or step == args.steps: + rec = evaluate(args, d, norm, flow_ema, rew_ema, rms_tok, rms_pr, dev, rank, world, + step, micro, ac) + if is_main: + rec["step"] = step + rec = {"step": step, **{k: v for k, v in rec.items() if k != "step"}} + hist.append(rec) + if wb is not None: + wb.log(_flat("eval", {k: v for k, v in rec.items() if k != "step"}, {}), step=step) + ident = rec["identity"] + print(f"[dwm] EVAL {step}: reward_auc={rec['reward_auc']:.4f} cfm={rec['cfm_val']:.4f} " + f"ACTION gap={rec['q_action_gap']:+.5f} win={rec['q_action_winrate']:.3f} | " + f"state auc={rec['q_success_auc']:.4f}", flush=True) + print(f"[dwm] MINMSE(n={args.eval_minmse_n}): train={rec['minmse_train']:.4f} " + f"val={rec['minmse_val']:.4f} meanmse={rec['meanmse_val']:.4f} " + f"staymse={rec['staymse_val']:.4f} (train stay {rec['staymse_train']:.4f})", flush=True) + print(f"[dwm] GENERALISATION: cfm train={rec['cfm_train']:.4f} val={rec['cfm_val']:.4f} " + f"(val/train {rec['val_over_train_cfm']:.2f}x, medians {rec['cfm_train_median']:.3f}/{rec['cfm_val_median']:.3f}) | " + f"minmse val/train {rec['val_over_train_minmse']:.2f}x " + f"(medians {rec['minmse_train_median']:.3f}/{rec['minmse_val_median']:.3f})", flush=True) + print(f"[dwm] IDENTITY Qbar: corr={ident['corr']:.3f} spearman={ident['spearman']:.3f} " + f"mse={ident['mse']:.5f} within-task={ident['corr_within_task']:.3f} " + f"(const-null mse {ident['mse_const']:.5f}) qhat={ident['q_hat_mean']:.4f} " + f"vs mc={ident['q_mc_mean']:.4f}", flush=True) + print("[dwm] by time-to-end: " + " ".join( + f"{k}:gap={v['action_gap']:+.5f}/win={v['action_winrate']:.2f}(n={v['n']})" + for k, v in rec["by_horizon"].items()), flush=True) + (out / "history.json").write_text(json.dumps(hist, indent=1)) + save(step, rec["q_action_winrate"], rec["q_action_gap"], rec["cfm_val"]) + _barrier() + pf.close() + if is_main: + print("[dwm] DONE", flush=True) + if dist.is_initialized(): + dist.destroy_process_group() + + +class _nullctx: + def __enter__(self): return self + def __exit__(self, *a): return False + + +# --------------------------------------------------------------------------- # +# evaluation, sharded across ranks (rows split by rank, gathered to every rank) +# --------------------------------------------------------------------------- # +@torch.no_grad() +def evaluate(args, d, norm, flow_ema, rew_ema, rms_tok, rms_pr, dev, rank, world, step, micro, ac): + flow_ema.eval(); rew_ema.eval() + rng = np.random.default_rng(args.seed + 12345 + step) # identical on every rank + n_rows = (args.eval_rows // world) * world + n_fr = (args.eval_frames // world) * world + N = args.eval_minmse_n + + def shard(arrs): + return [a[rank::world] for a in arrs] + + def _to(b): + return {k: (v.to(dev) if torch.is_tensor(v) else v) for k, v in b.items()} + + def minmse_block(split): + e, t, fut, beta = d.draw(n_rows, rng, args.beta_lo, args.beta_hi, split) + if args.dynamics == "latent_mse": + fut, beta = _onestep_future(d, e, t) # else validation would score another target + e, t, fut, beta = shard([e, t, fut, beta]) + mins, means, stays, cfms, cfm_prs, logits, r_now = [], [], [], [], [], [], [] + chunk = max(1, 4096 // max(N, 1)) + for i in range(0, len(t), chunk): + b = _to(d.gather(e[i:i + chunk], t[i:i + chunk], fut[i:i + chunk], beta[i:i + chunk])) + tn = norm.tok(b["tok_now"]); tf_ = norm.tok(b["tok_fut"]) + pn = norm.pr(b["pr_now"]) + B = tn.shape[0] + with ac(): + c = cfm_terms(flow_ema, norm, rms_tok, rms_pr, b, dynamics=args.dynamics) + logits.append(rew_ema(tn, pn).float()) + cfms.append(per_row_cfm(c["e_tok"], c["e_pr"])); cfm_prs.append(c["e_pr"]) + r_now.append(b["r_now"]) + xs, _ = sample_future_dwm(flow_ema, tn, pn, b["a_now"], b["beta"], rms_tok, rms_pr, + args.flow_steps, n=N, micro=micro, autocast=ac) + err = (xs.view(B, N, N_TOK, D_TOK) - tf_[:, None]).pow(2).mean((-1, -2)) # [B,N] + mins.append(err.min(1).values); means.append(err.mean(1)) + stays.append((tn - tf_).pow(2).mean((-1, -2))) + cat = lambda xs_: _gather_cat(torch.cat(xs_)).cpu().numpy() + return {"minmse": cat(mins), "meanmse": cat(means), "staymse": cat(stays), + "cfm": cat(cfms), "cfm_pr": cat(cfm_prs), "logit": cat(logits), "r_now": cat(r_now)} + + val = minmse_block("val") + tr = minmse_block("train") + r_auc = auc(val["logit"], val["r_now"]) + + # ---- headline: does Q RANK ACTIONS at a fixed state? (CRN across the two chunks) ---- + e, t, _, _ = d.draw(n_fr, rng, 0.5, 0.5, "val") + tkp = d.ep_task[e] + pw = np.arange(n_fr) + for _ti in np.unique(tkp): + _ix = np.nonzero(tkp == _ti)[0] + if len(_ix) > 1: + pw[_ix] = rng.permutation(_ix) + a_all = d._chunk_at(t, e); a_for_all = a_all[pw] + order = np.concatenate([np.arange(n_fr)[r::world] for r in range(world)]) # gathered row order + e_s, t_s = shard([e, t]) + a_s = torch.from_numpy(a_all[rank::world]).to(dev); af_s = torch.from_numpy(a_for_all[rank::world]).to(dev) + q_log, q_for = [], [] + n_part = 4 + chunk = max(1, 2048 // n_part) + for i in range(0, len(t_s), chunk): + b = _to(d.gather(e_s[i:i + chunk], t_s[i:i + chunk], t_s[i:i + chunk], np.zeros(min(chunk, len(t_s) - i)), with_fut=False)) + tn = norm.tok(b["tok_now"]); pn = norm.pr(b["pr_now"]); B = tn.shape[0] + beta_q = torch.full((B,), args.beta_q, device=dev) + x0 = (torch.randn(B * n_part, N_TOK, D_TOK, device=dev), torch.randn(B * n_part, d.n_pr, device=dev)) + + def q_of(a_chunk): + xt, xp = sample_future_dwm(flow_ema, tn, pn, a_chunk, beta_q, rms_tok, rms_pr, + args.flow_steps, n=n_part, x0=x0, micro=micro, autocast=ac) + with ac(): + p = torch.sigmoid(rew_ema(xt, xp).float()) + return p.view(B, n_part).mean(1) + q_log.append(q_of(a_s[i:i + chunk])); q_for.append(q_of(af_s[i:i + chunk])) + q_log = _gather_cat(torch.cat(q_log)).cpu().numpy(); q_for = _gather_cat(torch.cat(q_for)).cpu().numpy() + e_o, t_o = e[order], t[order] + succ = d.ep_success[e_o].astype(np.float32); te = (d.ep_to[e_o] - t_o).astype(np.float32) + tk_np = d.ep_task[e_o] + gap = float((q_log - q_for).mean()); gap_win = float((q_log > q_for).mean()) + q_succ_auc = auc(q_log, succ) + + # ---- MC identity: Qbar(s,a) = E_{k~Geom(1-beta)}[r(s_{t+k})] from the logged trajectory ---- + _kk = rng.geometric(1.0 - args.beta_q, size=(256, len(e_o))) - 1 + _ix = np.minimum(t_o[None, :] + _kk, d.ep_to[e_o][None, :] - 1) + q_mc = d.r[_ix].mean(0); _qh = q_log + identity = {"q_mc_mean": float(q_mc.mean()), "q_hat_mean": float(_qh.mean()), + "mse": float(((_qh - q_mc) ** 2).mean()), + "corr": float(np.corrcoef(_qh, q_mc)[0, 1]) if (_qh.std() > 1e-8 and q_mc.std() > 1e-8) else 0.0, + "spearman": float(np.corrcoef(np.argsort(np.argsort(_qh)), np.argsort(np.argsort(q_mc)))[0, 1]) + if (_qh.std() > 1e-8 and q_mc.std() > 1e-8) else 0.0, + "mse_const": float(((q_mc.mean() - q_mc) ** 2).mean())} + _wt = [] + for _ti in np.unique(tk_np): + _m = tk_np == _ti + if _m.sum() < 32 or _qh[_m].std() < 1e-8 or q_mc[_m].std() < 1e-8: + continue + _wt.append(float(np.corrcoef(_qh[_m], q_mc[_m])[0, 1])) + identity["corr_within_task"] = float(np.mean(_wt)) if _wt else 0.0 + identity["n_tasks_scored"] = len(_wt) + gl = q_log - q_for + by_horizon = {} + for name, lo_, hi_ in (("0-50", 0, 50), ("50-100", 50, 100), ("100-200", 100, 200), ("200+", 200, 1e9)): + m = (te >= lo_) & (te < hi_) + if m.sum() < 16: + continue + by_horizon[name] = {"n": int(m.sum()), "action_gap": float(gl[m].mean()), + "action_winrate": float((gl[m] > 0).mean()), "q_mean": float(q_log[m].mean())} + per_task = {} + for ti in np.unique(tk_np): + m = tk_np == ti + per_task[int(ti)] = {"n": int(m.sum()), "action_gap": float(gl[m].mean()), + "success_auc": auc(q_log[m], succ[m]), "succ_rate": float(succ[m].mean())} + rec = {"step": step, "reward_auc": r_auc, "cfm_val": float(val["cfm"].mean()), + "cfm_pr_val": float(val["cfm_pr"].mean()), + "cfm_train": float(tr["cfm"].mean()), "cfm_pr_train": float(tr["cfm_pr"].mean()), + "cfm_val_median": float(np.median(val["cfm"])), "cfm_train_median": float(np.median(tr["cfm"])), + "minmse_val_median": float(np.median(val["minmse"])), "minmse_train_median": float(np.median(tr["minmse"])), + "val_over_train_cfm": float(val["cfm"].mean() / max(tr["cfm"].mean(), 1e-9)), + "val_over_train_minmse": float(val["minmse"].mean() / max(tr["minmse"].mean(), 1e-9)), + "per_task": per_task, "by_horizon": by_horizon, + "q_action_gap": gap, "q_action_winrate": gap_win, + "q_success_auc": q_succ_auc, "q_mean": float(q_log.mean()), "identity": identity, + "minmse_train": float(tr["minmse"].mean()), "minmse_val": float(val["minmse"].mean()), + "meanmse_train": float(tr["meanmse"].mean()), "meanmse_val": float(val["meanmse"].mean()), + "staymse_train": float(tr["staymse"].mean()), "staymse_val": float(val["staymse"].mean()), + "meanmse": float(val["meanmse"].mean()), "staymse": float(val["staymse"].mean()), + "minmse_n": N, "eval_rows": n_rows, "eval_frames": n_fr, + "rms_mean": float(rms_tok.mean())} + return rec + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/train_slurm.sbatch b/frozen/rsm_libero_freeze_20261002/train_slurm.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..72f1dba70dc9336d54a499517b18ee9c389251ff --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/train_slurm.sbatch @@ -0,0 +1,22 @@ +#!/bin/bash +#SBATCH --job-name=rsm_arm +#SBATCH --account=vision-pulkitag +#SBATCH --qos=lab-free +#SBATCH --partition=csail-shared-h200 +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=110G +#SBATCH --time=20:00:00 +#SBATCH --output=/data/pulkitag/users/rli14/rsm_libero_runs/mit/%x_%j.out +#SBATCH --error=/data/pulkitag/users/rli14/rsm_libero_runs/mit/%x_%j.err +set -uo pipefail +export PYTHONUNBUFFERED=1 +cd /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +PY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python +echo "[arm] $SLURM_JOB_NAME on $(hostname) :: $CMD" +eval "$PY $CMD" +RC=$? +echo "[arm] rc=$RC $(date -u +%T)" +# propagate: otherwise the trailing echo makes a crashed job exit 0 and +# every --dependency=afterok eval launches against a missing checkpoint +exit $RC diff --git a/frozen/rsm_libero_freeze_20261002/verify_cpu.sbatch b/frozen/rsm_libero_freeze_20261002/verify_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..c3211b85af2040f1e3c39ab92119e676720cbd9e --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/verify_cpu.sbatch @@ -0,0 +1,19 @@ +#!/bin/bash +#SBATCH --job-name=verify_succ +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +# no renderer at all -- osmesa keeps mujoco happy without a GPU or EGL +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +OUT=/data/pulkitag/users/rli14/rsm_libero_runs/verify +mkdir -p $OUT +$B/venvs/rlinf-libero-eval-venv/bin/python \ + /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/verify_successes.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --task $SLURM_ARRAY_TASK_ID --out $OUT/task$SLURM_ARRAY_TASK_ID.npz diff --git a/frozen/rsm_libero_freeze_20261002/verify_full.sbatch b/frozen/rsm_libero_freeze_20261002/verify_full.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..e594f89950a15a4b266f3de38f511d28b892b19c --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/verify_full.sbatch @@ -0,0 +1,20 @@ +#!/bin/bash +#SBATCH --job-name=verify_full +#SBATCH --account=vision-pulkitag +#SBATCH --qos=tig-main +#SBATCH --partition=tig-cpu +#SBATCH --cpus-per-task=4 --mem=40G +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +T=$((SLURM_ARRAY_TASK_ID / 4)); K=$((SLURM_ARRAY_TASK_ID % 4)) +OUT=/data/pulkitag/users/rli14/rsm_libero_runs/verify_full; mkdir -p $OUT +$B/venvs/rlinf-libero-eval-venv/bin/python \ + /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/verify_successes.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 diff --git a/frozen/rsm_libero_freeze_20261002/verify_fullg.sbatch b/frozen/rsm_libero_freeze_20261002/verify_fullg.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..d94c538c9cb1892fc10aa111aa14de18e98291d8 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/verify_fullg.sbatch @@ -0,0 +1,22 @@ +#!/bin/bash +#SBATCH --job-name=verify_fullg +#SBATCH --account=vision-pulkitag +#SBATCH --qos=vision-pulkitag-free-cycles +#SBATCH --partition=vision-pulkitag-a100,vision-pulkitag-h200,vision-pulkitag-l40s,vision-pulkitag-a6000 +#SBATCH --cpus-per-task=4 --mem=40G +# CPU-only on the GPU nodes (no --gres): their cores sit idle while tig-cpu runs 2 shards at a time +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +T=$((SLURM_ARRAY_TASK_ID / 4)); K=$((SLURM_ARRAY_TASK_ID % 4)) +OUT=/data/pulkitag/users/rli14/rsm_libero_runs/verify_full; mkdir -p $OUT +[ -f $OUT/task${T}_s${K}.npz ] && { echo "shard task${T}_s${K} already done"; exit 0; } +$B/venvs/rlinf-libero-eval-venv/bin/python \ + /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/verify_successes.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 diff --git a/frozen/rsm_libero_freeze_20261002/verify_successes.py b/frozen/rsm_libero_freeze_20261002/verify_successes.py new file mode 100644 index 0000000000000000000000000000000000000000..a6683a70f11df3de835d5328b9333fc26cfb3af4 --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/verify_successes.py @@ -0,0 +1,97 @@ +"""Replay-verify every logged success: does it actually succeed in the simulator? + +The R1 corpus's is_success labels are ~16% optimistic on the positive side (60-episode +audit: 5/32 logged successes did not reproduce, 0/28 logged failures did). BC-on-successes +clones that pool, and the critic's gamma^steps-to-success reward gives a false success a +full progress curve toward an event that never happened. + +This re-executes each logged action sequence from the logged initial sim_state and records +whether the episode actually succeeds. Emits a boolean mask aligned to the cache's episode +index, consumed via --success-mask. + +Error is one-sided (no logged failure ever reproduced as a success), so verification only +ever REMOVES episodes from the success pool. +""" +import argparse, os, re, sys +import numpy as np +sys.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: str): + """cache ep_src -> the source episode parquet holding sim_state + actions.""" + m = PAT.search(ep_src) + if not m: + return None + t, b, i, idx = m.groups() + return (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--task", type=int, required=True, help="libero_10 task id shard") + 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("--max-steps", type=int, default=520) + 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) + ep_src, ep_task = m["ep_src"], m["ep_task"] + is_demo, is_succ = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) + # only logged SUCCESSES from ROLLOUTS need checking; demos are ground truth + todo = np.where((ep_task == args.task) & is_succ & ~is_demo)[0] + todo = todo[args.shard::args.num_shards] # within-task sharding for the full corpus + print(f"[verify] task {args.task}: {len(todo)} logged successes to replay", flush=True) + + bench = benchmark.get_benchmark_dict()["libero_10"]() + task = bench.get_task(args.task) + # Physics only: success is the task's goal predicate over sim state, so no + # cameras and no EGL are needed. That drops the GPU requirement entirely and lets + # this run on CPU nodes instead of competing with the training queue. + env = ControlEnv( + bddl_file_name=str(Path(get_libero_path("bddl_files")) + / task.problem_folder / task.bddl_file), + has_renderer=False, has_offscreen_renderer=False, use_camera_obs=False) + + rows = [] + for n, e in enumerate(todo): + p = src_parquet(str(ep_src[e])) + if p is None or not os.path.exists(p): + rows.append((int(e), -1)); continue # -1 = unresolvable, keep as-is + tb = pq.read_table(p, columns=["sim_state", "actions"]) + sim0 = np.asarray(tb["sim_state"][0].as_py(), dtype=np.float64) + acts = np.asarray([a.as_py() for a in tb["actions"]], dtype=np.float64) + env.reset() + env.env.sim.set_state_from_flattened(sim0) + env.env.sim.forward() + ok = False + for s in range(min(len(acts), args.max_steps)): + _o, _r, done, _i = env.step(acts[s]) + if done: + ok = True; break + rows.append((int(e), int(ok))) + if (n + 1) % 25 == 0: + got = [r for _, r in rows if r >= 0] + print(f"[verify] {n+1}/{len(todo)} reproduced {sum(got)}/{len(got)} " + f"({np.mean(got) if got else float('nan'):.3f})", flush=True) + env.close() + idx = np.array([r[0] for r in rows], np.int64) + val = np.array([r[1] for r in rows], np.int64) + np.savez(args.out, ep_index=idx, verified=val, task=args.task) + good = val[val >= 0] + print(f"[verify] task {args.task} DONE: {good.sum()}/{len(good)} reproduced " + f"({good.mean() if len(good) else float('nan'):.3f}); " + f"{int((val < 0).sum())} unresolvable", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_freeze_20261002/verify_successes.sbatch b/frozen/rsm_libero_freeze_20261002/verify_successes.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..8a16c44a98eb9123e19e747bb106293ff6c3556f --- /dev/null +++ b/frozen/rsm_libero_freeze_20261002/verify_successes.sbatch @@ -0,0 +1,20 @@ +#!/bin/bash +#SBATCH --job-name=verify_succ +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 --cpus-per-task=4 --mem=48G +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl PYTHONUNBUFFERED=1 +_G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)" +export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G" +OUT=/data/pulkitag/users/rli14/rsm_libero_runs/verify +mkdir -p $OUT +$B/venvs/rlinf-libero-eval-venv/bin/python \ + /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/verify_successes.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --task $SLURM_ARRAY_TASK_ID --out $OUT/task$SLURM_ARRAY_TASK_ID.npz diff --git a/frozen/rsm_libero_rsmpi/CLAUDE.md b/frozen/rsm_libero_rsmpi/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..d7ef613f133e4f77bd596d9cdf80179d3615f3ca --- /dev/null +++ b/frozen/rsm_libero_rsmpi/CLAUDE.md @@ -0,0 +1,291 @@ +# 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) and +every eval JSON under `rsm_libero_runs/eval/wrong_eval_env/` (143) was produced with the rollout +latents and the evaluator in DIFFERENT feature spaces. Do not cite, compare against, or resume +from them. The results tables further down in this file are retained only as a record of what +was 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 render +resolution 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 reported +number). `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 is +inadmissible 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 latent +must 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 actions +in the environment we evaluate in reproduces its reward labels. If it does not +reproduce, drop the trajectory.** + +This is not a data-cleaning nicety, it is a correctness condition. An offline learner +fits $(s,a,r,s')$ tuples and is then scored in the simulator. If those tuples cannot be +reproduced there, they describe different dynamics than the ones the policy is graded +against, and the learner is being fit to an environment that does not exist. That is the +standard 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, the +diagnostic goal-predicate check passes ~87% — the gap between the two is exactly the +set of trajectories that were honestly recorded but do not reproduce, and **those are +inadmissible 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 states +sbatch --export=ALL,POLICY=$P,NINIT=50,OUT=$E/x.json eval_slurm.sbatch +# B: continuous region +sbatch --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): + +```python +pseed = 7_919_003 + policy_seed*500_009 + tid*1_013 + k # policy sampling RNG +torch.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 RNG +env.reset() # B stops here +if 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-state +vectors (`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` uses +each stored state exactly once. + +**Protocol B** — no override, so object poses come from the task's BDDL placement +regions (`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 a +small 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 more +demanding of the two. (`stock_inside_fresh_support = 0.00` is a consequence of A being +wider, not of a distribution shift.) + +**Neither protocol reproduces the rollout corpus's init distribution.** The corpus was +collected with RLinf's `fresh_reset=true`, documented as "fresh 5 cm inits" — 0.05 +would be wider than both A and B. Our evaluator has no equivalent. Evaluating on the +genuine 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 init +shift under BOTH protocols. + +**Protocol A CANNOT be replicated by varying `SEED`.** `set_init_state` overwrites +whatever `env.reset()` sampled, so `env.seed` has no effect; `np.random.seed` is set but +never 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 500 +episodes. **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 those +same inits. Protocol B draws fresh placements per episode, so `SEED` gives genuine new +episodes 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 depends +on which policy or critic is being evaluated. So with `SEED=0` every arm sees the +identical 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 arms +you 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 collected +from, while the rollout corpus — which trains the critic and the success-pool policies +— comes from a different, wider region. That is a structural advantage for +BC-on-demos and a distribution shift against everything else. Protocol B is the one +where 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**, so +they are comparable by construction. Do not change this venv without re-deriving every +number 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 vendored +installed 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**; every +closed-loop number must come from MIT. + +**The replay divergence is NOT a version mismatch.** Collection and replay share the +venv and the versions, installed before collection and untouched since. Re-executing +logged actions reproduces only ~81% of successes because contact-rich manipulation is +chaotic and the two runs differ in floating-point detail (collection on GPU nodes under +EGL, replay on CPU under osmesa). This is why label correctness must be measured by +evaluating the goal predicate at the LOGGED FINAL state (~87% correct) rather than by +replay (~81%) -- replay conflates label error with non-reproducibility and overstates +it 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 gate +firing 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 on +a *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 of +32 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 gives +those 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 on +it, but it went 0.478 → 0.784 → 0.896 across critics while closed-loop went +0.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 run +through the chunk-10 concat harness scores exactly 0/350. Same signature as the +original 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 NOT +memorise the stock init states.** Protocol A is not inflating the baseline; the bar is +real. The remaining reason to run B is the reverse concern: the critic and the +success-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 beats +BC-on-demos. Using demo *data* without the label is unprivileged; beating +BC-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*. Its +ordering is calibrated only on the proposal's own distribution; outside it the ranking +is actively misleading, not merely uninformative. Corollary: AWR on a pool of uniformly +expert 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_libero +cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo # 5000 eps = 500 demo + 4500 rollout +runs /data/pulkitag/users/rli14/rsm_libero_runs/mit +evals /data/pulkitag/users/rli14/rsm_libero_runs/eval +best critic runs/mit/critic_1M_b995/ckpt_best.pt # band 0.93-0.995, step 110k +BC-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`. diff --git a/frozen/rsm_libero_rsmpi/FINDINGS.md b/frozen/rsm_libero_rsmpi/FINDINGS.md new file mode 100644 index 0000000000000000000000000000000000000000..f24eb52b9eb714b60ed1cb1d3c6dbceaca1c094a --- /dev/null +++ b/frozen/rsm_libero_rsmpi/FINDINGS.md @@ -0,0 +1,344 @@ +# 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, and +no 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.530 +through 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**. The +advantage 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, not +in any policy: it converted the end-effector quaternion to **Euler angles**, while +the latent cache stores robosuite **axis-angle**. Three of the eight +proprioception dimensions were a different physical quantity at every timestep of +every 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 did +not 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 float32 +interpolation where the cache builder rounds to uint8, shifting the latent by up +to 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 nothing +about 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 a +per-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 different +distribution (pi0.5 with SDE noise 0.5, about half failures). Whitening is +catastrophic because per-dim std spans 0.048 to 3.675, so it shrinks the few +informative 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 policy +want 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 value +is excellent throughout; only the action channel is missing. + +**The lever is the action window, not the hop.** Holding chunk at 10 and sweeping +the hop is flat (0.568 / 0.558 / 0.551). Widening the window to 100 frames is the +only thing that moves it. A 10-frame chunk does not determine enough about the +outcome on these tasks. + +This is consistent with the lane's own earlier measurement: over 5 frames the +executed action correlates with the **proprio** delta at |r| up to 0.98 but with +the **visual-latent** delta at only 0.49 (mean 0.10). A mean-pooled PaliGemma +embedding 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 own +precondition is that the proposal must be diverse, because ranking N copies of one +action 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 most +mean-collapsed policy.** Our earlier Q-filter was therefore ranking 32 near-copies +of 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 of +hugging 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 only +variable 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 is +uncorrelated with action quality.** Measured directly with +`probe_perturb.py` on demonstration frames, where the logged chunk is by +construction 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 every +level. + +That alone is ambiguous: it is equally consistent with "Q ignores the action" and +with "the Monte-Carlo estimator cannot resolve the action", because q_recursive +draws fresh flow noise per call. `probe_crn.py` separates them by scoring +candidates under COMMON random numbers, which cancels the shared noise from the +paired 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, roughly +linearly in the perturbation size, and at noise 0.8 the paired response exceeds +the estimator noise. What is missing is the SIGN: perturbing an expert action is +exactly as likely to raise Q as to lower it, even at the smallest perturbation and +even with the shared noise cancelled. + +The occupancy model has therefore learned an action-conditioned map whose +counterfactual gradient is meaningless. It is trained only on (state, action +actually taken, observed future); it never sees a counterfactual action with a +real outcome, so off the logged action it extrapolates confidently and +arbitrarily. Magnitude without direction. + +This explains every downstream result coherently, and explains the PARL sweep +better than "weak critic" does. Selection follows an arbitrary direction, so PARL +effectively picks a random member of its candidate set; the wider the set, the +further off-support the winner, and the worse the policy -- exactly the monotone +collapse 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 one +action is still that action, and it is also the only configuration that stays +inside the region where the model was ever trained. + +It also explains why the 0.568 offline win rate looked survivable: comparing the +logged chunk against a DIFFERENT episode's chunk is dominated by on-support versus +off-support, which the occupancy model does capture. Ranking a policy's own +candidates at the same state is a different question, and there the model has +nothing 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 different +question from ranking a policy's *own* candidates, which is what every extraction +method actually does. `probe_perturb.py` asks the right question directly: does Q +prefer 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 to +the WHOLE corpus, failures included, so its candidate set genuinely contains both +good and bad behaviour, then let the value filter it. A critic that can separate +success-like from failure-like actions should recover demonstration-level +performance 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 the +failure modes the critic was trained on, selection makes things worse, not better. + +That run also shows candidate diversity cannot be bought with data: fitting the +proposal to the whole corpus gives action std 0.056, against 0.053 for +demonstrations only. Flow matching learns the conditional mean regardless of how +varied the data behind it is. The only lever that moved diversity was sampling +temperature, and that pushes candidates off the manifold -- exactly where the +value's response was measured to be arbitrary. On-manifold and diverse are not +jointly 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-out +built on it can rank actions, and the horizon over which a short chunk matters is +too 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 moves +the action win rate off ~0.57. diff --git a/frozen/rsm_libero_rsmpi/FREEZE_COMMIT b/frozen/rsm_libero_rsmpi/FREEZE_COMMIT new file mode 100644 index 0000000000000000000000000000000000000000..3a17f1018fe8d46606e2ef54785b6ed4e30e6a5b --- /dev/null +++ b/frozen/rsm_libero_rsmpi/FREEZE_COMMIT @@ -0,0 +1 @@ +95842af1aa0e0854934b1fbf67f88a2cd6df850e diff --git a/frozen/rsm_libero_rsmpi/README.md b/frozen/rsm_libero_rsmpi/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7c5c121446e48c2825fe96a83772d1a0ee4714b4 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/README.md @@ -0,0 +1,737 @@ +# RSM + importance-sampled OPE on the LIBERO-10 rollout corpus + +Goal: learn an occupancy critic on the pi0.5 LIBERO-10 rollout corpus (43,135 +episodes, ~49.5% success), evaluate a target policy off-policy with the +importance-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 a +null 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 the +demos scores its own action the same as the demo action. Half of this corpus is +failure, 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 no +privileged success ball in this latent, so the read-out is a learned reward +decoder, which is what the image branch of `CLAUDE.md` requires anyway. + +The collapse analysis' central lesson drives the diagnostics: a value that ranks +STATES but cannot rank ACTIONS shows flat batch losses and then falls off a +cliff 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 the +state-level success AUC. + +## The importance-sampling correction + +The behaviour policy is a flow model sampled as an SDE at noise 0.5 and has **no +tractable 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 product +is 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 batch +compares against an action from a *different task*. Once the successor is +action-conditioned that lands off-manifold, and the frozen reward decoder scores +off-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 the +sweep, whose recursion originally used an untrained continuation head. + +With a within-task alternative and 8,192 pairs, the base critic ranks actions +above chance near the goal: 0.61 mean near-terminal win, vs a cross-task control +pinned 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 of +the trajectory to the continuation policy. Meanwhile reach at depth 1 grows from +25 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 the +occupancy was trained on a beta BAND covering the query horizon. Recursion earns +its 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) and +ranks near-terminal actions better (0.667 vs 0.609 over 12,000 pairs), but state +AUC 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 positive +at 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 the +contrastive idea. The 1.0 arm is also the one carrying the unexplained +depth-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 is +genuinely 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 not +there is a policy difference to correct, and never improves discrimination. + +**Cause, and it is an implementation error not a property of the method:** the +target policy was a diagonal Gaussian while the behaviour policy is a flow +sampled as an SDE. The classifier reached 100% accuracy by recognising the +SAMPLER, not the policy, so `log pi/mu` was a parametric-family artifact. This is +open question 2 of the notes -- a likelihood-free ratio only works if both +policies 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 control +that would have been reported as a working correction. + +**Fix:** `FlowPolicy` in `model.py` -- a flow-matching target policy that matches +the behaviour family. AWR weights the per-sample flow-matching loss in place of a +log-density. The fix is confirmed only if classifier accuracy drops below 1.0 AND +the 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 noise +0.5** deliberately injected for exploration; any policy fit to that data without +the same dispersion stays distinguishable from it. Exploration noise at +collection time is exactly what makes the behaviour distribution broad, and +breadth is what makes a target policy trivially separable from it. + +Across 3 critics and 2 policy families the correction consistently shifts values +18-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) and +did not fix the estimator. The clearest tell is the **+0.018 AUC gain in the NULL +gate**: a correction that improves discrimination when there is nothing to +correct is fitting something other than the policy difference. The endpoint +regression 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, the +per-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 CROSSES +ZERO -- after two rounds the policy fits FAILED chunks better than successful +ones. Iterating the loop does not merely fail to improve the policy, it +progressively 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 to +downweight the bad ones. With an advantage this weak (the critic ranks actions at +0.608 near the goal and at chance beyond one hop) that reduces to behaviour +cloning on the full half-failure corpus, undoing the success filtering that made +pi_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 baseline +it was supposed to beat: 0.0160-0.0221 in probability units vs the smolvla null +result'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 not +supported by this measurement.** + +**The correction is NOT what breaks the loop.** Turning it off changes nothing +qualitative: + +| 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-cloned +policy with the failure half of the corpus. + +**Caveat on the AWR arms:** `awr.py` seeded numpy but not torch, so the IS-on and +IS-off arms started from different policies (pi_0 gaps 0.0170 vs 0.0089). Each +arm's trajectory relative to its OWN baseline is valid; the absolute numbers are +not 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 than +successful ones. Restricting the pool slows the collapse a lot but still loses +3/4 of the starting gap. **None improves on its own starting point.** The +advantage from this critic is too weak to drive improvement even when it cannot +dilute. + +### 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 should +help. Inverted. That closes the question. + +## Status + +COMPLETE. Critic works; every off-policy result is negative. See the two FINAL +sections 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 it +to predict a 50-frame hop, so 4/5 of the transition came from actions the critic +never saw. A model-free probe shows the action's contribution to predicting success +rises 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 null +result'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, missing +smoothing, ratio scored over the conditioning window instead of decisions, target +policy at the wrong granularity, and two shape/order bugs). Overlap improved every +time -- classifier bce 0.0035 -> 0.286 -- and the weights still collapsed. + +The identity control explains why. Train two BC policies on **identical data** with +different 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** -- sampler +artifacts and generator fingerprints -- not a density difference. Every ratio it +produced was meaningless. `E_mu[W]` sat at 0.13-0.22 in all six configurations +regardless of critic, family, smoothing or granularity, and the final clean null +gate applied a **0.537 relative value shift where zero is correct**. + +**This RETRACTS the intermediate conclusion** that flow SDE noise 0.5 at collection +made the policies too separable and that the fix was data collection. The +separability was never between policies; less injected noise would not have helped. + +**Actual cause:** discriminative density-ratio estimation does not work on +continuous high-dimensional action chunks in this setup. It is an ESTIMATOR +property, not a data property. The notes' likelihood-free route -- classify instead +of requiring normalised densities -- is not viable here. A working correction needs +a genuine likelihood ratio (tractable densities on both sides) or a correction that +does 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, one +fit to the logged actions by maximum likelihood, densities evaluated AT the logged +action 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 the +endpoint regression needed a x10 calibration. + +**Cause is arithmetic.** At `beta_q=0.99` a hop spans 100 frames = **10 policy +decisions**, so W is a product of 10 factors each with p95 = 4.48. That product is +catastrophically heavy-tailed however well-calibrated each factor is. + +This is precisely the variance argument in the notes, and the real case for myopic +beta: keep each hop SHORT so the product has few factors, then recurse. The tension +is 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 per +product, where the probe still shows +0.0334 action contribution (40% above the +10-frame case). That is the configuration most likely to satisfy both, and it is +the 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 this +machine, scores **0.20 / 0.20 / 0.70 on tasks 0-2 (11/30 = 0.367)** before slurm +preempted it. The environment, EGL rendering, pi0.5 encoder, initial states and +success detection here are therefore sound, and any 0% is ours to fix. Two things +were needed to get it to run: `FL15_TASKS` must name the 10 libero_10 tasks (it +defaults to a 15-task list and the head's task embedding then refuses the +checkpoint), 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 is +trained to predict REWARD, so it keeps what separates success from failure and +discards what an action head needs. On a trained arm the policy beat a +predict-the-mean action baseline by only 14% in MSE (0.1456 vs 0.1701) with a +biased gripper channel. The policy now reads the full 4104-d observation; only +the 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.0374 +against 0.042 for the others) and still scored 0/100. Per-dim std on this corpus +spans 0.048 to 3.675, so whitening shrinks the few high-variance directions by up +to 34x relative to the median and flattens the spectrum. Offline the network +simply relearns its weights; at deployment the small online-vs-cache featurisation +difference is then comparable to the signal that survives. Centering removes the +uninformative common mode (mean vector norm 51.1 against a per-frame deviation of +9.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 this +evaluator is equivalent to the lane's; the 0.07 spread is seed variation at +n=100. + +### The whitening ablation is now clean + +A trained on demonstrations, center-scaled, scores 0.580. The identical run with +per-dim z-scored input scores 0.010. Same data, same head, same budget, same +seed -- only the input scaling differs. Whitening flattens a spectrum whose +per-dim std spans 0.048 to 3.675, shrinking the informative high-variance +directions 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 to +0.380. Both critic arms initialised on successes alone, which starts them 0.11 +below the BC-on-demos bar they must clear. `--init-pool demos_succ` now lets both +arms start from demonstrations plus successful rollouts, so the comparison +measures 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, the +concatenation flow head, chunk 10, batch 1024, 120k steps, seed 0. The critic +arms start from the SAME behaviour clone as arm A, so the comparison isolates the +improvement 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 and +0.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-frame +deviation of 9.0), WHICH frames the statistics come from matters (the rollout +corpus 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 to +34x 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 actually +taken 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 AUC +stays above 0.95. The state value is excellent and the action ranking is near +coin-flip. + +The cause is upstream of the occupancy model. This lane measured that over 5 +frames the executed action correlates with the proprio delta at |r| up to 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-frame chunk produces. Raising +the action-contrastive weight asks the flow to use information the latent does +not 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 and +beta 3 the exponent saturates, so the "soft" weight became a hard filter on the +sign of a 0.568-accurate critic. Standardising the advantage recovers most of the +loss (IQL 0.380 -> 0.490) but does not turn a coin-flip critic into an +improvement. + +## Where RSM stands (2026-09-11) + +Matched: full_demo cache, demo statistics, center scaling, concatenation flow +head, chunk 10, batch 1024, 120k steps, seed 0. C and D start from the SAME +demonstration 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 DOWN +from 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 actions +well (win 0.613 against 0.568 at chunk 10, confirming that over a 10-frame hop the +action barely moves the success probability). It does not rescue the result: BC at +chunk 100 fits far worse (sampled action MSE 0.114 against 0.049) and scores +0.00-0.20 per task over the first six, so the better critic sits on top of a much +weaker 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 measured +cause is upstream: over 5 frames the executed action correlates with the proprio +delta 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 a +good 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 uses +the same cache, demonstration statistics, center scaling, concatenation flow head, +batch 1024, 120k steps, seed 0. Both critic arms start from the SAME demonstration +clone 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 IQL +extraction on this dataset.** Behaviour cloning on the 500 demonstrations wins +outright, 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 and +two 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 at +chunk 100), while reward AUC stays above 0.95. The state value is strong; the +action channel is missing, and it is missing upstream of the occupancy model: over +5 frames the executed action correlates with the proprio delta at |r| up to 0.98 +but with the visual-latent delta at only 0.49 (mean 0.10). A mean-pooled PaliGemma +embedding does not resolve what a 10-frame chunk does. Every consumer of that +ranking therefore lowers a good policy rather than raising it. + +The chunk-100 result is the constructive part: lengthening the action window and +the hop is the one intervention that moved the win rate (0.568 -> 0.613), which +says the horizon, not the read-out, is what starves the signal. Making that +usable needs a policy that is still accurate at a 100-frame chunk; ours loses more +to 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, so +the ranking ceiling at chunk 10 is a property of the data rather than a modelling +failure. And the policy trades the other way: a chunk-100 policy loses more to the +longer chunk (sampled action MSE 0.114 against 0.049) than the critic gains. + +With this featurisation you can have an accurate policy or a discriminative +critic, not both. That is the finding, and it is what any future attempt on this +corpus 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, keep +the argmax, distill into a fresh head. The recipe's own precondition is that the +proposal's samples must be DIVERSE, because ranking N copies of one action cannot +improve 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 most +mean-collapsed one, so the earlier Q-filter run was ranking near-identical +candidates. 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. Every +other factor is fixed: same critic, same N, same distillation, same evaluator. +The only variable is how different the candidates are. If the value function +carried signal, widening the candidate set would help; it destroys the policy +instead, so the ranking is not weak, it is pointed the wrong way. A collapsed +proposal scores near BC simply because selection can do little harm when all 32 +candidates are the same action. + +This is the cleanest isolation of the critic in this lane, and it agrees with the +offline 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 critic +that 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 is +worse 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 to +choose among makes it worse, and removing the variance penalty -- so that +selection follows the raw value rather than staying near the mode -- makes it +worse again. The penalty was masking the problem by keeping choices close to the +proposal's mode, not by adding information. + +The RSM value's preference over actions is anti-correlated with action quality on +this corpus. That is a stronger and more useful statement than "the critic is +weak", and it is what the offline probe was too blunt to show: a 0.568 win rate +against dataset alternatives is dominated by on-support versus off-support, which +says nothing about ranking a policy's own candidates. diff --git a/frozen/rsm_libero_rsmpi/RSMPI_COPY.txt b/frozen/rsm_libero_rsmpi/RSMPI_COPY.txt new file mode 100644 index 0000000000000000000000000000000000000000..d3eb072c01316da94413537d8cbd8c367460ebcf --- /dev/null +++ b/frozen/rsm_libero_rsmpi/RSMPI_COPY.txt @@ -0,0 +1 @@ +copied from rsm_libero_freeze_20261002 on Thu Nov 12 05:31:15 AM UTC 2026 for RSM-pi (opt-in --pi-* flags in train_rsm.py; everything else verbatim) diff --git a/frozen/rsm_libero_rsmpi/audit_logged_goal.py b/frozen/rsm_libero_rsmpi/audit_logged_goal.py new file mode 100644 index 0000000000000000000000000000000000000000..2364662b54d02b29a26149305dc0277149046b78 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/audit_logged_goal.py @@ -0,0 +1,93 @@ +"""Is the label wrong, or did the replay diverge? These are different claims. + +Replaying logged actions tests reproducibility; the corpus is documented as NOT +bit-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 FINAL +sim_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, base64 +import numpy as np +sys.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() diff --git a/frozen/rsm_libero_rsmpi/audit_logged_goal.sbatch b/frozen/rsm_libero_rsmpi/audit_logged_goal.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..c80805de4fa27acd9bf575760baf58bc3f1c3d02 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/audit_logged_goal.sbatch @@ -0,0 +1,17 @@ +#!/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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +OUT=/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.npz diff --git a/frozen/rsm_libero_rsmpi/autoresearch_driver.py b/frozen/rsm_libero_rsmpi/autoresearch_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..d14df344b7ecc8e44e5bb790d64d7a34292f5b98 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/autoresearch_driver.py @@ -0,0 +1,78 @@ +"""Autoresearch driver: reads the local JSON mirror, advances stages, launches the next +cells via ibm_autoresearch.sh. Idempotent (state in a JSON file); run it repeatedly.""" +import json, os, subprocess, sys, glob +sys.argv = ["x"]; sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import ibm_table as T +D = "/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).stdout +cells = 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 r +print(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 2 +s1 = [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" # RSMbd[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 selection +if "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/B +CB = 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 3 +if "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() diff --git a/frozen/rsm_libero_rsmpi/awr.py b/frozen/rsm_libero_rsmpi/awr.py new file mode 100644 index 0000000000000000000000000000000000000000..9705795ffc6f20f9dd5453ff4f1125e3bd8c4bfa --- /dev/null +++ b/frozen/rsm_libero_rsmpi/awr.py @@ -0,0 +1,275 @@ +"""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 fit +on demonstrations only, so Q(demo action) ~= Q(actor's own action) and the mean +absolute advantage was 0.019 -- no gradient. Here half the corpus is failure, so +the advantage has real spread, and the weights are additionally corrected toward +pi 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 the +wrong policy -- the notes flag exactly this. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from model import BCHead, FlowPolicy +from data import LiberoRSMData +from 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() diff --git a/frozen/rsm_libero_rsmpi/bc_arm.py b/frozen/rsm_libero_rsmpi/bc_arm.py new file mode 100644 index 0000000000000000000000000000000000000000..7c9addae5d5a56d9f034ff8d930c9ac6842a4df0 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/bc_arm.py @@ -0,0 +1,153 @@ +"""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 are +independent 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 that +differs across the four arms is where the improvement signal comes from. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import train_bc, policy_features +from 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.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() diff --git a/frozen/rsm_libero_rsmpi/calib_dwm.py b/frozen/rsm_libero_rsmpi/calib_dwm.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3abd90f8d3b4bac3e6c247458a060886d34a7c --- /dev/null +++ b/frozen/rsm_libero_rsmpi/calib_dwm.py @@ -0,0 +1,106 @@ +"""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 real +frames, z-scored tokens/proprio exactly as in training) and writes /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/ --ckpt runs//rsm/DWM/ckpt_best.pt [--max-frames 20000] +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json, time +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from dwm_model import TokenRSMData +from dwm_readout import load_critic_dwm +from 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() diff --git a/frozen/rsm_libero_rsmpi/capture_cpu.sbatch b/frozen/rsm_libero_rsmpi/capture_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7d98b3ed49ab26b28ed51ff90ba1e741f0b7f920 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/capture_cpu.sbatch @@ -0,0 +1,32 @@ +#!/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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export 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=osmesa +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export 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)" diff --git a/frozen/rsm_libero_rsmpi/capture_init_feats.py b/frozen/rsm_libero_rsmpi/capture_init_feats.py new file mode 100644 index 0000000000000000000000000000000000000000..8a352429f3a7af7d1c51d63db6e6cd8de788801e --- /dev/null +++ b/frozen/rsm_libero_rsmpi/capture_init_feats.py @@ -0,0 +1,88 @@ +"""Capture the evaluator's t=0 feature vector without rolling out. + +The question this answers: are the features the closed-loop evaluator actually +feeds the policy in the DEMO region of the cache or the ROLLOUT region? It decides +whether 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 are +required -- reset, one zero step, encode, done. Uses the SAME featurization path as +eval_closed_loop.py (to224 quantisation, axis-angle proprio, cache normalisation); +any deviation would make the comparison meaningless. +""" +from __future__ import annotations +import argparse, importlib.util, sys, os +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.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() diff --git a/frozen/rsm_libero_rsmpi/crn_diag.py b/frozen/rsm_libero_rsmpi/crn_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..dfb5f48d034ff6fea75e08af0b8c32fe050b50e7 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/crn_diag.py @@ -0,0 +1,58 @@ +"""Does the Q arg-max over N near-copy candidates track the critic or the Monte-Carlo +noise? Score the same N candidates twice with fresh seeds, with independent draws and +with common random numbers (crn), and report arg-max agreement and the ratio of +between-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, torch +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, make_policy +from 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 = None +if 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 on +eps = 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}") diff --git a/frozen/rsm_libero_rsmpi/data.py b/frozen/rsm_libero_rsmpi/data.py new file mode 100644 index 0000000000000000000000000000000000000000..725401e7a2f03153b8c2d67856015c225ec0914d --- /dev/null +++ b/frozen/rsm_libero_rsmpi/data.py @@ -0,0 +1,587 @@ +"""Batch sampling over the packed LIBERO-10 rollout cache.""" +from __future__ import annotations +from pathlib import Path +import 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 load +import numpy as np +import 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 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, + } diff --git a/frozen/rsm_libero_rsmpi/df_readout.py b/frozen/rsm_libero_rsmpi/df_readout.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc7a30629084d32f178a38881033f466e5ccb7c --- /dev/null +++ b/frozen/rsm_libero_rsmpi/df_readout.py @@ -0,0 +1,228 @@ +"""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 thing +changed -- 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 reimplemented +here -- it is `df_value.value_of_candidates`, the same function the offline spread gate runs, so an +eval 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 the +same 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 it +needs 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 applied +inside 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 is +never told N, so drawing noise per row would give every candidate its own noise and make the argmax +partly a noise draw. This module therefore calls df_value with `crn_rows=True`: ONE noise draw per +Monte-Carlo index, shared by every row of the call. `crn_seed` from the planner selects it, so a +cell 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 json +import os +import sys +from pathlib import Path + +import numpy as np +import 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: F401 +except 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: E402 +from df_core import DFRise # noqa: E402 +from 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.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 crit diff --git a/frozen/rsm_libero_rsmpi/dinowm_readout.py b/frozen/rsm_libero_rsmpi/dinowm_readout.py new file mode 100644 index 0000000000000000000000000000000000000000..486d6eb2f5acdcc2707183f58e57fbad24a969c7 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/dinowm_readout.py @@ -0,0 +1,168 @@ +"""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 only +worth running if it differs from RSM/DWM in the MODEL and in nothing else. That is why this module +is 60 lines instead of 600: `DINOWMCritic` SUBCLASSES `dwm_readout.DWMCritic` and overrides exactly +two methods, the transition and the hop length. The fold algebra, the hop-policy chaining, the +reward head, the token normaliser, the temperature calibration and the two-stage rescore are the +same 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 transformer +that 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//tokens/tok.f16.npy is +[N, 514, 384] = 2 cameras x (CLS + 256 patches) from dinov2_vits14 at 224 px), and dwm_model.DWM is +already "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 queried +at 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 patch +tokens 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 ESTIMATOR +deterministic. Past the candidate chunk the continuation action comes from the stochastic Gaussian +hop head -- the same object RSM chains with -- so at depth > 1 the M particles are M different action +sequences and Q is the mean over them, with common random numbers across candidates (`_q_once` draws +eps per particle and tiles it over the rows). This module used to force n_particles = 1 at EVERY +depth, so all 855 published DINO-WM MPC cells requested 16 particles and measured one roll-out. Only +depth == 1 is truly deterministic and keeps the force. Search cost therefore scales with M and the +flagship discloses it; the effective count is in the cell's `planner.scorer.effective_particles` and +in 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 therefore +matched 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, which +is why its arm label in verdict_table is "L 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 json +from 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 crit diff --git a/frozen/rsm_libero_rsmpi/dwm_model.py b/frozen/rsm_libero_rsmpi/dwm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b40a26004ba1c4eb7459bca31439ed1ffe446d53 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/dwm_model.py @@ -0,0 +1,562 @@ +"""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 and +proprio 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, and +its own 9-d residual on the future side, read out by a 424->9 head). The MLP cells model the +pooled 1545-d state, which INCLUDES proprio, and the Stage-2 hop policy consumes the pooled +state of the sampled future, so the DWM successor has to predict proprio too. Cost: 2 tokens +out of 1030. + +No learned encoder: DINO is frozen and its tokens are the state (Stage 1 "no learned encoder +in either case"). +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import json +from pathlib import Path +import numpy as np +import torch +import torch.utils.checkpoint +import torch.nn as nn +import torch.nn.functional as F + +from model import beta_fourier, time_embed +from data import truncated_geometric_future + +# token layout of cache//tokens/tok.f16.npy [N, 514, 384] +N_PATCH = 256 +D_TOK = 384 +TOK_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.01 +Z_CLIP = 10.0 +RHO_FLOOR = 0.01 +Y_CLIP = 10.0 +STATS_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//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 /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 root diff --git a/frozen/rsm_libero_rsmpi/dwm_readout.py b/frozen/rsm_libero_rsmpi/dwm_readout.py new file mode 100644 index 0000000000000000000000000000000000000000..73ed820711fa7a32933ff5ed072d49283bb90d3d --- /dev/null +++ b/frozen/rsm_libero_rsmpi/dwm_readout.py @@ -0,0 +1,314 @@ +"""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//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//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_logit +q_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//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 4 +particles, rescores the top-16 by q_logit with 64 particles, returns full-length arrays. + +reward="goal_clf", reward_path="runs//goal_clf/clf.pt" (PRIVILEGED ABLATION: env success via state +replay, which RISE's baselines never see): the read-out reward is the standalone GOAL-STATE +classifier (train_goal_clf.py; env-success-by-replay label) on the pooled 1545-d state of every sampled future +instead 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 noise +tensor shared by all B rows (candidates), so Q differences between candidates at the same +state 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 annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +from pathlib import Path +import numpy as np +import 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= 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 /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)) diff --git a/frozen/rsm_libero_rsmpi/dwm_readout_timing.py b/frozen/rsm_libero_rsmpi/dwm_readout_timing.py new file mode 100644 index 0000000000000000000000000000000000000000..0ccaf606d13d147733aac7b7f1af917748464569 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/dwm_readout_timing.py @@ -0,0 +1,78 @@ +"""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 the +agreement between the rankings. Candidates: `--chunks hop` loads stream B's hop head (runs//hop/flow) if its +loader is importable, else (default `logged`) 128 logged chunks from 128 random frames of the val split -- the timing +does not depend on which chunks are used. Writes /readout_timing.json. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json, time +from pathlib import Path +import numpy as np +import torch + +from dwm_model import TokenRSMData +from 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() diff --git a/frozen/rsm_libero_rsmpi/encode_parquet.py b/frozen/rsm_libero_rsmpi/encode_parquet.py new file mode 100644 index 0000000000000000000000000000000000000000..82cc23b17d2ccc2841c2b58aac33eb066bc4a781 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/encode_parquet.py @@ -0,0 +1,83 @@ +"""Encode RLinf LeRobot parquet rollouts straight from their RECORDED frames into the +per-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 at +cam_res 256 and RLinf stores them upright, i.e. already in the evaluator's serving +orientation), 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_BASE +points at, so this is how a LIBERO-finetuned pi0.5 (lerobot/pi05_libero_base) becomes the +feature encoder for a new cache; the tag is recorded in every episode. + +usage: OGPO_PI05_BASE= encode_parquet.py --root --out + [--shard i --num-shards n] [--task-file lib10_tasks.txt] +Layout in: /task{t}_block{b}/rank_*/id_{i}/data/chunk-*/episode_{k:06d}.parquet +Layout out: //ep_t{t}_b{b}_i{i}_{k:06d}.npz (same as the existing corpus) +""" +from __future__ import annotations +import argparse, io, os, re, sys, glob, time +from pathlib import Path +import numpy as np +sys.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() diff --git a/frozen/rsm_libero_rsmpi/encode_t5.py b/frozen/rsm_libero_rsmpi/encode_t5.py new file mode 100644 index 0000000000000000000000000000000000000000..daffa4c3fea458ba1fb4305ad79f386e7fcc5114 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/encode_t5.py @@ -0,0 +1,52 @@ +"""Encode the ten LIBERO-10 instructions with T5 and cache the vectors. + +Replaces the learned nn.Embedding(n_task) conditioning. An index lookup carries no +information about WHAT the task is: it cannot transfer to a held-out instruction, and it +gives the network a free shortcut so nothing forces the visual latent to represent the +instruction. 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 does +from libero.libero import benchmark +b = 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, T5Tokenizer +tok = 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 named +import itertools +D = 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}") diff --git a/frozen/rsm_libero_rsmpi/encode_t5.sbatch b/frozen/rsm_libero_rsmpi/encode_t5.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..2831f345740df0507115747322b2ff02fd1b36e5 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/encode_t5.sbatch @@ -0,0 +1,16 @@ +#!/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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +export 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.npz diff --git a/frozen/rsm_libero_rsmpi/eval_closed_loop.py b/frozen/rsm_libero_rsmpi/eval_closed_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..278b28a32e077e551b36368a06b488f823f99e71 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/eval_closed_loop.py @@ -0,0 +1,1025 @@ +"""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 is +deliberate: the 0.584 +- 0.025 `bcdemos_m120k` bar was produced by +`09032026_latent_head_eval.py`, and a success rate measured by any other harness +is 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 in +either direction evaluates a good policy off-distribution and is +indistinguishable from the policy being bad, so the stats travel with the run +rather than being reconstructed here. +""" +from __future__ import annotations +import argparse, hashlib, importlib.util, json, os, sys +from pathlib import Path +import numpy as np +import 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, ConcatFlowPolicy +from 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 ") + 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 .partial.t 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 .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 .progress.t; 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() diff --git a/frozen/rsm_libero_rsmpi/eval_slurm.sbatch b/frozen/rsm_libero_rsmpi/eval_slurm.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..df5bb495a8fd02c30d28cebaf63eff4d6d31bc01 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/eval_slurm.sbatch @@ -0,0 +1,90 @@ +#!/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 pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +VENV=$B/venvs/rlinf-libero-eval-venv +PY=$VENV/bin/python + +export REPO_PATH=$B/external/rlinf +export PYTHONPATH="$REPO_PATH:${PYTHONPATH:-}" +export LIBERO_CONFIG_PATH=$S/libero_config +export ROBOT_PLATFORM=LIBERO +export LIBERO_TYPE=standard +export MUJOCO_GL=egl +export 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=false +export PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export HF_HUB_OFFLINE=1 +# the lane head sizes its task embedding from FL15_TASKS; harmless for our heads +export FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')" + +CRITIC=${CRITIC:-} # only needed when the policy reads latent features +POLICY=${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 $RC diff --git a/frozen/rsm_libero_rsmpi/extract_clips.py b/frozen/rsm_libero_rsmpi/extract_clips.py new file mode 100644 index 0000000000000000000000000000000000000000..49c7156358b664f2ac1e6561cd869e3cd9eb4a05 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/extract_clips.py @@ -0,0 +1,98 @@ +"""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 comparable +by eye. Demos come from the stock LIBERO hdf5 (agentview_rgb); rollouts from the source +corpus PNGs. +""" +import argparse, base64, io, json, os, re +import 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() diff --git a/frozen/rsm_libero_rsmpi/extract_viz.py b/frozen/rsm_libero_rsmpi/extract_viz.py new file mode 100644 index 0000000000000000000000000000000000000000..deaf3f38c9537b9919abfdcdbbe33d05b61d906c --- /dev/null +++ b/frozen/rsm_libero_rsmpi/extract_viz.py @@ -0,0 +1,90 @@ +"""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, and +LIBERO's datasets/ dir is not installed), so frames are rollout-only. End-effector +trajectories come from proprio and exist for all three slices, which makes them the one +directly comparable view. +""" +import argparse, base64, io, json, os, re, sys +import 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() diff --git a/frozen/rsm_libero_rsmpi/ibm_autoresearch.sh b/frozen/rsm_libero_rsmpi/ibm_autoresearch.sh new file mode 100644 index 0000000000000000000000000000000000000000..1686be6ff31b2f1ea9b0d36062de34ecddad992c --- /dev/null +++ b/frozen/rsm_libero_rsmpi/ibm_autoresearch.sh @@ -0,0 +1,53 @@ +#!/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 __s7e7_V. +# usage: ibm_autoresearch.sh train | stage1 | bcsel | stage2 | stage3 [prop] [policy] [hop] +set -uo pipefail +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; CACHE=$IB/cache/full_r256 +S="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.pt +V="SEED=7, QFCRN=1, QFPART=${QFPART:-256}"; VN=20 +sub(){ echo "$(NINIT=$VN ./ibm_cell.sh "$1" "$2" 7 1 "$3" &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:?}" in +train) # 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 | 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=${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: 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" "" +# 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 .json. Wall-clock per cell drops ~10x. +set -uo pipefail +NAME=${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/logs +Q=${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_ONLY +printf '%s' \"$COMMON\" > $E/$NAME.cell # manifest: the env this cell was submitted with (retries read it) +[ \"\${MANIFEST_ONLY:-0}\" = 1 ] && exit 0 +for 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>&1 +done +bsub -G $G -q $Q -n 4 -M 32G -J ${NAME}_asm -o $L/${NAME}_asm.out -e $L/${NAME}_asm.err -env \"$COMMON, ASM=1\" $IB/code/ibm_eval.sh 2>&1 | grep -o '<[0-9]*>' +" &1 | grep -v Authorized | tr -d '<>' diff --git a/frozen/rsm_libero_rsmpi/ibm_crn_diag.sh b/frozen/rsm_libero_rsmpi/ibm_crn_diag.sh new file mode 100644 index 0000000000000000000000000000000000000000..3673365859d935fa2a4881daebb02446a8e310f0 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/ibm_crn_diag.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# CRN diagnostic on IBM: no env, one GPU. Reuses ibm_eval.sh's environment block. +set -uo pipefail +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256 +PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python +export RSM_TASKS_FILE=$IB/lib10_tasks.txt RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktree +export OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorch +export OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.model +export LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard MUJOCO_GL=egl PYOPENGL_PLATFORM=egl +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1 +export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/" +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}" diff --git a/frozen/rsm_libero_rsmpi/ibm_eval.sh b/frozen/rsm_libero_rsmpi/ibm_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff827ea2ff7e6a2227efae3e15242f94913875f6 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/ibm_eval.sh @@ -0,0 +1,51 @@ +#!/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 pipefail +IB=/proj/dmfexp/zwhong/rsm_libero +export RSM_TASKS_FILE=/proj/dmfexp/zwhong/rsm_libero/lib10_tasks.txt +export RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktree +export OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorch +export OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.model +export LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export 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 here +export RSM_NO_ENV_CLOSE=1 +export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/" +PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python +TASKS=${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 .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 0 +fi +RETRY=${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.sh +fi +exit $RC diff --git a/frozen/rsm_libero_rsmpi/ibm_eval_depth.sh b/frozen/rsm_libero_rsmpi/ibm_eval_depth.sh new file mode 100644 index 0000000000000000000000000000000000000000..8538e9e112ae5a851875c3f484f1863365aa29d9 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/ibm_eval_depth.sh @@ -0,0 +1,7 @@ +#!/bin/bash +# beta-hop sweep cells only. usage: ibm_eval_depth.sh [seeds] [depths] +set -uo pipefail +PROPRUN=${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/logs +S="ssh -o BatchMode=yes -o ConnectTimeout=20" +sub(){ ./ibm_cell.sh "$1" "$2" "$3" "$4" "$5"; } \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/ibm_eval_matrix.sh b/frozen/rsm_libero_rsmpi/ibm_eval_matrix.sh new file mode 100644 index 0000000000000000000000000000000000000000..e6815716a8c82bd8babf545b55f70ea555edf398 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/ibm_eval_matrix.sh @@ -0,0 +1,25 @@ +#!/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 [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 ladder +set -uo pipefail +PROPRUN=${1:?proposer run dir}; TAG=${2:?tag}; SEEDS=${3:-0}; HOPRUN=${4:-} # 4th arg: latent hop policy run dir -> depth 2/3 cells +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logs +S="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; done +for 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" +done diff --git a/frozen/rsm_libero_rsmpi/ibm_eval_matrix_last.sh b/frozen/rsm_libero_rsmpi/ibm_eval_matrix_last.sh new file mode 100644 index 0000000000000000000000000000000000000000..64f816fb0862ade1651f8bc819b8c82a7fabb13d --- /dev/null +++ b/frozen/rsm_libero_rsmpi/ibm_eval_matrix_last.sh @@ -0,0 +1,38 @@ +#!/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 pipefail +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256 +PROPL=$R/BCdemo_f/policy_last.pt; HOP=$R/HOPdemo_f/policy_r1.pt +CB=$R/qsg_f/ckpt_best.pt; CL=$R/qsg_f/ckpt.pt +BON="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" 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 pipefail +PH=${1:?phase} +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +S="ssh -o BatchMode=yes -o ConnectTimeout=20" +IB=/proj/dmfexp/zwhong/rsm_libero; ID=/proj/dmfexp/zwhong/data +CACHE=$IB/cache/full_r256; RUNS=$IB/runs/full_r256; LOGS=$RUNS/logs +PYT=/proj/dmfexp/zwhong/venvs/lerobot_env/bin/python +MIT_META=/data/pulkitag/users/rli14/rsm_libero_cache/full_r256 +case $PH in +sync-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_f +BCroll_f|$BC --pool rollsucc --out $RUNS/BCroll_f" + MASKED="BCrollv_f|$BC --pool rollsucc --success-mask $MASK --out $RUNS/BCrollv_f +BCsucc_f|$BC --pool succ --success-mask $MASK --out $RUNS/BCsucc_f +qind_f|$CR --reward-mode subgoal_ind --subgoal-dir $SG --success-mask $MASK --out $RUNS/qind_f +qsg_f|$CR --reward-mode subgoal --subgoal-dir $SG --success-mask $MASK --out $RUNS/qsg_f" + [ "$PH" = train-nomask ] && LIST="$NOMASK" || LIST="$MASKED" + # /dev/null | xargs -n1 basename | sed 's/.json$//'" /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; echo "manifest $1"; return; fi + echo "$have" | grep -qx "$1" && return + echo "$(./ibm_cell.sh "$1" "$2" "$3" "$4" "$5" .cell) written at submission. Idempotent; run repeatedly. +set -uo pipefail +ssh -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=0 +active=$(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>&1 +done; echo "resubmitted $n task jobs"' diff --git a/frozen/rsm_libero_rsmpi/ibm_table.py b/frozen/rsm_libero_rsmpi/ibm_table.py new file mode 100644 index 0000000000000000000000000000000000000000..6d75bc360954a9a72b5b2e97da025dfe9806782f --- /dev/null +++ b/frozen/rsm_libero_rsmpi/ibm_table.py @@ -0,0 +1,70 @@ +"""Assemble the RSM-vs-baselines table from IBM eval JSONs, with PAIRED tests. + +Cells are named __s[e]_. Two cells with the same +proposer, pseed/evalseed and protocol share initial conditions (init_sha256 per episode), +so arm differences are paired: McNemar exact test on discordant episodes, plus the paired +throughput 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, sys +from collections import defaultdict +from 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() diff --git a/frozen/rsm_libero_rsmpi/ibm_train_onpol.sh b/frozen/rsm_libero_rsmpi/ibm_train_onpol.sh new file mode 100644 index 0000000000000000000000000000000000000000..279fc81ee5a1dce4b6ec7a037f310f96568aa0eb --- /dev/null +++ b/frozen/rsm_libero_rsmpi/ibm_train_onpol.sh @@ -0,0 +1,15 @@ +#!/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 pipefail +IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256 +PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/python +export PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1 +export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/" +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:?}" diff --git a/frozen/rsm_libero_rsmpi/iql.py b/frozen/rsm_libero_rsmpi/iql.py new file mode 100644 index 0000000000000000000000000000000000000000..fe469a03b5cdb80951551a8f0b59a8e910b28edd --- /dev/null +++ b/frozen/rsm_libero_rsmpi/iql.py @@ -0,0 +1,259 @@ +"""IQL critic + policy extraction, as the standard offline-RL baseline for RSM. + +Matched to the RSM arms on purpose: same latents, same reward labels, same +FlowPolicy class, same AWR extraction, same offline score. The ONLY thing that +differs is where the advantage comes from -- IQL's expectile-regressed Q - V +versus RSM's occupancy read-out. That is what makes the comparison a test of the +critic 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 method +gets a reward the other does not see. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from model import Encoder, mlp, FlowPolicy +from data import LiberoRSMData +from is_ope import make_policy, policy_nll, train_bc, policy_features +from 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() diff --git a/frozen/rsm_libero_rsmpi/is_ope.py b/frozen/rsm_libero_rsmpi/is_ope.py new file mode 100644 index 0000000000000000000000000000000000000000..19669c6e2149659a8f181413ecee924968f24348 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/is_ope.py @@ -0,0 +1,727 @@ +"""Importance-sampled off-policy evaluation of Q^pi with the RSM occupancy. + +Implements the notes' Sections 7-9 without ever needing a normalized action +density, which matters because the behavior policy here is a pi0.5 flow model +sampled 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 whose +occupancy we can compute directly. Take pi := "mu restricted to episodes that +succeed". d^pi is then estimable by fitting the occupancy on successes only, +while the IS estimate reweights the all-data model. If the corrected estimate +does not move toward the success-only reference, the weights are not working and +no policy is trained on them. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json, time +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from types import SimpleNamespace + +from model import (Encoder, RewardHead, OccFlow, RatioNet, EndpointRatio, + BCHead, FlowPolicy) +from data import LiberoRSMData +from 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} diff --git a/frozen/rsm_libero_rsmpi/label_full.sbatch b/frozen/rsm_libero_rsmpi/label_full.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..bb83d02365a8d65ee13748d92bb2c2c8013aff8f --- /dev/null +++ b/frozen/rsm_libero_rsmpi/label_full.sbatch @@ -0,0 +1,20 @@ +#!/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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +T=$((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 diff --git a/frozen/rsm_libero_rsmpi/label_subgoals.py b/frozen/rsm_libero_rsmpi/label_subgoals.py new file mode 100644 index 0000000000000000000000000000000000000000..4d1ca82f4b3e449c56ea613ce064715a1945e400 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/label_subgoals.py @@ -0,0 +1,91 @@ +"""Per-frame satisfied-subgoal count: a reward that IS a function of state. + +gamma_s**(frames-to-success) is not a function of the state -- it depends on the +episode's outcome and the frame index, so identical configurations carry targets +differing by ~1.4 sigma of the reward range (measured). A regressor fit to it can only +recover P(success|z). + +Each LIBERO goal is a conjunction of BDDL predicates over object geometry. Evaluating +them per frame gives r(s) = (#conjuncts satisfied)/K: deterministic in the state, +identical for identical states, and defined for EVERY frame of EVERY episode including +failures -- which today contribute only zeros. + +Emits per-episode arrays aligned to the cache's frame index. +""" +import argparse, os, re, sys +import numpy as np +sys.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("--shard", type=int, default=0); ap.add_argument("--num-shards", type=int, default=1) + ap.add_argument("--stride", type=int, default=5, + help="evaluate every Nth frame and hold; subgoal count is piecewise " + "constant and changes a handful of times per episode") + 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) + task, lo, hi = m["ep_task"], m["ep_from"], m["ep_to"] + demo = m["ep_demo"].astype(bool) + todo = np.where((task == args.task) & ~demo)[0] # rollouts; demos have no parquet + todo = todo[args.shard::args.num_shards] # within-task sharding for the full corpus + b = benchmark.get_benchmark_dict()["libero_10"]() + t = b.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"] + K = len(goal) + print(f"[label] task {args.task}: {len(todo)} rollouts, K={K} conjuncts {goal}", flush=True) + + eps, vals = [], [] + for n, e in enumerate(todo): + p = src_parquet(m["ep_src"][e]) + nfr = int(hi[e] - lo[e]) + if p is None: + eps.append(int(e)); vals.append(np.full(nfr, -1, np.int8)); continue + tb = pq.read_table(p, columns=["sim_state"]) + N = min(tb.num_rows, nfr) + out = np.zeros(nfr, np.int8) + last = 0 + for i in range(0, N, args.stride): + st = np.asarray(tb["sim_state"][i].as_py(), np.float64) + env.env.sim.set_state_from_flattened(st); env.env.sim.forward() + last = sum(bool(env.env._eval_predicate(g)) for g in goal) + out[i:min(i + args.stride, nfr)] = last + if N < nfr: out[N:] = last + eps.append(int(e)); vals.append(out) + if (n + 1) % 100 == 0: + f = np.concatenate(vals) + print(f"[label] {n+1}/{len(todo)} mean subgoals {f[f>=0].mean():.3f}", flush=True) + env.close() + np.savez_compressed(args.out, ep=np.array(eps), + vals=np.array(vals, dtype=object), K=K, task=args.task) + f = np.concatenate(vals); f = f[f >= 0] + print(f"[label] task {args.task} DONE: {len(eps)} eps, mean subgoals " + f"{f.mean():.3f}/{K}, frames at 0/1/2 = " + f"{np.bincount(f, minlength=K+1).tolist()}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/label_subgoals.sbatch b/frozen/rsm_libero_rsmpi/label_subgoals.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..a8c493c9b91e9ce5f1acb9b98296cd1ad11e326f --- /dev/null +++ b/frozen/rsm_libero_rsmpi/label_subgoals.sbatch @@ -0,0 +1,17 @@ +#!/bin/bash +#SBATCH --job-name=label_sub +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=osmesa PYTHONUNBUFFERED=1 +OUT=/data/pulkitag/users/rli14/rsm_libero_runs/subgoals; 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/users/rli14/rsm_libero_cache/full_demo \ + --task $SLURM_ARRAY_TASK_ID --out $OUT/task$SLURM_ARRAY_TASK_ID.npz --stride 5 diff --git a/frozen/rsm_libero_rsmpi/lane_control.sbatch b/frozen/rsm_libero_rsmpi/lane_control.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..6e27aca6de89d6d047e29472a687039215370393 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/lane_control.sbatch @@ -0,0 +1,36 @@ +#!/bin/bash +#SBATCH --job-name=lane_ctl +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=64G +#SBATCH --time=12: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 +# CONTROL: the lane's OWN bcdemos policy through the lane's OWN evaluator on THIS +# machine. If it reproduces ~0.584 the env, EGL, encoder and init states here are +# sound and any 0% we see is our training's fault. If it does not, the harness is. +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +W=$B/.claude/worktrees/08312026_jvq_recap_worktree/scripts/rlinf_jvq +PY=$B/venvs/rlinf-libero-eval-venv/bin/python +export REPO_PATH=$B/external/rlinf +export PYTHONPATH="$REPO_PATH:${PYTHONPATH:-}" +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export 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 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +# The head's task embedding is sized by FL15_TASKS. It defaults to the 15-task +# libero_90 list, which cannot load a 10-task libero_10 checkpoint. +export FL15_TASKS="$(tr '\n' ',' < /data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')" +echo "[ctl] FL15_TASKS has $(echo "$FL15_TASKS" | tr ',' '\n' | grep -c .) tasks" +$PY $W/09032026_latent_head_eval.py \ + --ckpt /data/pulkitag/users/rli14/laneP_bc_v1/bcdemos_h1024d4.best.pt \ + --norm /data/pulkitag/users/rli14/laneP_bc_v1/bcdemos_h1024d4.norm.npz \ + --suite libero_10 --tasks 0,1,2,3,4,5,6,7,8,9 --n-init 10 \ + --max-steps 520 --execute 10 --seed 0 \ + --out /data/pulkitag/users/rli14/rsm_libero_runs/lane_control2/LANE_CONTROL.json +echo "[ctl] rc=$?" diff --git a/frozen/rsm_libero_rsmpi/launch_full_r256.sh b/frozen/rsm_libero_rsmpi/launch_full_r256.sh new file mode 100644 index 0000000000000000000000000000000000000000..d08174658b91a411416d8df2a04ec1ed2059690f --- /dev/null +++ b/frozen/rsm_libero_rsmpi/launch_full_r256.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# The full-corpus, one-latent-space wave (williamd4112/gen_q#252). Submits a slurm DAG: +# pack -> stats -> {BC-demos, BC-rollsucc} -> n=500 evals A/B +# pack -> {label x40, verify x40} -> mask -> {BC-succ, BC-rollsucc-masked, critics ind/sg} -> evals +# critic qind_f -> IQL (q-only, same frozen encoder) -> BoN8 evals +# BC-demos + critics/IQL -> best-of-8 argmax / random / medoid, 3 policy seeds +# Every training job is --requeue + --resume; every eval is --requeue. No --export anywhere +# (tig-cpu kills exported jobs); values ride in the environment. +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +SR=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation/launchers/slurm_remote.sh +GPUP=vision-pulkitag-h200,vision-pulkitag-a100,vision-pulkitag-l40s,vision-pulkitag-a6000 +MEMP=vision-pulkitag-l40s,vision-pulkitag-a100,vision-pulkitag-h200 +Q=vision-pulkitag-free-cycles +CACHE=/data/pulkitag/users/rli14/rsm_libero_cache/full_r256 +RUNS=/data/pulkitag/users/rli14/rsm_libero_runs/mit; O=/data/pulkitag/users/rli14/rsm_libero_runs/eval +SG=/data/pulkitag/users/rli14/rsm_libero_runs/subgoals_full +MASK=/data/pulkitag/users/rli14/rsm_libero_runs/verify_full/verified_mask.npz +LEDGER=$O/launch_full_r256.ledger; : > $LEDGER +sub(){ local id; id=$($SR exec "cd $G && $1" 2>&1 | grep -o "Submitted batch job [0-9]*" | grep -o "[0-9]*$"); echo "$id $2" >> $LEDGER; echo "$id"; } + +# ---- data ---- +J_PACK=$(sub "sbatch --qos=$Q --partition=$MEMP $G/pack_full_r256.sbatch" pack_full_r256) +J_STATS=$(sub "sbatch --dependency=afterok:$J_PACK --qos=$Q --partition=$MEMP $G/stats_full.sbatch" stats_full) +J_LAB=$(sub "sbatch --dependency=afterok:$J_PACK $G/label_full.sbatch" label_full_x40) +J_VER=$(sub "sbatch --dependency=afterok:$J_PACK $G/verify_full.sbatch" verify_full_x40) +J_MASK=$(sub "sbatch --dependency=afterok:$J_LAB:$J_VER $G/merge_full.sbatch" merge_full) + +# ---- trainers ---- +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" +train(){ sub "CMD='$2' sbatch --job-name=$1 --dependency=afterok:$3 --qos=$Q --partition=$GPUP --requeue --time=20:00:00 $G/train_slurm.sbatch" "train $1"; } +J_BCD=$(train BCd_f "$BC --pool demos --out $RUNS/BCd_f" $J_STATS) +J_BCR=$(train BCroll_f "$BC --pool rollsucc --out $RUNS/BCroll_f" $J_STATS) +J_BCRV=$(train BCrollv_f "$BC --pool rollsucc --success-mask $MASK --out $RUNS/BCrollv_f" $J_STATS:$J_MASK) +J_BCS=$(train BCsucc_f "$BC --pool succ --success-mask $MASK --out $RUNS/BCsucc_f" $J_STATS:$J_MASK) +J_QI=$(train qind_f "$CR --reward-mode subgoal_ind --subgoal-dir $SG --success-mask $MASK --out $RUNS/qind_f" $J_STATS:$J_MASK) +J_QS=$(train qsg_f "$CR --reward-mode subgoal --subgoal-dir $SG --success-mask $MASK --out $RUNS/qsg_f" $J_STATS:$J_MASK) +IQ="iql.py --cache $CACHE --critic $RUNS/qind_f/ckpt_best.pt --out $RUNS/iql_f --chunk 10 --norm-pool demos --feat-scale center --policy-features raw --reward-mode subgoal_ind --subgoal-dir $SG --success-mask $MASK --tau 0.7 --gamma 0.99 --iql-steps 60000 --q-only 1 --in-ram 1 --seed 0" +J_IQL=$(train iql_f "$IQ" $J_QI) # same encoder as the RSM arm: only the source of Q differs + +# ---- evals: n=500, protocols A and B, evaluator at 256 ---- +ev(){ # name dep policy extra-env pseed + for P in A B; do F=0; [ $P = B ] && F=1 + sub "POLICY=$3 CAMRES=256 FRESH=$F NINIT=50 PSEED=$5 $4 OUT=$O/F_${1}_s$5_$P.json sbatch --job-name=e${1}$5$P --dependency=afterok:$2 --qos=$Q --partition=$GPUP --requeue --time=10:00:00 $G/eval_slurm.sbatch" "eval $1 seed$5 $P" >/dev/null + done; } +PROP=$RUNS/BCd_f/policy_r1.pt +for s in 0 1 2; do ev BCd $J_BCD $PROP "" $s; done +ev BCroll $J_BCR $RUNS/BCroll_f/policy_r1.pt "" 0 +ev BCrollv $J_BCRV $RUNS/BCrollv_f/policy_r1.pt "" 0 +ev BCsucc $J_BCS $RUNS/BCsucc_f/policy_r1.pt "" 0 +BON="QFILTER=8 QFBETA=0.98 QFDEPTH=1 QFPES=0 QFGATE=0" +for s in 0 1 2; do + ev RSMind_bon8 $J_BCD:$J_QI $PROP "CRITIC=$RUNS/qind_f/ckpt_best.pt $BON SELECT=argmaxq" $s + ev IQL_bon8 $J_BCD:$J_IQL $PROP "QFCKPT=$RUNS/iql_f/iql_q.pt $BON SELECT=argmaxq" $s + ev medoid8 $J_BCD $PROP "$BON SELECT=medoid" $s +done +ev RSMsg_bon8 $J_BCD:$J_QS $PROP "CRITIC=$RUNS/qsg_f/ckpt_best.pt $BON SELECT=argmaxq" 0 +ev random8 $J_BCD $PROP "$BON SELECT=random" 0 +echo "ledger: $LEDGER"; cat $LEDGER diff --git a/frozen/rsm_libero_rsmpi/lewm_data.py b/frozen/rsm_libero_rsmpi/lewm_data.py new file mode 100644 index 0000000000000000000000000000000000000000..29b2d0aff3cb14782451244266a0903bfaaddab1 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/lewm_data.py @@ -0,0 +1,177 @@ +"""Streaming frame windows for LeWM (gen_q#268) -- no image pack, by hard constraint. + +/proj/dmfexp runs at 99% full (5.6 T free of 350 T, and rsm_rise's own runs/ is 5.6 T), so an 84x84 +two-camera image pack of all seven tasks (~29 GB) is not something this lane may write. LeWM needs +pixels -- it is a JEPA that predicts its OWN encoder's embeddings, so feeding it frozen DINO features +would turn it into DINO-WM -- therefore the frames are streamed out of the task's source HDF5 at +training time instead. + +WHY AN EPISODE-RESIDENT BUFFER AND NOT RANDOM READS. A batch of 128 windows of 4 frames x 2 cameras +is 1024 separate 21 kB HDF5 reads; over this filesystem that is seconds per step and 100k steps is +out of reach. Whole episodes are contiguous, so the loader keeps `resident` episodes in RAM (each is +~300 frames x 2 cams x 21 kB = 13 MB, so 96 episodes is ~1.2 GB), draws every window from those, and +retires one episode every `refresh_every` steps. The buffer therefore turns over completely every +`resident * refresh_every` steps -- 768 at the defaults, i.e. ~130 full passes over a 100k-step run. + +ALIGNMENT. Frames come from the HDF5 but ACTIONS and the reward LABEL come from the packed cache, so +LeWM reads the same actions and the same provenance label as every other scorer in the table: + * cache//meta.npz ep_from/ep_to/ep_len/ep_src/ep_success (ep_src = the HDF5 demo key) + * cache//act.f32.npy (stride 1, cache row order) + * the label is ep_success, which is exactly what train_rsm.py --reward-mode dense turns into r=1 + on every frame of an expert episode -- the membership head's label. +The cache was packed from this HDF5 at stride 1 (PACK.json), so cache row ep_from[e]+j is frame j of +demo ep_src[e]; the constructor asserts that for every episode it loads. + +The episode split is the same permutation LiberoRSMData(seed=seed) uses, so LeWM's validation +episodes are the ones every other scorer held out. +""" +from __future__ import annotations + +import json +from collections import OrderedDict +from pathlib import Path + +import numpy as np +import torch + +CAMS = ("agentview_image", "robot0_eye_in_hand_image") + + +class StreamingFrameData: + def __init__(self, cache, hdf5="", chunk: int = 8, ctx: int = 3, n_preds: int = 1, + resident: int = 96, refresh_every: int = 8, val_frac: float = 0.1, + seed: int = 0, cams=CAMS, res: int = 84): + import h5py # imported here: the scorer never needs it + self.h5py = h5py + self.root = Path(cache) + m = np.load(self.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_success = m["ep_success"].astype(bool) + assert "ep_src" in m.files, f"{cache}/meta.npz has no ep_src: cannot map frames to the HDF5" + self.ep_src = [str(s) for s in m["ep_src"]] + self.adim = int(m["adim"]) + self.n_ep = len(self.ep_len) + self.act = np.ascontiguousarray(np.load(self.root / "act.f32.npy", mmap_mode="r")) + self.chunk, self.ctx, self.n_preds = chunk, ctx, n_preds + self.T = ctx + n_preds + self.cams, self.res = tuple(cams), res + self.d_act = chunk * self.adim + if not hdf5: + hdf5 = json.loads((self.root / "PACK.json").read_text())["src"] + self.hdf5 = str(hdf5) + self.f = h5py.File(self.hdf5, "r") + + 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:]) + # only episodes long enough to hold one window are usable + ok = self.ep_len >= self.T + self.train_eps = np.array([e for e in self.train_eps if ok[e]], np.int64) + self.val_eps = np.array([e for e in self.val_eps if ok[e]], np.int64) + self.resident, self.refresh_every = int(resident), int(refresh_every) + self.buf = {"train": OrderedDict(), "val": OrderedDict()} + self._n_draw = 0 + print(f"[lewm_data] {self.n_ep} eps ({len(self.train_eps)} train / {len(self.val_eps)} val), " + f"label positives {self.ep_success.mean():.4f}, frames from {self.hdf5}", flush=True) + + # ---- episode I/O --------------------------------------------------------------------------- + def _load_ep(self, e): + """[T, 2, res, res, 3] uint8 for one episode, read whole (contiguous in the HDF5).""" + g = self.f["data"][self.ep_src[e]]["obs"] + arrs = [] + for c in self.cams: + a = np.asarray(g[c][:]) + arrs.append(a) + n = int(self.ep_to[e] - self.ep_from[e]) + assert arrs[0].shape[0] == n, (f"episode {self.ep_src[e]}: HDF5 has {arrs[0].shape[0]} frames, " + f"cache has {n} -- the row map would be wrong") + assert arrs[0].shape[1:3] == (self.res, self.res), \ + f"{self.cams[0]} is {arrs[0].shape[1:3]}, expected {(self.res, self.res)}" + return np.stack(arrs, 1) + + def _ensure(self, split, rng): + pool = self.train_eps if split == "train" else self.val_eps + buf = self.buf[split] + want = self.resident if split == "train" else min(self.resident, max(8, len(pool))) + while len(buf) < want: + cand = [int(e) for e in pool if int(e) not in buf] + if not cand: + break + e = int(rng.choice(cand)) + buf[e] = self._load_ep(e) + # retire the oldest and pull one new episode in, so the buffer keeps turning over + if split == "train" and self.refresh_every > 0 and self._n_draw % self.refresh_every == 0 \ + and len(pool) > len(buf): + buf.popitem(last=False) + cand = [int(e) for e in pool if int(e) not in buf] + if cand: + e = int(rng.choice(cand)) + buf[e] = self._load_ep(e) + + # ---- windows ------------------------------------------------------------------------------- + def _chunk_at(self, t, e): + """the flattened `chunk`-step action window at cache row t, padded by repeating the last.""" + hi = int(self.ep_to[e]) + take = min(self.chunk, hi - t) + a = np.asarray(self.act[t:t + take], np.float32) + if take < self.chunk: + a = np.concatenate([a, np.repeat(a[-1:], self.chunk - take, 0)], 0) + return a.reshape(-1) + + def sample(self, batch, rng, split="train", device="cpu"): + """-> frames [B,T,6,res,res] uint8, actions [B,T,d_act], label [B], plus bookkeeping.""" + self._n_draw += 1 + self._ensure(split, rng) + buf = self.buf[split] + eps = np.array(list(buf.keys()), np.int64) + w = (self.ep_len[eps] - self.T + 1).astype(np.float64) + w = np.maximum(w, 1.0) + w /= w.sum() + pick = rng.choice(len(eps), size=batch, p=w) + fr = np.empty((batch, self.T, 2, self.res, self.res, 3), np.uint8) + ac = np.empty((batch, self.T, self.d_act), np.float32) + lab = np.empty(batch, np.float32) + for j, pi in enumerate(pick): + e = int(eps[pi]) + n = int(self.ep_len[e]) + j0 = int(rng.integers(0, max(n - self.T + 1, 1))) + fr[j] = buf[e][j0:j0 + self.T] if n >= self.T else \ + np.concatenate([buf[e], np.repeat(buf[e][-1:], self.T - n, 0)], 0)[:self.T] + base = int(self.ep_from[e]) + j0 + for i in range(self.T): + ac[j, i] = self._chunk_at(min(base + i, int(self.ep_to[e]) - 1), e) + lab[j] = float(self.ep_success[e]) + # [B,T,2,H,W,3] -> [B,T,6,H,W]: the two cameras become channels (declared deviation 1) + f6 = torch.from_numpy(fr).permute(0, 1, 2, 5, 3, 4).reshape(batch, self.T, 6, self.res, self.res) + return {"frames": f6.to(device, non_blocking=True), + "actions": torch.from_numpy(ac).to(device, non_blocking=True), + "label": torch.from_numpy(lab).to(device, non_blocking=True)} + + def close(self): + try: + self.f.close() + except Exception: + pass + + +def frames_from_obs(obs_t, cams=CAMS, res=84): + """The scorer's side of the SAME transform: the planner's obs dict -> [B,6,res,res] uint8. + + The planner hands float CHW images in [0,1] (robomimic ObsUtils.process_frame); LeWM's encoder + expects raw uint8 because it does the /127.5 - 1 itself, so the round trip back to uint8 here is + what makes scoring see the same inputs training did. + """ + out = [] + for c in cams: + x = obs_t[c] + x = torch.as_tensor(x) + if x.ndim == 4 and x.shape[-1] == 3: # NHWC -> NCHW + x = x.permute(0, 3, 1, 2) + if x.dtype.is_floating_point: + x = (x.clamp(0, 1) * 255.0).round().to(torch.uint8) + out.append(x) + return torch.cat(out, 1) diff --git a/frozen/rsm_libero_rsmpi/lewm_model.py b/frozen/rsm_libero_rsmpi/lewm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..67b705107fcaab82afd76e8047365f186760b45d --- /dev/null +++ b/frozen/rsm_libero_rsmpi/lewm_model.py @@ -0,0 +1,237 @@ +"""LeWorldModel (LeWM), ported to torch from the JAX reference for gen_q#268. + +Reference implementation: /proj/dmfexp/zwhong/projs/wt-i97-beta/rsm_vla/lewm.py (flax) and its +`rsm_vla/models.py:Encoder`. This is a line-for-line port of the *method*: JEPA next-embedding +prediction with an AdaLN-zero causal predictor, collapse prevented by SIGReg alone -- NO +stop-gradient and NO EMA target encoder, which is the recipe's defining choice and the easiest thing +to "fix" by accident into a different method. Every constant below is the reference's: + + CTX = 3 history frames the predictor conditions on + N_PREDS = 1 next-step target only + LAMBDA = 0.09 SIGReg weight + LR = 5e-5, WD = 1e-3, global-norm clip 1.0 (AdamW) + LEWM_SIZES (emb_dim, depth, heads, mlp_dim); "m" is the official ~15M config + +WHY A PORT AND NOT THE ORIGINAL. The reference is JAX/flax; rsm_rise's venv has torch only (no +jax), and the reference's shell runners point at a clone that no longer exists on this filesystem. +The port therefore has to be checked rather than trusted: tests/test_lewm_port.py asserts the SIGReg +statistic against an independent numpy implementation and asserts the AdaLN-zero block is the +identity at initialisation (which is what "zero" means and what makes the recipe trainable). + +DECLARED DEVIATIONS from the reference, all forced by the rsm_rise observation and protocol: + 1. INPUT is 84x84 with SIX channels -- the two RISE cameras (agentview, wrist) stacked -- not one + 64x64 RGB frame. The encoder is resolution-general (stride-2 stages until the spatial size is + <= 4), so 84px needs 5 stages where 64px needs 4; nothing else changes. + 2. ACTIONS are the 8-step chunk the RISE actor emits, flattened, not a single step: that is the + candidate the planner ranks, so it is what the world model has to be conditioned on. + 3. The reward probe is a SINGLE-argument probe on the predicted embedding, trained by BCE on the + provenance/membership label, rather than the reference's (z, z_goal) pair probe. gen_q#268 + fixes the reward for every scorer to that label, and a goal-conditioned probe would be reading a + different reward than RSM, TD-Flow and DINO-WM do. +""" +from __future__ import annotations + +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F + +CTX = 3 +N_PREDS = 1 +LAMBDA = 0.09 +LR = 5e-5 +WD = 1e-3 +CLIP = 1.0 +PROBE_LR = 3e-4 +# (emb_dim, depth, heads, mlp_dim) +LEWM_SIZES = {"s": (128, 4, 8, 1024), "m": (192, 6, 16, 2048), "l": (384, 8, 16, 3072)} + + +class Encoder(nn.Module): + """uint8 image -> z_dim latent. Resolution-general: stride-2 stages until spatial <= 4. + + Port note: the reference divides by 127.5 and subtracts 1 INSIDE the encoder, so the caller + hands it raw uint8. Keeping that boundary here means the scorer can feed the planner's frames + through the identical transform the trainer used. + """ + + CHANS = (32, 64, 128, 256, 512, 512, 512) + + def __init__(self, z_dim=192, in_ch=6, res=84): + super().__init__() + layers, c_in, s = [], in_ch, res + i = 0 + while s > 4: + c_out = self.CHANS[min(i, len(self.CHANS) - 1)] + layers += [nn.Conv2d(c_in, c_out, 3, stride=2, padding=1), + nn.GroupNorm(8, c_out), nn.SiLU()] + c_in, s, i = c_out, (s + 1) // 2, i + 1 + self.conv = nn.Sequential(*layers) + self.flat = c_in * s * s + self.fc1 = nn.Linear(self.flat, 512) + self.fc2 = nn.Linear(512, z_dim) + self.n_stages, self.out_res = i, s + + def forward(self, img_u8): + x = img_u8.float() / 127.5 - 1.0 + x = self.conv(x).flatten(1) + return self.fc2(F.silu(self.fc1(x))) + + +class ProjMLP(nn.Module): + """Dense(hidden) -> LayerNorm -> gelu -> Dense(out_dim), as in the reference.""" + + def __init__(self, in_dim, out_dim, hidden=2048): + super().__init__() + self.l1 = nn.Linear(in_dim, hidden) + self.ln = nn.LayerNorm(hidden) + self.l2 = nn.Linear(hidden, out_dim) + + def forward(self, x): + return self.l2(F.gelu(self.ln(self.l1(x)))) + + +class ActionEmbedder(nn.Module): + """Dense(A) -> Dense(4*emb) -> silu -> Dense(emb), applied per time step.""" + + def __init__(self, a_dim, emb_dim, mlp_scale=4): + super().__init__() + self.l0 = nn.Linear(a_dim, a_dim) + self.l1 = nn.Linear(a_dim, mlp_scale * emb_dim) + self.l2 = nn.Linear(mlp_scale * emb_dim, emb_dim) + + def forward(self, a): + return self.l2(F.silu(self.l1(self.l0(a)))) + + +def modulate(x, shift, scale): + return x * (1.0 + scale) + shift + + +class AdaLNBlock(nn.Module): + """One AdaLN-zero transformer block: the conditioning head is zero-initialised, so the block is + the IDENTITY at initialisation and the predictor starts as a pass-through of the embedding. + That is what makes this recipe trainable without a target network, so the zero init is not a + detail -- tests/test_lewm_port.py asserts it.""" + + def __init__(self, dim, heads, mlp_dim, dropout=0.0): + super().__init__() + self.ln1 = nn.LayerNorm(dim, elementwise_affine=False) + self.ln2 = nn.LayerNorm(dim, elementwise_affine=False) + self.heads, self.inner = heads, 64 * heads + self.to_qkv = nn.Linear(dim, 3 * self.inner, bias=False) + self.to_out = nn.Linear(self.inner, dim) + self.mlp = nn.Sequential(nn.Linear(dim, mlp_dim), nn.GELU(), nn.Linear(mlp_dim, dim)) + self.ada = nn.Linear(dim, 6 * dim) + nn.init.zeros_(self.ada.weight) + nn.init.zeros_(self.ada.bias) + self.dropout = dropout + + def forward(self, x, c, mask): + sh1, sc1, g1, sh2, sc2, g2 = self.ada(F.silu(c)).chunk(6, -1) + h = modulate(self.ln1(x), sh1, sc1) + B, T, _ = h.shape + q, k, v = self.to_qkv(h).chunk(3, -1) + q, k, v = (t.view(B, T, self.heads, 64).transpose(1, 2) for t in (q, k, v)) + o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, + dropout_p=self.dropout if self.training else 0.0) + x = x + g1 * self.to_out(o.transpose(1, 2).reshape(B, T, self.inner)) + return x + g2 * self.mlp(modulate(self.ln2(x), sh2, sc2)) + + +class ARPredictor(nn.Module): + """Causal transformer over the CTX embedding history, conditioned on the action embedding.""" + + def __init__(self, emb_dim, depth, heads, mlp_dim, num_frames=CTX, dropout=0.0): + super().__init__() + self.pos = nn.Parameter(torch.randn(1, num_frames, emb_dim) * 0.02) + self.blocks = nn.ModuleList([AdaLNBlock(emb_dim, heads, mlp_dim, dropout) for _ in range(depth)]) + self.norm = nn.LayerNorm(emb_dim) + mask = torch.tril(torch.ones(num_frames, num_frames, dtype=torch.bool)) + self.register_buffer("mask", mask[None, None], persistent=False) + + def forward(self, emb_ctx, act_ctx): + x = emb_ctx + self.pos[:, : emb_ctx.shape[1]] + m = self.mask[..., : x.shape[1], : x.shape[1]] + for blk in self.blocks: + x = blk(x, act_ctx, m) + return self.norm(x) + + +class LeWM(nn.Module): + """encoder -> projector -> causal predictor -> pred_proj, JEPA-style.""" + + def __init__(self, size="m", a_dim=56, in_ch=6, res=84, ctx=CTX, dropout=0.0): + super().__init__() + emb, depth, heads, mlp = LEWM_SIZES[size] + self.emb_dim, self.ctx, self.a_dim = emb, ctx, a_dim + self.encoder = Encoder(emb, in_ch=in_ch, res=res) + self.projector = ProjMLP(emb, emb) + self.pred_proj = ProjMLP(emb, emb) + self.act_enc = ActionEmbedder(a_dim, emb) + self.predictor = ARPredictor(emb, depth, heads, mlp, num_frames=ctx, dropout=dropout) + + def embed(self, frames_u8): + """frames [B,T,C,H,W] uint8 -> embeddings [B,T,D] (encoder + projector).""" + B, T = frames_u8.shape[:2] + z = self.encoder(frames_u8.reshape(B * T, *frames_u8.shape[2:])) + return self.projector(z).view(B, T, -1) + + def step_emb(self, emb_hist, act_hist): + """[B,ctx,D] history + [B,ctx,A] actions -> the NEXT embedding [B,D].""" + h = self.predictor(emb_hist, self.act_enc(act_hist)) + return self.pred_proj(h)[:, -1] + + def forward(self, frames_u8, actions): + """frames [B,ctx+N_PREDS,C,H,W] uint8, actions [B,ctx+N_PREDS,A] + -> (pred [B,ctx,D], emb [B,ctx+N_PREDS,D]). `emb` is NOT detached anywhere: the target of + the prediction loss is the live encoder's own output, which is the recipe.""" + emb = self.embed(frames_u8) + act = self.act_enc(actions) + h = self.predictor(emb[:, : self.ctx], act[:, : self.ctx]) + return self.pred_proj(h), emb + + +def sigreg_stat(emb_tbd, generator=None, knots=17, num_proj=1024, A=None): + """Epps-Pulley SIGReg statistic, ported verbatim from the reference. + + emb_tbd: [T, B, D]. Projects onto `num_proj` random unit directions and compares the empirical + characteristic function of each projection against a standard normal's on a trapezoid grid over + t in [0, 3]. Scaled by B and averaged over time slices, exactly as the reference does. + This term is the ONLY thing preventing representation collapse in LeWM -- there is no target + network -- so its weight (LAMBDA = 0.09) and its scaling are load-bearing. + """ + dev, dt_ = emb_tbd.device, emb_tbd.dtype + T, B, D = emb_tbd.shape + t = torch.linspace(0.0, 3.0, knots, device=dev, dtype=dt_) + dt = 3.0 / (knots - 1) + w = torch.full((knots,), 2 * dt, device=dev, dtype=dt_) + w[0] = dt + w[-1] = dt + phi = torch.exp(-t ** 2 / 2.0) + weights = w * phi + # `A` is injectable ONLY so test_lewm_port.py can check the statistic against an independent + # implementation on the same projections; training always draws it fresh, as the reference does. + if A is None: + A = torch.randn(D, num_proj, device=dev, dtype=dt_, generator=generator) + A = A / A.norm(dim=0, keepdim=True) + x_t = (emb_tbd @ A).unsqueeze(-1) * t # [T,B,P,K] + err = (x_t.cos().mean(-3) - phi) ** 2 + x_t.sin().mean(-3) ** 2 # [T,P,K] + return ((err @ weights) * B).mean() + + +class RewardProbe(nn.Module): + """p(membership | z): logit MLP on one embedding (see the deviation note in the module docstring).""" + + def __init__(self, emb_dim, hidden=512): + super().__init__() + self.net = nn.Sequential(nn.Linear(emb_dim, hidden), nn.SiLU(), + nn.Linear(hidden, hidden), nn.SiLU(), nn.Linear(hidden, 1)) + + def forward(self, z): + return self.net(z).squeeze(-1) + + +def make_optimizer(model, lr=LR, wd=WD): + return torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=wd) diff --git a/frozen/rsm_libero_rsmpi/lewm_readout.py b/frozen/rsm_libero_rsmpi/lewm_readout.py new file mode 100644 index 0000000000000000000000000000000000000000..2b32779e285284abd8896deb6051faa9a923604b --- /dev/null +++ b/frozen/rsm_libero_rsmpi/lewm_readout.py @@ -0,0 +1,265 @@ +"""LeWM read-out: best-of-N scoring of RISE-actor action chunks with a LeWM world model (gen_q#268). + +Q(s, A) for a candidate chunk A at the current frame s: + + z_0 = projector(encoder(s)) one frame, repeated to fill the ctx history + z_k+1 = pred_proj(predictor(hist_k, act_k)) one LeWM step under the chunk + c_k = sigmoid(probe(z_k)) the membership reward probe + Q = c_1 (mode "d1", L = 1) + = c_1 + (1-c_1) g^h (c_2 + (1-c_2) g^h (...)) (mode "fold", L hops, h = chunk frames) + +The fold is the SAME reach-or-continue algebra RSM, DWM and DINO-WM use, so the L>1 columns differ +in the model and not in the read-out arithmetic. + +TWO DEVIATIONS, BOTH FORCED AND BOTH DECLARED + 1. HISTORY. LeWM conditions on 3 frames; the planner hands a scorer the SINGLE current frame + (rsm_planner.plan_get_action: `obs_t = {k: v[:, -1] ...}`). The history is therefore filled by + repeating that frame. Changing the planner to keep a frame stack would change what EVERY other + scorer sees, so this is the only choice that keeps the comparison matched. + 2. CONTINUATION PAST THE FIRST HOP is sampled from the SAME stochastic Gaussian hop head RSM and + DINO-WM chain with, but conditioned on the pooled DINO state of the CURRENT observation rather + than of the rolled latent (gen_q#288, owner 2026-09-25: "should definitely be M different chains + for DINOWM and LeWM with stochastic continuations just like RSM"). The staleness is forced, not + chosen: LeWM predicts in ITS OWN embedding space, so a rolled state has no pooled DINO vector and + a policy over DINO states cannot be queried there; training a BC head on LeWM's latent would make + the continuation a DIFFERENT actor from RSM's, which is the one thing #288 asks to hold fixed. + So the action DISTRIBUTION is the same actor's, the conditioning state is s_0 for every hop, and + that is stated in the table. What this REPLACES is a zero-order hold -- every hop re-used the + candidate chunk -- which made the roll deterministic and every LeWM MPC cell a single rollout + even though it requested 16 (630 published cells; see `effective_particles` below). + `hop_policy=None` still gives the old zero-order hold at n_particles=1, byte-identical, so the + published M=1 arms remain reproducible. + + 3. PARTICLES. With (2) the roll is stochastic, so M particles are M different action sequences and + Q is the mean over them, with common random numbers across candidates (particle m's eps is drawn + once per hop and tiled over the candidate rows, exactly as dwm_readout._q_once does). Only + depth == 1 has no continuation to sample and stays deterministic at n_particles = 1. + +PROPRIO is not an input to LeWM (the reference is pixels + actions), so the `pr` half of the +scorer's input tuple is accepted and ignored rather than being silently concatenated somewhere. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from lewm_model import LeWM, RewardProbe + + +class LeWMCritic: + """The interface robomimic's RSMScorer expects of a backend core (see rsm_scorer.DWMBackend).""" + + def __init__(self, ck, device): + a = ck["arch"] + self.device = torch.device(device) + self.arch = dict(a) + self.chunk = int(a["chunk"]) + self.adim = int(a["adim"]) + self.d_act = int(ck["d_act"]) + self.res = int(a["res"]) + self.ctx = int(a["ctx"]) + self.in_ch = int(a["in_ch"]) + self.model = LeWM(size=a["size"], a_dim=self.d_act, in_ch=self.in_ch, res=self.res, + ctx=self.ctx).to(self.device) + self.probe = RewardProbe(int(a["emb_dim"])).to(self.device) + self.model.load_state_dict(ck["lewm"]) + self.probe.load_state_dict(ck["probe"]) + for m in (self.model, self.probe): + m.eval() + for p in m.parameters(): + p.requires_grad_(False) + self.config = dict(ck.get("config", {})) + self.step = int(ck.get("step", -1)) + self.q_action_winrate = ck.get("q_action_winrate", float("nan")) + self.temperature = 1.0 + self.calib = None + self.hop_frames = float(self.chunk) + self.cams = tuple(ck.get("cams", ("agentview_image", "robot0_eye_in_hand_image"))) + self.autocast = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) \ + if self.device.type == "cuda" else (lambda: torch.autocast("cpu", enabled=False)) + + # ------------------------------------------------------------------------------------------ + def _gen(self, seed): + g = torch.Generator(device=self.device) + g.manual_seed(int(0 if seed is None else seed)) + return g + + def n_eff_particles(self, n_particles, depth, mode, hop_policy=None): + """DISTINCT roll-outs a (n_particles, depth, mode) cell actually averages -- see deviation 3. + + Recorded in the eval cell's `planner.scorer.effective_particles` so verdict_table's arm key can + carry the MEASURED M rather than the requested one. Before gen_q#288 this critic collapsed + every count to 1, so 630 published LeWM cells requested 16 and measured one rollout; without + this field a repaired M=16 cell would pool with them. + """ + d = 1 if mode == "d1" else int(depth or 1) + if d <= 1 or hop_policy is None: + return 1 + return int(n_particles or 1) + + @staticmethod + def _pooled_of(inp): + """The pooled 1545-d DINO state of the CURRENT observation, if the scorer carried it. + + rsm_scorer hands LeWM `(frames, proprio)` historically and `(frames, proprio, pooled_raw)` + since gen_q#288, because the hop head is a policy over pooled DINO states (deviation 2). A + 2-tuple therefore means "no hop head on this cell" and takes the zero-order-hold path. + """ + return inp[2] if isinstance(inp, (tuple, list)) and len(inp) > 2 else None + + def _prep(self, inp, a_chunk): + img = inp[0] if isinstance(inp, (tuple, list)) else inp + x = torch.as_tensor(img).to(self.device) + if x.dtype.is_floating_point: # the planner's frames are float in [0,1] + x = (x.clamp(0, 1) * 255.0).round().to(torch.uint8) + assert x.ndim == 4 and x.shape[1] == self.in_ch, \ + f"LeWM expects [B,{self.in_ch},{self.res},{self.res}] frames, got {tuple(x.shape)}" + aa = torch.as_tensor(a_chunk).to(self.device).float().view(x.shape[0], -1) + assert aa.shape[1] == self.d_act, f"a_chunk must be [B,{self.d_act}], got {tuple(aa.shape)}" + return x, aa + + @torch.no_grad() + def q(self, inp, a_chunk, beta=None, n_particles=16, crn_seed=None, depth=1, mode="d1", + 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, the mean over `n_particles` stochastic roll-outs (gen_q#288; see deviations 2-3). + + `beta` is inert -- LeWM has no discount, and the per-hop discount uses hop_frames = the action + chunk. `flow_steps` is inert (no ODE). `hop_policy(pooled_raw [R,1545], eps [R,d_act]) -> + a_chunk [R,d_act]` is the continuation actor: the SAME callable rsm_scorer builds for DWM and + DINO-WM. With hop_policy=None the roll falls back to the pre-#288 zero-order hold at one + particle, byte-identical, so the published M=1 arms stay reproducible. + """ + if mode == "d1": + depth = 1 + elif mode not in ("fold", "mpc", "mpc_disc"): + # gen_q#273: the MPC read-outs, identical in meaning to dwm_readout's -- the SAME open-loop + # roll-out this method already performs, combined as terminal / discounted-sum instead of + # through the beta-hazard fold. Additive: d1 and fold are untouched. + raise ValueError(f"mode {mode!r}: use 'd1', 'fold', 'mpc' or 'mpc_disc'") + depth = max(int(depth), 1) + n = self.n_eff_particles(n_particles, depth, mode, hop_policy) + if return_lcb is not None: + # The particle distribution now EXISTS at n > 1, but the caller also needs the (q, ql, lcb) + # triple rsm_scorer.DWMBackend returns, and LeWMBackend does not build it. Refuse rather + # than return a mean where a quantile was asked for. + raise ValueError("plan_score=conformal_lcb is not implemented for the LeWM backend " + "(gen_q#288 gives it a particle bundle; the LCB plumbing is not wired)") + x, aa = self._prep(inp, a_chunk) + pooled = self._pooled_of(inp) + B = x.shape[0] + T = float(self.temperature if temperature is None else temperature) + d_act = int(getattr(hop_policy, "d_act", self.d_act)) if hop_policy is not None else self.d_act + # CRN: one eps per (hop, particle), drawn UP FRONT so it is independent of the micro-batching + # and shared by every candidate -- particle m of every row sees the same continuation noise, + # which is the variance-reduction convention dwm_readout._q_once uses (`.repeat(B, 1)` there, + # an index by row % n here because the micro loop slices the repeat_interleave'd rows). + eps = None + if n > 1 or (hop_policy is not None and depth > 1): + if hop_policy is not None and pooled is None: + raise ValueError( + "LeWM's continuation actor is a policy over the POOLED 1545-d DINO state, but the " + "scorer passed inp=(frames, proprio) without it. rsm_scorer.RSMScorer._inputs must " + "hand LeWM (frames, proprio, pooled_raw) whenever a hop head is loaded (gen_q#288).") + g = self._gen(crn_seed) + eps = torch.randn(max(depth - 1, 1), n, d_act, device=self.device, generator=g) + xr = x.repeat_interleave(n, 0) if n > 1 else x + ar = aa.repeat_interleave(n, 0) if n > 1 else aa + pr_pool = None if pooled is None else (pooled.repeat_interleave(n, 0) if n > 1 else pooled) + R = B * n + logits, cs = [], [] + m = max(int(micro), 1) + for i in range(0, R, m): + j = min(i + m, R) + xi, ai = xr[i:j], ar[i:j] + pid = torch.arange(i, j, device=self.device) % n # which particle each row is + with self.autocast(): + z0 = self.model.embed(xi.unsqueeze(1))[:, 0] # one frame -> [b, D] + hist = z0.unsqueeze(1).repeat(1, self.ctx, 1) # deviation 1: repeat it + acts = ai.unsqueeze(1).repeat(1, self.ctx, 1) # hop 1 IS the candidate + lg_i, cs_i = [], [] + for k in range(depth): + with self.autocast(): + z = self.model.step_emb(hist, acts) + lg = self.probe(z).float() + lg_i.append(lg) + cs_i.append(torch.sigmoid(lg / T)) + if k == depth - 1: + break + hist = torch.cat([hist[:, 1:], z.unsqueeze(1).float()], 1) + if hop_policy is not None: + # deviation 2: fresh draw from RSM's OWN hop head, conditioned on s_0's pooled state + nxt = torch.as_tensor(hop_policy(pr_pool[i:j].float(), eps[k][pid])).to( + self.device).float().view(j - i, -1) + if nxt.shape[1] != self.d_act: + raise ValueError(f"hop_policy returned {nxt.shape[1]}-d chunks, LeWM needs " + f"{self.d_act}") + else: + nxt = acts[:, -1] # pre-#288 zero-order hold + acts = torch.cat([acts[:, 1:], nxt.unsqueeze(1)], 1) + logits.append(torch.stack(lg_i, 0)) + cs.append(torch.stack(cs_i, 0)) + lg_all = torch.cat(logits, 1) # [depth, R] + cs_all = torch.cat(cs, 1) + # COMBINE OVER HOPS FIRST, AVERAGE OVER PARTICLES LAST -- the order dwm_readout._q_once uses. + # Averaging the per-hop c_k over particles first and folding the means afterwards is a + # different (and biased) estimator for every non-linear read-out, i.e. for the fold. + if mode == "d1": + q = cs_all[0] + elif mode in ("mpc", "mpc_disc"): + h = self.hop_frames + if mode == "mpc": + q = cs_all[-1] + else: + w = [float(gamma) ** (h * k) for k in range(depth)] + tot = float(sum(w)) + q = sum(wk * cs_all[k] for k, wk in enumerate(w)) / tot + else: + h = self.hop_frames + q = torch.zeros_like(cs_all[-1]) + for k in range(depth - 1, -1, -1): + c = cs_all[k] + 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_all[-1], nan=0.0).view(B, n).mean(1) + out = (q, q_logit) if return_logit else q + if return_hops: + return out, [c.view(B, n) for c in cs_all] + return out + + def hop_sample(self, x, eps): + raise RuntimeError("LeWMCritic has no hop head of its own; the continuation actor is passed in " + "as `hop_policy` by rsm_scorer.LeWMBackend (gen_q#288) and is a policy over " + "POOLED DINO states, so sample it there, not here") + + def describe(self): + return {"backend": "lewm", "size": self.arch.get("size"), "emb_dim": self.arch.get("emb_dim"), + "ctx": self.ctx, "chunk": self.chunk, "hop_frames": self.hop_frames, + "step": self.step, "q_action_winrate": self.q_action_winrate, + # gen_q#288: the TRANSITION is deterministic, the ROLL-OUT is not (the continuation is + # sampled from the hop head past hop 1), so this flag now names the transition only. + "deterministic": True, "deterministic_transition": True, + "stochastic_continuation": True} + + +def load_critic_lewm(path, device="cuda", calib="auto") -> LeWMCritic: + ck = torch.load(str(path), map_location="cpu", weights_only=False) + m = str(ck.get("model", "?")) + if m != "lewm": + raise RuntimeError(f"{path} is a {m!r} checkpoint, not a LeWM one (train_lewm.py writes " + f"model='lewm')") + crit = LeWMCritic(ck, device) + 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"[lewm_readout] calib.json unreadable ({e}); T=1", flush=True) + return crit diff --git a/frozen/rsm_libero_rsmpi/make_video_report.py b/frozen/rsm_libero_rsmpi/make_video_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8187fc90470f1eac3969e78708de4de06c32f299 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/make_video_report.py @@ -0,0 +1,94 @@ +"""Turn the eval matrix (video frames + per-episode outcomes) into a report: +mp4 per episode, one collage per cell (10 tasks x first/mid/last frame, outcome-coded), +and an HTML index with the SR table and links. Cells are named by the eval job: + __, e.g. r256_demo = BC_rollsucc @256 from exact demo inits.""" +import argparse, json, glob, os +from pathlib import Path +import numpy as np + + +def mp4(frames, path, fps=15): + import imageio + w = imageio.get_writer(path, fps=fps, codec="libx264", quality=7, macro_block_size=1) + for f in frames: w.append_data(f) + w.close() + + +def collage(cell_dir, out_png, title): + from PIL import Image, ImageDraw + files = sorted(glob.glob(f"{cell_dir}/t*_e*.npz"), + key=lambda p: (int(Path(p).stem.split("_")[0][1:]), int(Path(p).stem.split("_")[1][1:]))) + by_task = {} + for f in files: + z = np.load(f, allow_pickle=True); by_task.setdefault(int(z["task"]), []).append((f, z)) + tasks = sorted(by_task); n_ep = max(len(v) for v in by_task.values()) if by_task else 0 + S = 96; cols = 3 * n_ep; rows = len(tasks) + im = Image.new("RGB", (cols * S + 60, rows * S + 24), (245, 245, 245)); dr = ImageDraw.Draw(im) + dr.text((4, 4), title, fill=(0, 0, 0)) + for r, t in enumerate(tasks): + dr.text((4, 24 + r * S + S // 2 - 6), f"t{t}", fill=(0, 0, 0)) + for e, (f, z) in enumerate(by_task[t]): + fr = z["frames"]; ok = bool(z["success"]); n = len(fr) + for j, k in enumerate((0, n // 2, n - 1)): + tile = Image.fromarray(fr[k]).resize((S, S)) + x, y = 60 + (e * 3 + j) * S, 24 + r * S + im.paste(tile, (x, y)) + dr.rectangle([x, y, x + S - 1, y + S - 1], outline=(0, 170, 0) if ok else (200, 0, 0), width=3) + dr.text((60 + e * 3 * S + 2, 24 + r * S + 2), "OK" if ok else f"fail {int(z['steps'])}", + fill=(0, 120, 0) if ok else (180, 0, 0)) + im.save(out_png) + return len(files), sum(bool(np.load(f, allow_pickle=True)["success"]) for f in files) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--video-root", default="/data/pulkitag/users/rli14/rsm_libero_runs/video") + ap.add_argument("--eval-root", default="/data/pulkitag/users/rli14/rsm_libero_runs/eval") + ap.add_argument("--cells", default="r256_lib,r256_demo,r256_roll,r128_demo,d128_lib,d256_lib") + ap.add_argument("--out", required=True) + args = ap.parse_args() + out = Path(args.out); (out / "mp4").mkdir(parents=True, exist_ok=True) + legend = {"r256_lib": "BC_rollsucc @256, LIBERO stock inits (protocol A)", + "r256_demo": "BC_rollsucc @256, EXACT demo initial states (hdf5 states[0])", + "r256_roll": "BC_rollsucc @256, EXACT rollout initial states (its own training inits)", + "r128_demo": "BC_rollsucc @128 (old evaluator), EXACT demo initial states", + "d128_lib": "BC-on-demos @128 (old evaluator, the 0.584 bar), LIBERO inits", + "d256_lib": "BC-on-demos @256 (new evaluator), LIBERO inits"} + rows = [] + for c in args.cells.split(","): + cd = f"{args.video_root}/{c}" + if not glob.glob(f"{cd}/t*_e*.npz"): + rows.append((c, legend.get(c, c), None, None, None, None)); continue + n, k = collage(cd, out / f"{c}.png", legend.get(c, c)) + links = [] + for f in sorted(glob.glob(f"{cd}/t*_e*.npz")): + z = np.load(f, allow_pickle=True); name = f"{c}_{Path(f).stem}_{'ok' if z['success'] else 'fail'}.mp4" + p = out / "mp4" / name + if not p.exists(): mp4(z["frames"], str(p)) + links.append((name, bool(z["success"]), int(z["task"]))) + js = f"{args.eval_root}/{c}.json" + sr = json.load(open(js)).get("overall", {}) if os.path.exists(js) else {} + rows.append((c, legend.get(c, c), n, k, sr, links)) + html = ["BC on rollout successes: evaluator at 256", + "", + "

BC on rollout successes — does the existing policy work once the evaluator renders at 256?

", + "

Same checkpoints as before; the only change is the evaluator's camera resolution and where the initial state comes from. Green border = success, red = failure (with step count). Videos are the agentview camera, every 2nd step.

", + ""] + for c, what, n, k, sr, links in rows: + if n is None: + html.append(f""); continue + html.append(f"") + html.append("
cellwhatsuccessfrom json
{c}{what}not run yet
{c}{what}{k}/{n} = {k/n:.3f}{sr}
") + for c, what, n, k, sr, links in rows: + if n is None: continue + html.append(f"

{c} — {what}

{k}/{n} succeeded

") + html.append("

" + " · ".join(f"t{t}{'✓' if ok else '✗'}" for nm, ok, t in links) + "

") + html.append("") + (out / "index.html").write_text("\n".join(html)) + print(f"[report] {out}/index.html") + for c, what, n, k, sr, links in rows: + print(f" {c:<10} {('%d/%d' % (k, n)) if n else 'pending':>8} {what}") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/mc_critic.py b/frozen/rsm_libero_rsmpi/mc_critic.py new file mode 100644 index 0000000000000000000000000000000000000000..79215fc2a67ef2ef4bb37fbbc7f19192d7d8d5b1 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/mc_critic.py @@ -0,0 +1,72 @@ +"""Scalar Monte-Carlo critic on the frozen RSM latent: Q(z, a_chunk, task) regressed on the +LOGGED discounted return of the offline corpus -- no occupancy, no bootstrap. The matched +scalar comparator for the RSM read-out (same latent, same inputs, same held-out set). + G_sub = (1-g) sum_k g^k r_{t+k} (dense subgoal-fraction reward) -> head 'sub' + G_succ = g^(steps to success) or 0 -> head 'succ' +Saved in the evaluator's --qf-ckpt format (iql_q=True) so it plugs into every selection +arm unchanged; `q` = the G_sub head unless --target succ. +usage: mc_critic.py --cache C --critic ckpt --subgoal-dir D --mask M --out DIR [--steps 60000]""" +import argparse, os, sys, json, numpy as np, torch, torch.nn.functional as F +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from data import LiberoRSMData +from is_ope import load_critic +from iql import QNet +from scipy.stats import spearmanr + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) +ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="") +ap.add_argument("--out", required=True); ap.add_argument("--steps", type=int, default=60000) +ap.add_argument("--batch", type=int, default=1024); ap.add_argument("--lr", type=float, default=3e-4) +ap.add_argument("--gamma", type=float, default=0.99); ap.add_argument("--target", default="sub", choices=["sub", "succ"]) +ap.add_argument("--width", type=int, default=1024); ap.add_argument("--depth", type=int, default=3) +ap.add_argument("--seed", type=int, default=0) +a = ap.parse_args() +torch.manual_seed(a.seed); dev = "cuda" if torch.cuda.is_available() else "cpu" +d = LiberoRSMData(a.cache, chunk=10, seed=a.seed, in_ram=True, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, + success_mask=a.mask, norm_pool="demos") +enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d) +g = a.gamma +# ---- precompute per-frame returns once (both targets), vectorised per episode +G_sub = np.zeros(len(d.r), np.float32); G_succ = np.zeros(len(d.r), np.float32) +for e in range(d.n_ep): + lo, hi = int(d.ep_from[e]), int(d.ep_to[e]); rr = np.asarray(d.r[lo:hi], np.float64) + acc = 0.0 + for i in range(hi - lo - 1, -1, -1): + acc = rr[i] + g * acc; G_sub[lo + i] = (1 - g) * acc + if bool(d.ep_success[e]): + G_succ[lo:hi] = g ** np.arange(hi - lo, 0, -1) +print(f"[mc] returns: mean G_sub={G_sub.mean():.3f} G_succ={G_succ.mean():.3f}", flush=True) +q = QNet(cfg["d_z"], 70, d.n_task, width=a.width, depth=a.depth).to(dev) +opt = torch.optim.AdamW(q.parameters(), lr=a.lr, weight_decay=1e-4) +rng = np.random.default_rng(a.seed) +def batch(split, n): + eps = d.train_eps if split == "train" else d.val_eps + w = d.ep_len[eps].astype(np.float64); w /= w.sum(); e = rng.choice(eps, size=n, p=w) + t = d.ep_from[e] + (rng.random(n) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + act = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(n, -1) + tgt = torch.from_numpy((G_sub if a.target == "sub" else G_succ)[t]).to(dev) + return x, tk, act, tgt, t +os.makedirs(a.out, exist_ok=True); best = -1 +for step in range(1, a.steps + 1): + x, tk, act, tgt, _ = batch("train", a.batch) + with torch.no_grad(): z = enc(x) + pred = q(z, act, tk).squeeze(-1) + loss = F.mse_loss(pred, tgt); opt.zero_grad(); loss.backward(); opt.step() + if step % 5000 == 0 or step == a.steps: + q.eval() + with torch.no_grad(): + x, tk, act, tgt, t = batch("val", 6000); z = enc(x); pv = q(z, act, tk).squeeze(-1).cpu().numpy() + tkn = tk.cpu().numpy(); gs, gc = G_sub[t], G_succ[t] + wt = np.nanmean([spearmanr(pv[tkn == tt], gs[tkn == tt]).correlation for tt in range(d.n_task) if (tkn == tt).sum() > 30]) + sp = spearmanr(pv, gs).correlation; sc = spearmanr(pv, gc).correlation + print(f"[mc] {step} train_mse={float(loss):.4f} | VAL spearman G_sub {sp:+.3f} within-task {wt:+.3f} | G_succ {sc:+.3f}", flush=True) + blob = {"iql_q": True, "q": q.state_dict(), "d_z": cfg["d_z"], "d_act": 70, "n_task": d.n_task, "critic": a.critic, + "config": {"target": a.target, "gamma": g, "width": a.width, "depth": a.depth, "steps": step}, + "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch"), + "val_spearman_within": float(wt), "val_spearman": float(sp)} + torch.save(blob, os.path.join(a.out, f"mc_q_s{step}.pt")); torch.save(blob, os.path.join(a.out, "mc_q.pt")) + if wt > best: best = wt; torch.save(blob, os.path.join(a.out, "mc_q_best.pt")) + q.train() +print("[mc] DONE", flush=True) diff --git a/frozen/rsm_libero_rsmpi/merge_and_train.sbatch b/frozen/rsm_libero_rsmpi/merge_and_train.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..88c8c9a88bc1dc059d7c5870f99d567d1ed84ca2 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/merge_and_train.sbatch @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=merge_verify +#SBATCH --account=vision-pulkitag +#SBATCH --cpus-per-task=2 --mem=16G +#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 +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +PY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python +$PY $G/merge_verify.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --shards /data/pulkitag/users/rli14/rsm_libero_runs/verify \ + --out /data/pulkitag/users/rli14/rsm_libero_runs/verify/verified_mask.npz diff --git a/frozen/rsm_libero_rsmpi/merge_full.sbatch b/frozen/rsm_libero_rsmpi/merge_full.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..4149931e4c9e22e27f583db6c5d2ebcfdb202f23 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/merge_full.sbatch @@ -0,0 +1,15 @@ +#!/bin/bash +#SBATCH --job-name=merge_full +#SBATCH --account=vision-pulkitag +#SBATCH --qos=tig-main +#SBATCH --partition=tig-cpu +#SBATCH --cpus-per-task=2 --mem=16G +#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 +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python $G/merge_verify.py \ + --cache /data/pulkitag/scratch/rli14/rsm_libero_cache/full_r256 \ + --shards /data/pulkitag/users/rli14/rsm_libero_runs/verify_full \ + --out /data/pulkitag/users/rli14/rsm_libero_runs/verify_full/verified_mask.npz +echo "[merge] rc=$?" diff --git a/frozen/rsm_libero_rsmpi/merge_verify.py b/frozen/rsm_libero_rsmpi/merge_verify.py new file mode 100644 index 0000000000000000000000000000000000000000..99447b748fddf5a1c3ed10c1fd01f5218b806cac --- /dev/null +++ b/frozen/rsm_libero_rsmpi/merge_verify.py @@ -0,0 +1,60 @@ +"""Merge the per-task replay-verification shards into one success mask. + +Output: keep[i] over cache episode indices. An episode stays in the success pool only +if it is a demo (ground truth, never replayed), or a rollout whose logged success +REPRODUCED when its actions were re-executed from the logged sim_state. Episodes that +could not be resolved (source parquet missing) are dropped from the success pool rather +than trusted -- the whole point is that an unverified success is not a success. +""" +import argparse, glob, numpy as np + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True) +ap.add_argument("--shards", required=True, help="REPLAY shards (reproducibility)") +ap.add_argument("--goal-shards", default="", + help="GOAL-AUDIT shards (goal predicate at the logged final state). " + "DIAGNOSTIC ONLY -- do NOT filter on this. It answers 'was the label " + "honest about the state the episode reached', which is not the " + "admissibility question. Admissibility is REPRODUCIBILITY in the eval " + "environment; see --shards.") +ap.add_argument("--out", required=True) +ap.add_argument("--keep-unresolvable", type=int, default=0) +a = ap.parse_args() + +m = np.load(f"{a.cache}/meta.npz", allow_pickle=True) +demo, succ = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) +keep = demo.copy() # demos always kept +seen = np.zeros(len(demo), bool) +rep = unres = 0 +# ADMISSIBILITY RULE: a trajectory may train an offline learner only if its reward +# labels REPRODUCE in the environment we evaluate in. A label that was honest about the +# state its own run reached is still inadmissible if replaying those actions here does +# not get there -- those (s,a,r) tuples describe different dynamics than the ones the +# policy will be scored against, which is exactly what breaks offline RL. +src, mode = a.shards, "REPLAY in the eval environment (admissibility)" +if a.goal_shards: + print("[merge] NOTE: goal-audit shards given but NOT used as the filter; " + "they are diagnostic. Filtering on reproducibility.") +print(f"[merge] filtering on: {mode}") +for f in sorted(glob.glob(f"{src}/task*.npz")): + z = np.load(f, allow_pickle=True) + if a.goal_shards: + r = z["rows"]; idx, ver = r[:, 0], r[:, 1] + else: + idx, ver = z["ep_index"], z["verified"] + for e, v in zip(idx, ver): + seen[e] = True + if v == 1: keep[e] = True; rep += 1 + elif v < 0: + unres += 1 + if a.keep_unresolvable: keep[e] = True +n_succ = int((succ & ~demo).sum()) +missing = int((succ & ~demo & ~seen).sum()) +np.savez(a.out, keep=keep, n_checked=int(seen.sum()), n_reproduced=rep) +print(f"[merge] rollout successes in cache : {n_succ}") +print(f"[merge] checked : {int(seen.sum())} (missing shards: {missing})") +print(f"[merge] reproduced : {rep} ({rep/max(seen.sum(),1):.1%})") +print(f"[merge] unresolvable : {unres} " + f"({'kept' if a.keep_unresolvable else 'DROPPED'})") +print(f"[merge] success pool: {int((succ).sum())} -> {int(keep.sum())} episodes") +print(f"[merge] wrote {a.out}") diff --git a/frozen/rsm_libero_rsmpi/mislabel_report.py b/frozen/rsm_libero_rsmpi/mislabel_report.py new file mode 100644 index 0000000000000000000000000000000000000000..f27a0ca4e7bfa2b8c0ab16399f9ceefb8c4070a7 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/mislabel_report.py @@ -0,0 +1,41 @@ +"""Per-task mislabelling breakdown: episodes AND reward-frames affected. + +An episode's success bit is one label, but the reward is per-frame and derived from +it, so a single mislabelled episode corrupts every frame it occupies. Both counts are +reported because they answer different questions: how much of the success POOL is +fake (episodes), and how much of the reward SIGNAL is wrong (frames).""" +import glob, sys, numpy as np +V = sys.argv[1] if len(sys.argv) > 1 else "/data/pulkitag/users/rli14/rsm_libero_runs/verify" +C = "/data/pulkitag/users/rli14/rsm_libero_cache/full_demo" +m = np.load(f"{C}/meta.npz", allow_pickle=True) +elen = (m["ep_to"] - m["ep_from"]).astype(int) +tn = [str(t) for t in m["tasks"]] +d, s = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) +rows, TE, TB, TF, TFB = [], 0, 0, 0, 0 +for f in sorted(glob.glob(f"{V}/task*.npz")): + z = np.load(f); t = int(z["task"]) + idx, ver = z["ep_index"], z["verified"] + ok = ver >= 0; idx, ver = idx[ok], ver[ok] + if len(idx) == 0: + rows.append((t, 0, 0, 0, 0)); continue + bad = idx[ver == 0] + nf, nfb = int(elen[idx].sum()), int(elen[bad].sum()) + rows.append((t, len(idx), len(bad), nf, nfb)) + TE += len(idx); TB += len(bad); TF += nf; TFB += nfb +print(f"{'task':4s} {'name':36s} {'checked':>8s} {'MISLAB':>7s} {'rate':>6s} " + f"{'frames':>9s} {'bad frames':>11s} {'%':>6s}") +for t, n, b, nf, nfb in sorted(rows): + if n == 0: + print(f" {t:<3d} {tn[t][:36]:36s} {'--':>8s} {'--':>7s} {'--':>6s}" + f" {'--':>9s} {'--':>11s} {'--':>6s} (no logged successes)") + continue + print(f" {t:<3d} {tn[t][:36]:36s} {n:8d} {b:7d} {b/n:6.1%} " + f"{nf:9,d} {nfb:11,d} {nfb/nf:6.1%}") +nd = sum(1 for r in rows if r[1] > 0) +print(f"\n TOTAL over {nd} tasks with successes: {TE} checked, " + f"{TB} mislabelled ({TB/max(TE,1):.1%})") +print(f" reward frames: {TF:,} in verified episodes, {TFB:,} carry a wrong label " + f"({TFB/max(TF,1):.1%})") +npool = int((s & ~d).sum()) +print(f" rollout successes in cache: {npool}; checked {TE} ({TE/npool:.0%})" + f" -> projected ~{round(npool*TB/max(TE,1))} mislabelled at the pooled rate") diff --git a/frozen/rsm_libero_rsmpi/model.py b/frozen/rsm_libero_rsmpi/model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c006359c647f7ddc3b9f8700f8f0dc276fdcd34 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/model.py @@ -0,0 +1,525 @@ +"""Nets for RSM on the LIBERO-10 pi0.5 rollout corpus. + +Design follows the unified-RSM recipe on gen_q `main` (ogbench_unified_rsm/RECIPE.md, +notes/COLLAPSE_ANALYSIS.md), adapted from goal-ball OGBench to sparse-success LIBERO: + + * beta BAND training, not a single discount (RECIPE "train beta [0.8,0.98]") + * Fourier features on log(-log beta) (RECIPE "fourier_unit, n_fourier=6") + * residual successor z' = z + delta, with delta divided by the per-dimension + dataset RMS of (z_fut - z_now) (RECIPE v6.1 "horizon-normalize + then per-dimension divide by rms((s'-s)_i)") + * EMA target encoder supplies the future target, stop-grad, plus a per-coordinate + variance floor (RECIPE "variance floor keeps the + embedding from collapsing"; smolvla_rsm METHOD.md) + * action chunk conditions the occupancy on an equal footing with the task + embedding, via concat + FiLM (RECIPE v6 "condition on g and a equally") + +What is deliberately NOT ported: the goal-ball arrival likelihood (`q_readout=lik`, +`p = exp(-d^2/2 tol^2)` on privileged xy/xyz). LIBERO has no privileged success ball +in this latent, so the read-out is a learned reward decoder over the same latent, as +the image branch of CLAUDE.md requires. + +COLLAPSE_ANALYSIS lesson carried over: a value that scores STATES but cannot rank +ACTIONS produces flat batch metrics and a closed-loop cliff. The occupancy here is +action-conditioned for exactly that reason, and action ranking is the headline +diagnostic rather than state ranking. +""" +from __future__ import annotations +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def beta_fourier(beta: torch.Tensor, n: int = 6) -> torch.Tensor: + """Fourier features on the log-horizon of a discount in (0,1).""" + x = torch.log(-torch.log(beta.clamp(1e-6, 1 - 1e-6))) + fr = torch.arange(1, n + 1, device=beta.device, dtype=beta.dtype) + a = x[:, None] * fr[None] + return torch.cat([a.sin(), a.cos(), x[:, None]], -1) # 2n+1 + + +def time_embed(t: torch.Tensor, dim: int = 64) -> torch.Tensor: + half = dim // 2 + fr = torch.exp(-np.log(10000.0) * torch.arange(half, device=t.device, + dtype=t.dtype) / half) + a = t[:, None] * fr[None] * 1000.0 + return torch.cat([a.sin(), a.cos()], -1) + + +def mlp(sizes, act=nn.SiLU, out_act=False, norm=False): + layers = [] + for i in range(len(sizes) - 1): + layers.append(nn.Linear(sizes[i], sizes[i + 1])) + if i < len(sizes) - 2 or out_act: + if norm: + layers.append(nn.LayerNorm(sizes[i + 1])) + layers.append(act()) + return nn.Sequential(*layers) + + + +class TaskCond(nn.Module): + """Task conditioning: a frozen T5 sentence embedding, projected. + + The alternative -- nn.Embedding(n_task, d_task) -- conditions on an INDEX. It carries + nothing about what the task is, cannot transfer to a held-out instruction, and gives + the network a shortcut that removes any pressure on the visual latent to represent + the instruction. Passing t5_path swaps in the frozen sentence embedding; omitting it + keeps the index embedding so old checkpoints still load. + """ + + def __init__(self, n_task: int, d_task: int = 64, t5_path: str = ""): + super().__init__() + self.t5 = bool(t5_path) + if self.t5: + import numpy as _np + emb = _np.load(t5_path)["emb"].astype("float32") + emb = emb / (_np.linalg.norm(emb, axis=1, keepdims=True) + 1e-6) + self.register_buffer("E", torch.tensor(emb), persistent=True) + self.proj = nn.Linear(emb.shape[1], d_task) + else: + # hold the table as `weight` and look it up with F.embedding, so the + # state_dict key stays `.task.weight` -- exactly what + # nn.Embedding produced. Wrapping it as a submodule would rename the + # key and break every checkpoint written before this change. + self.weight = nn.Parameter(torch.randn(n_task, d_task) * 0.02) + + def forward(self, task): + if self.t5: + return self.proj(self.E[task]) + return F.embedding(task, self.weight) + + +class Encoder(nn.Module): + """OGPO 4096-d -> compact reward-predictive latent.""" + + def __init__(self, d_in: int, d_z: int = 256, width: int = 1024, depth: int = 3): + super().__init__() + self.net = mlp([d_in] + [width] * depth + [d_z], norm=True) + self.d_z = d_z + + def forward(self, x): + return self.net(x) + + +class IdentityEncoder(nn.Module): + """`--enc identity`: the (z-scored) input feature IS the latent. No parameters, so the + EMA target, the variance floor and the reward warm-up are all no-ops. Used when the + feature is a frozen foundation-model embedding modelled directly (rsm_rise: DINOv2 + CLS|GeM per camera + proprio, 1545-d), as the OCBench visual recipe did.""" + + def __init__(self, d_in: int): + super().__init__() + self.d_z = int(d_in) + + def forward(self, x): + return x + + +class PCAEncoder(nn.Module): + """`--pca-dim k`: a FIXED linear map fitted once on training frames (not a learned encoder). + z = (x - mean) @ W with W [d_in, k] orthonormal columns (top-k right singular vectors), so the + pseudo-inverse is W^T: back(z) = z @ W^T + mean. mean/W are persistent buffers, saved in the + checkpoint's `enc` state_dict and reloaded by is_ope.load_critic.""" + + def __init__(self, d_in: int, k: int): + super().__init__() + self.d_z = int(k) + self.register_buffer("mean", torch.zeros(int(d_in))) + self.register_buffer("W", torch.zeros(int(d_in), int(k))) + + @torch.no_grad() + def fit(self, X): + """X [n, d_in] float tensor of (z-scored) training states. Returns explained-variance ratio.""" + self.mean.copy_(X.mean(0)) + _u, S, Vh = torch.linalg.svd(X - self.mean, full_matrices=False) + self.W.copy_(Vh[: self.d_z].T) + var = S.pow(2) + return float(var[: self.d_z].sum() / var.sum()) + + def forward(self, x): + return (x - self.mean) @ self.W + + def back(self, z): + return z @ self.W.T + self.mean + + +class RewardHead(nn.Module): + """Goal-conditioned reward decoder R(z, task) -> logit of 'task complete here'.""" + + def __init__(self, d_z: int, n_task: int, d_task: int = 64, width: int = 512, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.net = mlp([d_z + d_task, width, width, 1]) + + def forward(self, z, task): + return self.net(torch.cat([z, self.task(task)], -1)).squeeze(-1) + + +class GoalLikelihood(nn.Module): + """Dense two-tower goal likelihood -- the recipe's `q_readout=lik`. + + `l = sigmoid( / tau)` with phi, psi unit-norm MLPs. Asymmetric + on purpose (phi != psi), because "z is at goal g" is not "g is at goal z". + + Why this replaces a binary success head: the success head is SPARSE -- terminal + labels are ~0.5% of frames, so almost every sampled future reads ~0 and Q is + near-constant in the action, leaving nothing to rank. This gives EVERY (z, g) + pair a probability, which is what makes the read-out able to separate actions. + + Trained by in-batch InfoNCE: positive is (z + eps, z), negatives are the other + goals in the batch. Recipe knobs: goal_feat_dim 256, towers (512,)x3, + goal_nce_tau 0.2, nce_noise 0.1. The scorer is STOP-GRAD in the Q path -- NCE + is the only gradient into the towers. + """ + + def __init__(self, d_z: int, d_feat: int = 256, width: int = 512, depth: int = 3, + tau: float = 0.2, noise: float = 0.1): + super().__init__() + self.phi = mlp([d_z] + [width] * depth + [d_feat], norm=True) + self.psi = mlp([d_z] + [width] * depth + [d_feat], norm=True) + self.tau = tau + self.noise = noise + + def _emb(self, net, z): + e = net(z) + return e / e.norm(dim=-1, keepdim=True).clamp_min(1e-6) + + def logit(self, z, g): + return (self._emb(self.phi, z) * self._emb(self.psi, g)).sum(-1) / self.tau + + def forward(self, z, g): + return torch.sigmoid(self.logit(z, g)) + + def nce_loss(self, z): + """In-batch InfoNCE. Positive (z+eps, z); negatives are other batch rows.""" + zp = z + self.noise * torch.randn_like(z) + a = self._emb(self.phi, zp) + b = self._emb(self.psi, z) + logits = (a @ b.t()) / self.tau + tgt = torch.arange(z.shape[0], device=z.device) + return F.cross_entropy(logits, tgt) + + +class FiLM(nn.Module): + def __init__(self, d_cond, d_h): + super().__init__() + self.to_gb = nn.Linear(d_cond, 2 * d_h) + + def forward(self, h, c): + g, b = self.to_gb(c).chunk(2, -1) + return h * (1 + g) + b + + +class OccFlow(nn.Module): + """Conditional flow-matching velocity for the beta-discounted successor. + + Predicts the velocity of the RESIDUAL delta = (z_fut - z_now) / rms, so the + network never has to re-encode z_now's own coordinates. + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 1024, depth: int = 4, n_fourier: int = 6, t5_path: str = "", + norm: bool = False, dropout: float = 0.0): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + d_cond = d_z + d_act + d_task + (2 * n_fourier + 1) + self.cond = mlp([d_cond, width, width], out_act=True, norm=True) + self.in_proj = nn.Linear(d_z + 128, width) + # norm=True (train_rsm.py --flow-norm 1): LayerNorm inside every residual block and on the + # stream before the output head. rsm_rise measured the un-normalised trunk amplifying + # held-out states (velocity 170 -> 8500 over 8 Euler steps on val rows, 8 -> 11 on train). + # Default False keeps every existing checkpoint loadable (Identity has no parameters). + self.blocks = nn.ModuleList([mlp([width, width], out_act=True, norm=norm) + for _ in range(depth)]) + if dropout > 0: + # appended INSIDE each block's Sequential so the Linear keeps state_dict index 0 + for blk in self.blocks: + blk.append(nn.Dropout(dropout)) + self.films = nn.ModuleList([FiLM(width, width) for _ in range(depth)]) + self.final_norm = nn.LayerNorm(width) if norm else nn.Identity() + self.out = nn.Linear(width, d_z) + self.n_fourier = n_fourier + + def forward(self, z_now, a_chunk, task, beta, x_k, k): + c = self.cond(torch.cat( + [z_now, a_chunk, self.task(task), beta_fourier(beta, self.n_fourier)], -1)) + h = self.in_proj(torch.cat([x_k, time_embed(k, 128)], -1)) + for blk, film in zip(self.blocks, self.films): + h = h + film(blk(h), c) + return self.out(self.final_norm(h)) + + +class RatioNet(nn.Module): + """Per-decision density-ratio classifier. + + Trained to separate a LOGGED action chunk at state z (from the behavior policy + mu) from a chunk freshly SAMPLED from the target policy pi at the same z. On + balanced classes the logit is exactly log pi/mu, so we never need a normalized + density for either policy -- which matters because mu here is a flow model + sampled as an SDE and has no tractable likelihood. This is the substitute for + the notes' w_{t,k} = prod pi(a_j|s_j)/mu(a_j|s_j). + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 512, depth: int = 3, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.net = mlp([d_z + d_act + d_task] + [width] * depth + [1], norm=True) + + def forward(self, z, a_chunk, task): + return self.net(torch.cat([z, a_chunk, self.task(task)], -1)).squeeze(-1) + + +class EndpointRatio(nn.Module): + """Rao-Blackwellized endpoint weight w*(z,a,z') = d^pi_beta / d^mu_beta. + + Regression target is the chunk-level product of per-decision ratios; the + squared-loss minimizer is the conditional expectation given the endpoint, + which is precisely the notes' Section-9 identity. Predicts LOG w for stability. + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 512, depth: int = 3, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.net = mlp([2 * d_z + d_act + d_task] + [width] * depth + [1], norm=True) + # start at w ~= 1: softplus(0.5413) = 1.0 + nn.init.zeros_(self.net[-1].weight); nn.init.constant_(self.net[-1].bias, 0.5413) + + def forward(self, z, a_chunk, z_fut, task): + """Returns w > 0 directly. softplus rather than exp: under squared loss an + exponential head has gradient proportional to w itself, so once it + undershoots it stops learning -- observed as E_mu[w]=0.45 against a target + of 1.0. softplus keeps the gradient alive as w -> 0.""" + o = self.net(torch.cat([z, a_chunk, z_fut, self.task(task)], -1)).squeeze(-1) + return F.softplus(o) + + +class RawFeat(nn.Module): + """Feature map for policy extraction: full observation, CENTERED only. + + Two separate findings drive this. + + (1) The policy must not read the critic's latent. That encoder is trained to + predict REWARD, so its bottleneck keeps what separates success from failure + and discards what an action head needs. Measured: a flow policy on the 264-d + reward latent beat a predict-the-mean action baseline by only 14% in MSE, + with a biased gripper channel. + + (2) It must not read PER-DIM Z-SCORED features either. Whitening gives all + 4104 dimensions equal variance, which amplifies thousands of near-dead + directions up to the scale of the informative ones. Measured on BC-on-demos: + action loss rose 0.158 -> 0.355 and closed-loop success fell from 3/10 to + 0/10 on task 2 when the policy input was whitened. + + What the input actually needed was CENTERING: the mean feature vector has + norm 51.1 against a per-frame deviation of norm 9.0, so 85% of the raw + magnitude is a constant carrying no information. Centering removes that + without touching the relative importance of dimensions. + + The data layer hands over z-scored features (the critic wants those), so this + module rescales them back by `scale` = sd / mean(sd) over the visual block, + recovering (x - mu) / s_global exactly. Proprio keeps its per-dim z-score: + its 8 dims are genuinely different units, spanning std 0.014 to 1.372.""" + + def __init__(self, d, scale=None): + super().__init__() + self.d_out = int(d) + if scale is None: + scale = torch.ones(int(d)) + self.register_buffer("scale", torch.as_tensor(scale, dtype=torch.float32)) + + def forward(self, x): + return x * self.scale + + +class ConcatFlowPolicy(nn.Module): + """Flow-matching action-chunk policy, CONCATENATION-conditioned. + + A faithful port of the head behind this lane's 0.584 bcdemos bar. The + difference from FlowPolicy is not cosmetic: FlowPolicy squeezes the whole + 4104-d observation through a `cond` MLP and injects it only as FiLM scale and + shift, so the action branch never sees the observation directly. Measured + consequence at identical chunk (10), width (1024), depth (4) and demo cache: + held-out ODE-sampled reconstruction MSE was 0.0480 for FiLM against 0.00319 + for the concatenation head that reaches 0.584 -- a 15x gap that no amount of + normalisation or feature choice closed. + + Everything else matches that recipe: SiLU, no normalisation layers, 64-d task + embedding, 128-d sinusoidal flow-time embedding, the noisy chunk fed straight + in, and 10 Euler steps at sampling time. + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 1024, depth: int = 4, steps: int = 10, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + ind = d_z + d_task + 128 + d_act + layers = [] + for i in range(depth): + layers += [nn.Linear(ind if i == 0 else width, width), nn.SiLU()] + layers += [nn.Linear(width, d_act)] + self.net = nn.Sequential(*layers) + self.d_act = d_act + self.steps = steps + + def velocity(self, z, task, a_k, k): + return self.net(torch.cat([z, self.task(task), time_embed(k, 128), a_k], -1)) + + def fm_loss(self, z, task, a, reduce=True): + k = torch.rand(a.shape[0], device=a.device) + noise = torch.randn_like(a) + a_k = (1 - k)[:, None] * a + k[:, None] * noise + per = (self.velocity(z, task, a_k, k) - (a - noise)).pow(2).mean(-1) + return per.mean() if reduce else per + + @torch.no_grad() + def sample(self, z, task, temp: float = 1.0, sde: float = 0.0, + sde_anneal: bool = False): + """temp scales the initial noise; sde injects noise DURING integration. + + sde_anneal scales the injected noise by the remaining noise fraction k, so + the perturbation is large early (where the drift can still re-project it + onto the manifold) and vanishes at the last steps; constant sde leaves an + un-corrected sde*sqrt(dt) kick on the final action. + + These buy diversity in different places and it matters here. temp inflates + the PRIOR the ODE transports, so every sample starts further out and the + map carries it somewhere the data never was -- measured closed-loop 0.550 + at temp 1.0, 0.310 at 1.5, 0.000 at 2.0, with the ranker held fixed. sde + follows the learned drift and perturbs along the way, which keeps samples + near the manifold the drift was fitted on. That is the mechanism that + produced usable candidate diversity in the related lane. + + Flow matching learns a near-deterministic map for a unimodal conditional, + so a trained policy's samples barely differ: measured action std 0.029 at + 120k steps and 0.053 at 20k, against 0.421 in the data. PARL cannot rank + N copies of one action, so temp>1 widens the prior the ODE transports and + gives the critic something to choose between. Candidates further from the + mode are exactly what the value is there to accept or reject. + """ + return self.sample_eps(z, task, torch.randn(z.shape[0], self.d_act, device=z.device), + temp=temp, sde=sde, sde_anneal=sde_anneal) + + def sample_eps(self, z, task, eps, temp: float = 1.0, sde: float = 0.0, + sde_anneal: bool = False): + """sample() with caller-supplied initial noise eps [B, d_act] (common random + numbers across candidates); the SDE perturbations, if any, stay independent.""" + x = eps * temp + dt = 1.0 / self.steps + for s in range(self.steps): + k = torch.full((z.shape[0],), 1 - s / self.steps, device=z.device) + x = x + self.velocity(z, task, x, k) * dt + if sde: + # Euler-Maruyama style: the drift is followed exactly and the + # perturbation scales as sqrt(dt), so total injected variance is + # independent of the number of solver steps. + sc = sde * (dt ** 0.5) + if sde_anneal: + sc = sc * float(k[0]) + x = x + sc * torch.randn_like(x) + return x + + +class BCHead(nn.Module): + """Gaussian action-chunk policy over the frozen latent: pi(A | z, task). + + Deliberately a tractable Gaussian, unlike the flow-SDE behavior policy: the + target policy is the one we must SAMPLE from many times per state (for the + ratio classifier and for AWR), and a closed form keeps that cheap. + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 1024, depth: int = 4, log_std_init: float = -1.0, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.trunk = mlp([d_z + d_task] + [width] * depth, out_act=True, norm=True) + self.mu = nn.Linear(width, d_act) + self.log_std = nn.Parameter(torch.full((d_act,), log_std_init)) + + def forward(self, z, task): + h = self.trunk(torch.cat([z, self.task(task)], -1)) + return self.mu(h), self.log_std.clamp(-5.0, 2.0) + + def sample(self, z, task, n: int = 1): + mu, ls = self(z, task) + if n == 1: + return mu + torch.randn_like(mu) * ls.exp() + mu = mu[:, None].expand(-1, n, -1) + return mu + torch.randn_like(mu) * ls.exp() + + def sample_eps(self, z, task, eps): + """Sample with caller-supplied standard-normal noise (common random numbers).""" + mu, ls = self(z, task) + return mu + eps * ls.exp() + + def log_prob(self, z, task, a): + mu, ls = self(z, task) + var = (2 * ls).exp() + return (-0.5 * ((a - mu) ** 2 / var + 2 * ls + np.log(2 * np.pi))).sum(-1) + + +class FlowPolicy(nn.Module): + """Flow-matching action-chunk policy pi(A | z, task). + + Replaces the Gaussian head because of a measured failure: with a Gaussian + target and a flow-SDE behaviour policy, the density-ratio classifier hit + 99.9-100% accuracy. It was not separating good actions from bad, it was + separating "Gaussian sample" from "flow sample" -- a parametric-family + artifact -- which drove E_mu[W] to 0.18 against a required 1.0 and made the + importance weights meaningless. Matching the family removes that shortcut. + + No tractable density, which is fine: the classifier supplies the ratio, and + AWR weights the per-sample flow-matching loss instead of a log-likelihood + (the same substitution the smolvla AWR run used). + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 1024, depth: int = 4, steps: int = 8, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.cond = mlp([d_z + d_task, width, width], out_act=True, norm=True) + self.in_proj = nn.Linear(d_act + 128, width) + self.blocks = nn.ModuleList([mlp([width, width], out_act=True) + for _ in range(depth)]) + self.films = nn.ModuleList([FiLM(width, width) for _ in range(depth)]) + self.out = nn.Linear(width, d_act) + self.d_act = d_act + self.steps = steps + + def velocity(self, z, task, a_k, k): + c = self.cond(torch.cat([z, self.task(task)], -1)) + h = self.in_proj(torch.cat([a_k, time_embed(k, 128)], -1)) + for blk, film in zip(self.blocks, self.films): + h = h + film(blk(h), c) + return self.out(h) + + def fm_loss(self, z, task, a, reduce=True): + """Per-sample flow-matching loss; stands in for -log pi(a|z).""" + k = torch.rand(a.shape[0], device=a.device) + noise = torch.randn_like(a) + a_k = (1 - k)[:, None] * a + k[:, None] * noise + v = self.velocity(z, task, a_k, k) + per = (v - (a - noise)).pow(2).mean(-1) + return per.mean() if reduce else per + + @torch.no_grad() + def sample(self, z, task, n: int = 1): + if n > 1: + z = z.repeat_interleave(n, 0) + task = task.repeat_interleave(n, 0) + a = torch.randn(z.shape[0], self.d_act, device=z.device) + for s in range(self.steps): + k = torch.full((z.shape[0],), 1.0 - s / self.steps, device=z.device) + a = a + self.velocity(z, task, a, k) / self.steps + return a + + +@torch.no_grad() +def ema_update(target: nn.Module, online: nn.Module, m: float = 0.995): + for pt, po in zip(target.parameters(), online.parameters()): + pt.mul_(m).add_(po.detach(), alpha=1 - m) + for bt, bo in zip(target.buffers(), online.buffers()): + bt.copy_(bo) diff --git a/frozen/rsm_libero_rsmpi/notes/action_contrast.pdf b/frozen/rsm_libero_rsmpi/notes/action_contrast.pdf new file mode 100644 index 0000000000000000000000000000000000000000..ee49476a9e88e8a40fb4c00a0f06f26b39901ee5 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/notes/action_contrast.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65c4330748f098ef6fcd6fbf42b24807b9bfb2dd2146e0ad8851b75d8e29cea3 +size 187852 diff --git a/frozen/rsm_libero_rsmpi/notes/action_contrast.tex b/frozen/rsm_libero_rsmpi/notes/action_contrast.tex new file mode 100644 index 0000000000000000000000000000000000000000..bbdc28c13a9a74693660ca02a5e8adbbd9a386e1 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/notes/action_contrast.tex @@ -0,0 +1,182 @@ +\documentclass[11pt]{article} +\usepackage[margin=1in]{geometry} +\usepackage{amsmath,amssymb,booktabs,microtype} +\title{\vspace{-2em}The action-contrast term: same intent, opposite sign,\\opposite conclusion} +\author{gen\_q, branch \texttt{rsm-libero10-ope}} +\date{2026-09-11} +\begin{document}\maketitle\vspace{-1.5em} + +\section{Why this needs writing down} + +\texttt{origin/main}'s campaign concludes that its action-contrast term is +\emph{wrong-signed}, a ``flat standing tax on correct behaviour'', and ablates it. +Ours is superficially the same idea. It would be easy --- and wrong --- to copy +that conclusion across. The two terms have opposite signs, and measured on this +corpus ours is load-bearing: removing it makes the critic worse. + +\section{The two terms} + +Write $e_{\text{true}}$ for the flow's reconstruction error of the true future +when conditioned on the action actually taken, and $e_{\text{shuf}}$ for the same +error when conditioned on another action from the batch. The \emph{desired} +state of affairs is $e_{\text{true}} < e_{\text{shuf}}$: the real action should +explain the real future better. Define the gap as main does, +\begin{equation} +\mathrm{gap} \;=\; e_{\text{true}} - e_{\text{shuf}}, +\qquad\text{so desired}\;\Longleftrightarrow\; \mathrm{gap} < 0 . +\end{equation} + +\paragraph{main's hinge.} +$\mathcal{L} = \mathrm{relu}\!\left(e_{\text{shuf}} - e_{\text{true}} + m\right) + = \mathrm{relu}(-\mathrm{gap} + m)$, with margin $m = 0.02$. This is +\emph{large} exactly when the gap is most negative, i.e. when the model is +behaving best. Their own reproduction pins it: + +\begin{center}\small +\begin{tabular}{lrrrrr} +\toprule +cell & $e_{\text{true}}$ & $e_{\text{shuf}}$ & gap & logged term & corrected hinge \\ +\midrule +cube-single & 0.3017 & 0.3675 & $-0.0658$ & \textbf{0.0858} & 0.0000 \\ +cube-double & 0.2670 & 0.3319 & $-0.0649$ & \textbf{0.0849} & 0.0000 \\ +cube-triple & 0.2419 & 0.3002 & $-0.0583$ & \textbf{0.0783} & 0.0000 \\ +cube-quadruple & 0.2240 & 0.2788 & $-0.0548$ & \textbf{0.0748} & 0.0000 \\ +\bottomrule +\end{tabular} +\end{center} + +The logged value equals $\mathrm{relu}(-\mathrm{gap}+m)$ to four decimals on every +cell, which is what confirms the sign. The true action \emph{already} reconstructs +better everywhere, and the hinge penalises that by $\approx 0.085$ on every step +of every run. The corrected hinge, $\mathrm{relu}(\mathrm{gap}+m)$, evaluates to +exactly $0$ on all four cells --- so on state their ``fix'' is an \textbf{ablation} +of the term, not a re-aiming of it. On pixels the same term is steeply +cell-dependent rather than uniform: $0.4069 \pm 0.0630$ on visual-single against +$0.0278 \pm 0.0075$ on quadruple, a ${\sim}15\times$ spread, falling hardest on +the cell that works best. + +\paragraph{Ours.} +$\mathcal{L} = \mathrm{softplus}\!\left(e_{\text{true}} - e_{\text{shuf}}\right) + = \mathrm{softplus}(\mathrm{gap})$. Minimising it drives the gap \emph{more} +negative, which is the desired direction. The sign is right. + +It is not, however, inert once the gap goes negative, and that is worth stating +because it is the natural assumption. At a gap of $-0.065$, +\begin{equation} +\mathrm{softplus}(-0.065) = \ln\!\left(1 + e^{-0.065}\right) \approx 0.661, +\qquad +\frac{\partial}{\partial\,\mathrm{gap}}\,\mathrm{softplus} = \sigma(-0.065) \approx 0.484 . +\end{equation} +So it still contributes a substantial loss and, more importantly, a gradient of +roughly $0.48$ --- it keeps pushing long after the ordering is correct. That is the +sense in which it resembles a tax; the difference from main's is that it pushes in +the \emph{right} direction. + +\section{Which negative? Measured, not argued} + +The natural reading of the term is ``the error on $(s,a,s')$ should beat the error +on $(s,a_{\text{rand}},s'_{\text{rand}})$'' --- shuffle the action \emph{and} the +target. What we implement holds $s'$ fixed and shuffles only the action. The +worry about the first form is that it confounds two effects: its error is large +partly because the action is wrong and partly because the target is an unrelated +future, and a successor that ignored the action entirely would still score well on +it. + +Measured on the deployed critic (\texttt{probe\_actcon.py}, 4 batches of 2048, +$\beta=0.9$, held-out): + +\begin{center}\small +\begin{tabular}{lrr} +\toprule +negative & flow-matching error & gap vs true \\ +\midrule +(true action, true target) & 0.5989 & --- \\ +shuffled ACTION, true target & \textbf{14.1241} & $+13.5251$ \\ +true action, shuffled target & 0.7378 & $+0.1389$ \\ +shuffled action AND target & 13.4020 & $+12.8031$ \\ +\bottomrule +\end{tabular} +\end{center} + +The action accounts for \textbf{105.6\%} of the both-shuffled gap and the target +for \textbf{1.1\%}. So the confound is negligible here: the intuitive form and the +implemented form measure essentially the same thing, because on this model +essentially all of the difficulty comes from the conditioning action. Holding +$s'$ fixed is still the cleaner instrument --- it is a paired comparison, same +target, same noise, same flow time --- but the two are not in practical conflict. + +(What one would \emph{ideally} contrast against is +$(s, a_{\text{rand}}, s'\!\mid\! a_{\text{rand}})$, the future that the random +action would actually have produced. That is unobtainable offline: the dataset +never shows where $a_{\text{rand}}$ leads from $s$. This is the same missing +counterfactual that makes the value's action direction arbitrary.) + +\section{The number that reframes everything} + +Shuffling the action multiplies the flow-matching error by \textbf{23.6$\times$} +($0.599 \to 14.12$). The successor is not remotely action-blind: it keys on the +action extremely strongly. Give it an action that did not produce this future and +its velocity prediction falls apart. + +That sits beside a fact established separately (\texttt{probe\_crn.py}): the +\emph{value} read off this same flow does not rank actions --- perturbing an +expert chunk raises $Q$ as often as it lowers it. Both are true, and together they +say something sharper than either alone. The model has learned a strong, +confident mapping from action to future. For actions it never saw at that state +that mapping produces a \emph{wildly} different prediction, and a wildly different +latent earns an essentially arbitrary reward. The failure is not indifference to +the action; it is confident nonsense off the data. + +\paragraph{A correction to this document.} An earlier version argued our term is +``not inert'' once the gap goes negative, computing +$\mathrm{softplus}(-0.065)\approx0.661$ with gradient $\approx0.48$. That used +\emph{main's} measured gap. Ours is $-13.53$, where +$\mathrm{softplus}(-13.53)\approx 1.3\times10^{-6}$ and the gradient is +$\sigma(-13.53)\approx 1.3\times10^{-6}$. On the trained model our term is +\textbf{numerically inert}. It is active only early, while the gap is still +small --- which is precisely where the action win rate peaks (steps 1000--2000) +before decaying. That is a better explanation of the ablation result below than +``a standing force'': the term shapes the successor early and then switches off. + +\section{What it is worth here} + +Held-out within-task action win rate of the critic, everything else fixed: + +\begin{center}\small +\begin{tabular}{lcc} +\toprule +$w_{\text{actcon}}$ & label & best action win rate \\ +\midrule +0.0 & dense (outcome) & 0.522 \\ +0.0 & terminal (arrival) & 0.478 \\ +\textbf{0.5} & dense & \textbf{0.568} \\ +1.0 (with $d_z{=}512$) & dense & 0.532 \\ +2.0 & dense & 0.533 \\ +\bottomrule +\end{tabular} +\end{center} + +Removing the term costs $0.046$ of win rate; doubling it past $0.5$ costs about as +much again. There is an optimum near $0.5$ and we are at it. \textbf{main's +ablation conclusion does not transfer}, and the reason is simply that their term +had the opposite sign: ablating a penalty on correct behaviour helps, ablating a +reward for it does not. + +\section{The caveat that limits all of this} + +The win rates above live in $0.52$--$0.57$, barely above chance, and the term +moves them by $0.05$. It is a real effect on a critic that is weak in a way this +term does not address. Separate measurement (\texttt{probe\_crn.py}) shows the +counterfactual-conditioned $Q$ responds to an action with roughly the right +magnitude and an \emph{arbitrary sign}, because it is trained only on the action +actually taken. The action-contrast term sharpens how much the successor depends +on the action; it does nothing to make that dependence point the right way. The +reader that does rank actions correctly here is the supervised student $Q$, fit by +regression onto real $(s,a,s')$ transitions --- expert-versus-perturbation wins +rising $0.515 \to 0.614$ with perturbation size, against flat chance for the +counterfactual read-out. + +So: keep the term at $0.5$, do not copy the ablation, and do not expect it to fix +the direction problem. + +\end{document} diff --git a/frozen/rsm_libero_rsmpi/notes/is_successor_tutorial.pdf b/frozen/rsm_libero_rsmpi/notes/is_successor_tutorial.pdf new file mode 100644 index 0000000000000000000000000000000000000000..946ace6a82e814ea79427765dbbe6ed26d5e0fcd Binary files /dev/null and b/frozen/rsm_libero_rsmpi/notes/is_successor_tutorial.pdf differ diff --git a/frozen/rsm_libero_rsmpi/notes/is_successor_tutorial.tex b/frozen/rsm_libero_rsmpi/notes/is_successor_tutorial.tex new file mode 100644 index 0000000000000000000000000000000000000000..ea8d0759076cdf13a835efff4d8c62964ec2e0df --- /dev/null +++ b/frozen/rsm_libero_rsmpi/notes/is_successor_tutorial.tex @@ -0,0 +1,104 @@ +\documentclass[9pt]{extarticle} +\usepackage[margin=0.4in]{geometry} +\usepackage{amsmath,amssymb,amsthm} +\usepackage{bm} +\usepackage{enumitem} +\usepackage[colorlinks=true,linkcolor=blue!60!black,urlcolor=blue!60!black]{hyperref} +\usepackage{xcolor} +\usepackage{tcolorbox} +\usepackage{parskip} +\setlength{\parskip}{2pt}\setlength{\abovedisplayskip}{3pt}\setlength{\belowdisplayskip}{3pt}\setlength{\abovedisplayshortskip}{2pt}\setlength{\belowdisplayshortskip}{2pt} + +\newcommand{\E}{\mathbb{E}} +\newcommand{\ind}{\mathbf{1}} +\newcommand{\dpi}{d^{\pi}_{\lambda}} +\newcommand{\dmu}{d^{\mu}_{\lambda}} + + +\linespread{0.92}\pagestyle{empty} +\begin{document} +\begin{center}{\large\bfseries Importance Sampling for Successor Distributions}\\[1pt]{\small How to turn a behavior-policy occupancy into a target-policy occupancy, and why the same weight reweights $Q$}\end{center}\vspace{-4pt} + +\paragraph{Short answer.} The note uses importance sampling to do \emph{both}: Sections~7--8 reweight to change the +\emph{distribution} ($\dmu \to \dpi$), and Section~9 pushes the identical weight through to the $Q$ readout, where +it becomes a per-particle multiplier. They are the same identity applied at different points. + + +\paragraph{Setup.} +The successor model $\hat d_\lambda(z\mid s,a)$ predicts a \emph{single} future state $z$. In the dataset that +state was produced by a logged sub-trajectory $\tau = (s_0, a_0, s_1, a_1, \dots, s_K)$ with $K\sim \mathrm{Geom}(1-\lambda)$ +and $z := s_K$. Call $\tau$ the chunk; it lives only in the data and in this derivation, never as a model output. +Conditioning on the first state--action pair, the chunk probability under a policy $\rho$ factorizes into dynamics, +the stopping clock, and the policy's own action choices: +\[ +p_\rho(\tau\mid s_0,a_0) \;=\; P(K)\prod_{j=0}^{K-1} P(s_{j+1}\mid s_j,a_j)\prod_{j=1}^{K-1}\rho(a_j\mid s_j). +\] +The dataset gives chunks from $p_\mu$ (behavior). We want the occupancy of the target policy $\pi$. + +\paragraph{Step 1: the trajectory ratio.} +Dynamics and the stopping clock do not depend on the policy, so they cancel in the ratio, leaving only the +intervening actions: +$w(\tau) := p_\pi(\tau\mid s_0,a_0)/p_\mu(\tau\mid s_0,a_0) = \prod_{j=1}^{K-1}\pi(a_j\mid s_j)/\mu(a_j\mid s_j)$. +The first action is excluded because both sides condition on it. This is the $w_{t,k}$ of Section~7 of the note. + +\paragraph{Step 2: the change of measure.} +For any function $f$ of the chunk, assuming $\mu>0$ wherever $\pi>0$, +\[ +\E_{\tau\sim p_\pi}[f(\tau)] \;=\; \sum_\tau p_\pi(\tau)\, f(\tau) \;=\; \sum_\tau p_\mu(\tau)\,\frac{p_\pi(\tau)}{p_\mu(\tau)}\, f(\tau) \;=\; \E_{\tau\sim p_\mu}\big[w(\tau)\, f(\tau)\big]. +\] +This one line is the whole method; everything else is choosing $f$. + +\paragraph{Step 3: from trajectories to the endpoint occupancy.} +Take $f(\tau)=\ind[s_K = z]$. The left side is $\dpi(z\mid s_0,a_0)$. Splitting the right side by endpoint, +\[ +\dpi(z\mid s,a) \;=\; \E_\mu\big[w(\tau)\,\ind[s_K=z]\big] \;=\; \dmu(z\mid s,a)\cdot\underbrace{\E_\mu\big[w(\tau)\mid s,a,s_K=z\big]}_{=:\;w^*(s,a,z)}. +\] +So the endpoint density ratio is the \emph{conditional average} of the trajectory ratio over all logged chunks that +share the same endpoint: +\[ +w^*(s,a,z) \;=\; \frac{\dpi(z\mid s,a)}{\dmu(z\mid s,a)} \;=\; \E_\mu\!\left[\prod_{j=1}^{K-1}\frac{\pi(a_j\mid s_j)}{\mu(a_j\mid s_j)}\;\middle|\; s,a,\,s_K=z\right]. +\] +This is the boxed identity in Section~9, and it is the key step: because the model emits only $z$, the only +weight usable at inference is a function of $(s,a,z)$, and $w^*$ is that function. Regressing $w(\tau)$ onto $(s,a,z)$ +with squared loss recovers it exactly, since the squared-loss minimizer is the conditional expectation. Averaging over +the hidden trajectories is Rao--Blackwellization, so $w^*$ has lower variance than $w(\tau)$. + +\paragraph{Step 4: three places to apply the weight.} +All three are Step~2 with a different $f$. +\begin{enumerate}[leftmargin=1.5em,itemsep=1pt,topsep=1pt] +\item \textbf{Training-time reweighting} (Sec.~7). Take $f=\ell_\theta(z\mid s,a)$, the endpoint flow-matching loss. Then +$\E_\mu[w\,\ell_\theta]=\E_\pi[\ell_\theta]$, so weighting each logged $(s,a,z)$ tuple by $w(\tau)$, computed from the +logged intervening actions, fits the endpoint model to $\dpi$ directly. The model still predicts only $z$. +\item \textbf{Test-time resampling} (Sec.~8). Sample chunks $\tau_i$ from the behavior model, compute $w_i$, normalize +$\tilde w_i = w_i/\sum_j w_j$, resample. Sampling--importance--resampling converts behavior samples into approximate +target samples. This is the one variant that needs the model to generate the whole chunk with its actions, i.e.\ a truncated trajectory/video model rather than a successor model. +\item \textbf{$Q$ reweighting} (Sec.~9). Take $f=r(z)$. Then +$Q^\pi(s,a) = \frac{1}{1-\gamma}\,\E_{z\sim d^\pi_\gamma}[r(z)] = \frac{1}{1-\gamma}\,\E_{z\sim d^\mu_\gamma}\big[w^*(s,a,z)\,r(z)\big]$. +The occupancy model stays fixed at $d^\mu$. Only a small learned $\hat w_\omega\approx w^*$ changes with $\pi$. +\end{enumerate} + +\paragraph{Step 5: through the recursion.} +With restart probability $p=\frac{\gamma-\lambda}{\gamma(1-\lambda)}$, a particle makes jumps $\ell=0,1,\dots$ and +draws each boundary action $a^{(\ell+1)}\sim\pi(\cdot\mid s^{(\ell+1)})$ itself. The boundary is already on-policy, +so only the \emph{inside} of each chunk needs correcting, and the corrections multiply: +\[ +C_i \;=\; \prod_{\ell}\hat w_\omega\big(s^{(\ell)},a^{(\ell)},z^{(\ell)}\big),\qquad +\hat Q^\pi(s,a) \;=\; \frac{1}{(1-\gamma)N}\sum_{i=1}^N C_i\, r(z_i). +\] +The self-normalized form $\frac{1}{1-\gamma}\,\sum_i C_i r(z_i)\big/\sum_i C_i$ trades a small bias for much lower +variance; resampling by $\hat w$ after every jump instead of carrying the product is the sequential Monte Carlo variant and avoids weight collapse. + +\paragraph{What it costs.} +Normalized action likelihoods for both policies ($\mu$ needs a fitted density; diffusion/flow policies have no tractable one); +variance of $w$ growing roughly like $\exp\!\big(K\cdot\mathrm{KL}(\pi\|\mu)\big)$, which is the argument for short chunks; and the +weight corrects policy mismatch only, never error in the learned proposal $\hat d^\mu_\lambda$. + +\begin{tcolorbox}[colback=orange!5,colframe=orange!60!black,boxrule=0.5pt,boxsep=1pt,top=2pt,bottom=2pt,left=4pt,right=4pt] +\textbf{Why this bears on the stitching result.} Boundary-only stitching swaps the policy at one action per chunk. +At $\lambda=0.98$ a chunk averages $\lambda/(1-\lambda)\approx 49$ steps, so the composed process follows $\pi$ on +roughly $2\%$ of steps and $\mu$ on the rest. The $Q$ estimate is then mostly evaluating the behavior policy, which +would make an improvement signal at the boundaries hard to see. Importance weighting is what makes the inside of each +chunk follow $\pi$ too. +\end{tcolorbox} + +\end{document} diff --git a/frozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.pdf b/frozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.pdf new file mode 100644 index 0000000000000000000000000000000000000000..5063b2d9ed3f9529a3e1f790fb506377d2f49481 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4df1f5ceef4984acf8b865afd0c510f854c61c91e3214a49ad86f239e8302ebc +size 202537 diff --git a/frozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.tex b/frozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.tex new file mode 100644 index 0000000000000000000000000000000000000000..2bc0c33d83005d1370867682304a0e526d5d5402 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.tex @@ -0,0 +1,141 @@ +\documentclass[11pt]{article} +\usepackage[margin=1in]{geometry} +\usepackage{amsmath,amssymb,booktabs,microtype} +\usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref} +\title{\vspace{-2em}RSM on LIBERO-10 rollouts: how our value differs from +\texttt{origin/main}} +\author{gen\_q, branch \texttt{rsm-libero10-ope}} +\date{2026-09-11} +\begin{document}\maketitle\vspace{-1.5em} + +\section{Why this document} + +Our RSM recipe does not improve on behaviour cloning for LIBERO-10 +(BC-on-demos $0.630$; best value-guided arm $0.510$), while the same family of +method works on \texttt{origin/main}'s benchmarks. This compares the two value +definitions term by term. The conclusion is that they are \emph{not the same +estimator}: three differences are structural, and one of them is a variance +problem that \texttt{main} explicitly documents and fixes and we did not. + +\section{The two definitions} + +Both start from the same object, the discounted successor occupancy +\begin{equation} +d^{\pi}_{\beta}(x\mid s,a,\cdot)=(1-\beta)\sum_{k\ge0}\beta^{k} +P^{\pi}\!\big(s_{t+k}=x\mid s_t=s,a_t=a\big), +\end{equation} +fitted by conditional flow matching on the residual +$\tilde x=(E(x)-E(s))/\eta(\beta)$ with $E(s)$ stop-gradient. Up to here the two +implementations agree, including the per-dimension residual normalisation and the +EMA target encoder. They diverge at the read-out. + +\paragraph{\texttt{origin/main}: a survival product over hops.} +A two-tower InfoNCE arrival likelihood +$\ell(x,g)=\sigma\!\big(\varphi(x)\!\cdot\!\psi_g(g)/\tau_q\big)$ is folded +backwards along a $K$-hop chain, giving +\begin{equation} +Q_{\text{main}}(s,a,g)\;=\;-\frac{\gamma^{K}}{1-\gamma} +\prod_{k=1}^{K}\big(1-\ell(h_k,g)\big), +\qquad +\arg\max_a Q \;=\; \arg\max_a \sum_{k=1}^{K}\operatorname{softplus}(f_k), +\label{eq:main} +\end{equation} +where $\ell=\sigma(f)$. Each factor is the modelled probability of \emph{not} +having arrived by hop $k$. + +\paragraph{Ours: an expectation of reward at one endpoint.} +A reward head $r$ is trained by BCE against a dense success label, and +\begin{equation} +Q_{\text{ours}}(z,a)\;=\;\frac{1}{1-\gamma}\, +\mathbb{E}_{z'\sim d^{\mu}_{\beta}}\big[\sigma(r(z'))\big], +\label{eq:ours} +\end{equation} +estimated as a self-normalised importance-weighted mean over $N$ particles, where +$z'$ is the endpoint of a geometrically-truncated recursion with restart +probability $p=(\gamma-\beta)/(\gamma(1-\beta))$. + +\section{The three structural differences} + +\begin{enumerate} +\item \textbf{Product over hops versus a single endpoint.} +\eqref{eq:main} accumulates arrival evidence at \emph{every} hop; \eqref{eq:ours} +reads the reward head \emph{once}, at the final endpoint, and discards the +intermediate hops. With a dense per-frame success label this throws away most of +the signal the chain generates and makes the estimate depend on one noisy draw +rather than $K$. + +\item \textbf{Unsaturating versus saturating.} +In log space \eqref{eq:main} is a \emph{sum of softplus}, whose derivative +$\sigma(f)\in(0,1)$ never vanishes. Ours is a mean of $\sigma$, whose gradient +vanishes at both ends. Our reward head reaches AUC $0.96$, so it is routinely +saturated, precisely where it stops discriminating. + +\item \textbf{Contrastive arrival versus a BCE reward head.} +$\ell$ is normalised against in-batch negatives, so it is a \emph{relative} +quantity and cannot collapse to a base rate. $\sigma(r(z'))$ is absolute: an +off-support $z'$ that drifts toward the dataset mean returns roughly the corpus +success rate, which is $0.545$ here and outranks a confident low score on a +genuinely failing action. +\end{enumerate} + +\section{The variance difference, which is the one that bites} + +\texttt{main} reports that the per-state estimator has +$\mathrm{sd}(\hat Q)\approx 4.51$ against a policy-improvement signal +$\mathbb{E}[Q(a_\pi)-Q(a_{\text{data}})]\approx 0.82$, a ratio of $5.5$, and +concludes that ``a maximising actor ascends estimator noise as readily as +signal''. Its fix is clipped double-$Q$ built from \emph{flow noise rather than +twin networks}: split the $N$ draws, take the minimum of the two half-means, +\begin{equation} +\hat Q_{\min2}=\min\Big\{\tfrac{2}{N}\textstyle\sum_{i\le N/2}Q^{(i)},\; +\tfrac{2}{N}\textstyle\sum_{i>N/2}Q^{(i)}\Big\}. +\label{eq:min2} +\end{equation} + +We measured the same regime independently on LIBERO-10 with +\texttt{probe\_crn.py}: repeat noise (same action, independent draws) $2.246$ +against a paired action effect of $0.399$ at the smallest perturbation, a ratio of +$5.6$. \textbf{The numbers agree almost exactly, and we did not implement +\eqref{eq:min2}.} We used the plain mean, optionally minus a particle standard +deviation. Those are not the same estimator: subtracting a spread penalises +disagreement symmetrically, whereas \eqref{eq:min2} is a one-sided pessimistic +bias that specifically stops an argmax from selecting a draw that was lucky. + +\begin{table}[h]\centering\small +\begin{tabular}{lll} +\toprule +& \texttt{origin/main} & ours \\ +\midrule +conditioning & goal $g$, reward-free & task id, dense success label \\ +arrival signal & two-tower InfoNCE $\ell(x,g)$ & $\sigma$ of a BCE reward head \\ +value form & survival product over $K$ hops & mean reward at one endpoint \\ +composition & fixed $K$, policy acts after hop 1 & geometric restart $p$, truncated \\ +estimator & $\min$ of two half-means & mean ($\pm$ std penalty) \\ +actor & $\max Q$ + BC anchor, scale-normalised & AWR exponential weights \\ +deployment & Polyak--Ruppert tail average & last / best checkpoint \\ +off-policy term & none & importance sampling (interior + endpoint) \\ +\bottomrule +\end{tabular} +\end{table} + +\section{What this predicts, and what it does not excuse} + +The differences above are enough to explain a weak value, and \eqref{eq:min2} +plus the product form are directly portable. They do \emph{not} by themselves +explain our sharper finding: with common random numbers cancelling the shared +noise, perturbing an expert action raises our $Q$ exactly as often as it lowers +it, at every perturbation size. That is a statement about \emph{direction}, not +variance, and no estimator applied after the fact repairs it. Its likely cause is +upstream of both formulas: the occupancy model is trained only on the action that +was actually taken, so its counterfactual response is unsupervised, and our +mean-pooled PaliGemma latent barely resolves what a 10-frame chunk does (action +versus proprio-delta correlation $0.98$, versus visual-latent delta $0.49$). + +Ordered by expected value: (i) adopt \eqref{eq:min2}; (ii) adopt the +product-over-hops read-out, which uses every hop and is unsaturating; +(iii) adopt the contrastive arrival likelihood, which cannot collapse to a base +rate. Items (i) and (ii) are small changes to \texttt{q\_recursive}; (iii) needs +the \texttt{GoalLikelihood} module already present but unused in +\texttt{model.py}. + +\end{document} diff --git a/frozen/rsm_libero_rsmpi/pack.py b/frozen/rsm_libero_rsmpi/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..dc899ff8fb29c3fb0408514dc528de8ffb203541 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/pack.py @@ -0,0 +1,278 @@ +"""Pack the LIBERO-10 pi0.5 OGPO rollout corpus into a flat memmap cache. + +Source layout (one npz per episode, 43,135 episodes over 10 task dirs): + /ep_t{T}_b{B}_i{id}_{epidx:06d}.npz + z [F,4096] float16 OGPO latent (agentview | wrist) + (task_index is NOT read -- see the guard in main()) + proprio [F,8] float32 + actions [F,7] float32 + success () bool + prompt () str + +Cache layout (written atomically into /): + z.f16 memmap [N,D] latents, frame-major, episodes contiguous + act.f32 memmap [N,7] executed action at that frame + meta.npz ep_from/ep_to/ep_len/ep_task/ep_success/ep_src, tasks, dim + +LEAKAGE NOTE recorded here because it shapes every downstream label choice: +failed episodes are ALL exactly 520 frames (the timeout) while successful ones +terminate early (mean ~263). Episode LENGTH therefore predicts success almost +perfectly. Any label built from "frames remaining" leaks the outcome, so the +reward label is defined on terminal states of successful episodes only, and the +headline diagnostic is action ranking at a FIXED state, never state ranking. +""" +from __future__ import annotations +import argparse, io, json, os, time, zipfile +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np + + +def read_header(path, assume_success=None): + """(n_frames, success) without reading the arrays. + + `np.load(f)["z"].shape` materialises the whole 2.3 MB latent block, which for + 43k episodes is ~99 GB of pointless NFS traffic. npz is a zip of .npy members, + so the shape lives in the member's own header: parse that and stop. + """ + with zipfile.ZipFile(path) as zf: + with zf.open("z.npy") as f: + ver = np.lib.format.read_magic(f) + shape, _fortran, _dt = np.lib.format._read_array_header(f, ver) + if assume_success is None or "success.npy" in zf.namelist(): + # rollouts always carry it; REPLAYED demo caches (rerender_rollouts.py + # --pool demos_replay) carry it too, and a demo whose live replay did not + # end in success is inadmissible exactly like a non-reproducing rollout + with zf.open("success.npy") as f: + succ = bool(np.load(io.BytesIO(f.read()), allow_pickle=False)) + else: + succ = assume_success # legacy demo caches carry no success field + return int(shape[0]), succ + + +def episode_files(root: Path): + """-> list of (task_name, path, is_demo). Task id comes from the directory name. + + Rollout dirs hold ep_*.npz and carry a `success` flag. The demo cache uses the + same task name with a `_demo` suffix, holds demo_*.npz, and has no success + field because every demonstration succeeds.""" + out = [] + for d in sorted(p for p in root.iterdir() if p.is_dir()): + demo = d.name.endswith("_demo") + name = d.name[:-5] if demo else d.name + for f in sorted(d.glob("demo_*.npz" if demo else "ep_*.npz")): + out.append((name, f, demo)) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--demos", default="", help="optional demo cache root to union in") + ap.add_argument("--max-eps", type=int, default=0, help="0 = all") + ap.add_argument("--stride", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--workers", type=int, default=32, + help="threads for the header scan (NFS latency-bound)") + ap.add_argument("--header-cache", default="", + help="npz to cache/reuse the (success,length) scan") + ap.add_argument("--tasks-file", default="/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation/logs/09052026_lib10_tasks.txt", + help="canonical LIBERO benchmark-id task order; task ids are " + "assigned from THIS list, never from directory sort order " + "and never from the npz `task_index` field.") + ap.add_argument("--keep-all-demos", action="store_true", + help="always include EVERY demo episode, then fill the rest " + "with rollouts. Balanced sampling kept only 94 of 500 " + "demos, which starves a BC-on-demos baseline.") + ap.add_argument("--episode-list", default="", + help="text file, one '/.npz' per line: pack EXACTLY these " + "rollouts in this order. Two clusters packing from the same list produce " + "index-identical caches, so per-episode artefacts (subgoal labels, " + "admissibility mask) transfer by index.") + ap.add_argument("--encoder", default="pi05_base_pytorch", + help="feature-encoder tag (basename of OGPO_PI05_BASE the latents were encoded " + "with). Written to PACK.json/RENDER.json; the evaluator refuses a mismatch.") + ap.add_argument("--cam-res", default="", + help="render resolution the SOURCE latents were encoded from (e.g. 256). " + "Written to PACK.json and RENDER.json; the evaluator refuses a cache " + "whose cam_res is undeclared or differs from its own --cam-res.") + ap.add_argument("--balance", action="store_true", + help="equalize success/failure count within each task") + args = ap.parse_args() + + rng = np.random.default_rng(args.seed) + src, out = Path(args.src), Path(args.out) + out.mkdir(parents=True, exist_ok=True) + files = episode_files(src) + if args.episode_list: + _want = [l.strip() for l in open(args.episode_list) if l.strip()] + _by = {f"{f.parent.name}/{f.name}": (n, f, dm) for n, f, dm in files if not dm} + _missing = [w for w in _want if w not in _by] + if _missing: + raise SystemExit(f"--episode-list: {len(_missing)} listed episodes absent under --src, e.g. {_missing[:3]}") + files = [_by[w] for w in _want] + [t for t in files if t[2]] # rollouts in list order, then demos + print(f"[pack] episode list: {len(_want)} rollouts pinned from {args.episode_list}", flush=True) + if args.demos: + files += episode_files(Path(args.demos)) + print(f"[pack] found {len(files)} episodes in {len(set(t for t, *_ in files))} tasks", + flush=True) + + # ---- pass 1: read headers (success + length), pick the subset ---- + hc = Path(args.header_cache) if args.header_cache else out / "headers.npz" + if hc.exists(): + c = np.load(hc, allow_pickle=True) + if len(c["paths"]) == len(files) and set(map(str, c["paths"])) == {str(f[1]) for f in files}: + dm_col = c["demo"] if "demo" in c.files else np.zeros(len(c["paths"]), bool) + hdr = [(t, Path(p), bool(s), int(L), bool(dm)) for t, p, s, L, dm in + zip(c["tasknames"], c["paths"], c["succ"], c["lens"], dm_col)] + print(f"[pack] header scan reused from {hc}", flush=True) + else: + hc.unlink() + if not hc.exists(): + def rd(tf): + task, f, demo = tf + L, succ = read_header(f, assume_success=True if demo else None) + return (task, f, succ, L, demo) + t_scan = time.time() + with ThreadPoolExecutor(max_workers=args.workers) as ex: + hdr = list(ex.map(rd, files, chunksize=16)) + print(f"[pack] header scan {len(hdr)} files in {time.time()-t_scan:.0f}s", + flush=True) + hc.parent.mkdir(parents=True, exist_ok=True) + np.savez(hc, tasknames=np.array([h[0] for h in hdr]), + paths=np.array([str(h[1]) for h in hdr]), + succ=np.array([h[2] for h in hdr]), + lens=np.array([h[3] for h in hdr]), + demo=np.array([h[4] for h in hdr])) + + # Task ids come from the canonical benchmark-id list so they agree with every + # other trainer in this lane. Two things are deliberately NOT used: directory + # sort order (incidental, and disagrees with benchmark id), and the npz + # `task_index` field (0 in every episode of this corpus). + canon = [n.strip() for n in + Path(args.tasks_file).read_text().replace("\n", ",").split(",") if n.strip()] + tid = {t: i for i, t in enumerate(canon)} + present = sorted(set(t for t, *_ in hdr)) + unknown = [t for t in present if t not in tid] + if unknown: + raise SystemExit(f"[pack] refusing: task dir(s) not in {args.tasks_file}: {unknown}") + tasks = canon + chosen = [] + unbalanced = [] + forced = [] + if args.keep_all_demos: + forced = [h for h in hdr if h[4]] + hdr = [h for h in hdr if not h[4]] + print(f"[pack] forcing all {len(forced)} demo episodes into the cache", flush=True) + if args.max_eps and args.max_eps < len(hdr): + per_task = args.max_eps // len(tasks) + for t in tasks: + pool = [h for h in hdr if h[0] == t] + if args.balance: + s = [h for h in pool if h[2]] + f_ = [h for h in pool if not h[2]] + k = min(per_task // 2, len(s), len(f_)) + pick = ([s[i] for i in rng.choice(len(s), k, replace=False)] + + [f_[i] for i in rng.choice(len(f_), k, replace=False)]) + if k == 0 and pool: + # A task can be entirely one-sided: STUDY_SCENE1 has 0 + # successes in 2,962 rollouts, so 50/50 balancing would drop + # it silently. Keep it at natural composition and record that + # it could not be balanced -- a task the behaviour policy + # never solves is a result, not a reason to hide the task. + kk = min(per_task, len(pool)) + pick = [pool[i] for i in rng.choice(len(pool), kk, replace=False)] + unbalanced.append((t, len(s), len(f_))) + else: + k = min(per_task, len(pool)) + pick = [pool[i] for i in rng.choice(len(pool), k, replace=False)] + chosen += pick + else: + chosen = hdr + chosen = forced + chosen + rng.shuffle(chosen) + sel_task = np.array([tid[h[0]] for h in chosen]) + n_per = np.bincount(sel_task, minlength=len(tasks)) + missing = [tasks[i] for i, n in enumerate(n_per) if n == 0 and + any(h[0] == tasks[i] for h in hdr)] + if missing: + raise SystemExit(f"[pack] refusing: task(s) present in source but absent " + f"from the selection: {missing}") + print(f"[pack] packing {len(chosen)} episodes " + f"(success {np.mean([h[2] for h in chosen]):.3f}) " + f"per-task {n_per.tolist()}", flush=True) + if unbalanced: + print(f"[pack] NOT balanceable (kept at natural composition): " + f"{[(u[0][:28], u[1], u[2]) for u in unbalanced]}", flush=True) + + # ---- pass 2: sizes, allocate, fill ---- + lens = np.array([1 + (h[3] - 1) // args.stride for h in chosen], dtype=np.int64) + ep_demo = np.array([h[4] for h in chosen], bool) + ep_to = np.cumsum(lens); ep_from = ep_to - lens + N = int(ep_to[-1]) + with np.load(chosen[0][1], allow_pickle=True) as n: + D = int(n["z"].shape[1]); A = int(n["actions"].shape[1]) + print(f"[pack] N={N} frames D={D} A={A} " + f"({N*D*2/1e9:.1f} GB latents)", flush=True) + + zmm = np.lib.format.open_memmap(out / "z.f16.npy", mode="w+", + dtype=np.float16, shape=(N, D)) + # proprio is cheap (8 floats/frame) and the lane's closed-loop policy head + # consumes it alongside the latent, so pack it for interoperability even + # though the occupancy critic here does not use it. + pmm = np.lib.format.open_memmap(out / "proprio.f32.npy", mode="w+", + dtype=np.float32, shape=(N, 8)) + amm = np.lib.format.open_memmap(out / "act.f32.npy", mode="w+", + dtype=np.float32, shape=(N, A)) + ep_task = np.zeros(len(chosen), np.int64) + ep_succ = np.zeros(len(chosen), bool) + ep_src = [] + for i, (task, f, succ, _L, _dm) in enumerate(chosen): + with np.load(f, allow_pickle=True) as n: + z = n["z"][::args.stride] + a = n["actions"][::args.stride] + pr = n["proprio"][::args.stride] if "proprio" in n.files else None + s, e = int(ep_from[i]), int(ep_to[i]) + zmm[s:e] = z[: e - s] + amm[s:e] = a[: e - s] + if pr is not None: + pmm[s:e] = pr[: e - s] + ep_task[i] = tid[task]; ep_succ[i] = succ + ep_src.append(str(f)) + if (i + 1) % 250 == 0: + # Bound dirty-page accumulation: without periodic flushes the whole + # written cache sits dirty in page cache and the box is reported as + # out of memory (it killed this job and the concurrent upload once). + zmm.flush(); amm.flush(); pmm.flush() + print(f"[pack] {i+1}/{len(chosen)} episodes", flush=True) + zmm.flush(); amm.flush(); pmm.flush() + + np.savez(out / "meta.npz", ep_from=ep_from, ep_to=ep_to, ep_len=lens, + ep_task=ep_task, ep_success=ep_succ, ep_demo=ep_demo, + tasks=np.array(tasks), + dim=D, adim=A, stride=args.stride, n_frames=N, + ep_src=np.array(ep_src)) + _cam = int(args.cam_res) if str(args.cam_res).isdigit() else (args.cam_res or "UNKNOWN") + (out / "RENDER.json").write_text(json.dumps({ + "cam_res": _cam, "encoder": args.encoder, "flip": "[::-1,::-1] to serving orientation", + "resize": "-> 224 bilinear, uint8", + "encoder": "08312026_1110pm_ogpo_latent_cache.py PaliGemma base||wrist", + "proprio": "eef_pos(3)+axis_angle(3)+gripper(2)"}, indent=1)) + (out / "PACK.json").write_text(json.dumps({ + "cam_res": _cam, "encoder": args.encoder, + "src": str(src), "episodes": len(chosen), "frames": N, "dim": D, + "adim": A, "stride": args.stride, + "success_rate": float(ep_succ.mean()), + "n_demo": int(ep_demo.sum()), + "tasks": tasks, + "task_id_source": f"canonical benchmark order from {args.tasks_file} " + f"(dir sort order and the npz task_index field are both ignored)", + "episodes_per_task": n_per.tolist(), + "tasks_not_balanceable": [[u[0], int(u[1]), int(u[2])] for u in unbalanced], + }, indent=2)) + print(f"[pack] DONE -> {out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/pack_full.sbatch b/frozen/rsm_libero_rsmpi/pack_full.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..31eecaec479efb777ccb45f70233834b688e2f4f --- /dev/null +++ b/frozen/rsm_libero_rsmpi/pack_full.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=pack_full +#SBATCH --account=vision-pulkitag +#SBATCH --cpus-per-task=32 --mem=200G +#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 +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +PY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python +export PYTHONUNBUFFERED=1 +# --max-eps 0 = ALL 43,135 rollouts (the existing cache capped at 4,500 to fit a +# 110G --mem request; the a100/h200 nodes have 1-2 TB, so the cap is not binding) +$PY $G/pack.py \ + --src /data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1 \ + --demos /data/pulkitag/users/rli14/libero10_demo_ogpo_cache_srv \ + --out /data/pulkitag/scratch/rli14/rsm_libero_cache_full \ + --max-eps 0 --stride 1 --keep-all-demos --workers 32 +RC=$?; echo "[pack] rc=$RC $(date -u +%T)"; exit $RC diff --git a/frozen/rsm_libero_rsmpi/pack_full_r256.sbatch b/frozen/rsm_libero_rsmpi/pack_full_r256.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..b187808db5120af93bbb1a49360b0094694f2730 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/pack_full_r256.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=pack_full_r256 +#SBATCH --account=vision-pulkitag +#SBATCH --cpus-per-task=32 --mem=200G +#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 +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +PY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python +export PYTHONUNBUFFERED=1 +# ALL 43,135 rollouts (256-encoded, as the collector produced them) + the 500 demos +# re-rendered at 256. One latent space, the evaluator's. +$PY $G/pack.py \ + --src /data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1 \ + --demos /data/pulkitag/users/rli14/libero10_demo_ogpo_cache_r256 \ + --out /data/pulkitag/scratch/rli14/rsm_libero_cache/full_r256 \ + --max-eps 0 --stride 1 --keep-all-demos --workers 32 --cam-res 256 --episode-list /data/pulkitag/users/rli14/rsm_libero_cache/full_r256_episodes.txt +RC=$?; echo "[pack] rc=$RC $(date -u +%T)"; exit $RC diff --git a/frozen/rsm_libero_rsmpi/pack_r256.sbatch b/frozen/rsm_libero_rsmpi/pack_r256.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..190dd1d187299f0d504914e734af5790c981531e --- /dev/null +++ b/frozen/rsm_libero_rsmpi/pack_r256.sbatch @@ -0,0 +1,18 @@ +#!/bin/bash +#SBATCH --job-name=pack_r256 +#SBATCH --account=vision-pulkitag +#SBATCH --cpus-per-task=32 --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.err +set -uo pipefail +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +PY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/python +export PYTHONUNBUFFERED=1 +# Same 4,500-rollout subset as full_demo (same seed + header cache) so per-episode +# artefacts (subgoal labels, verified mask) stay aligned by index; demos at 256. +$PY $G/pack.py \ + --src /data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1 \ + --demos /data/pulkitag/users/rli14/libero10_demo_ogpo_cache_r256 \ + --out /data/pulkitag/users/rli14/rsm_libero_cache/full_demo_r256 \ + --max-eps 4500 --stride 1 --keep-all-demos --workers 32 --cam-res 256 --seed 0 --header-cache /data/pulkitag/users/rli14/rsm_libero_cache/headers_v2.npz +RC=$?; echo "[pack] rc=$RC $(date -u +%T)"; exit $RC diff --git a/frozen/rsm_libero_rsmpi/paired_test.py b/frozen/rsm_libero_rsmpi/paired_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b441c5581e64006461e0c581f253bb9b3664c8 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/paired_test.py @@ -0,0 +1,55 @@ +"""Paired comparison of two closed-loop evals. + +Arms are paired by construction: the env seed depends only on (seed, tid, k), so two +arms run at the same SEED see identical initial conditions. This verifies that from the +recorded init_sha256 and then runs McNemar's exact test on the discordant pairs, which +is the correct test for paired binary outcomes. The unpaired two-proportion z-test used +elsewhere is conservative here and understates real differences. +""" +import json, sys +from math import comb + +def load(p): + """Key on (task, episode index), NOT on init_sha256. + + The env seed is a pure function of (seed, tid, k), so episode k is the same + initial condition in every arm run at the same SEED. init_sha256 hashes raw + float64 sim-state bytes and therefore differs between compute nodes for a + logically identical state, which made it useless as a join key.""" + r = json.load(open(p)) + out, sha = {}, {} + for task, eps in r["episodes_detail"].items(): + for e in eps: + out[(task, e["episode"])] = bool(e["success"]) + sha[(task, e["episode"])] = e.get("init_sha256") + return out, r["pooled_SR"], sha + +def mcnemar(b, c): + """two-sided exact binomial on the discordant pairs""" + n = b + c + if n == 0: + return 1.0 + k = min(b, c) + tail = sum(comb(n, i) for i in range(0, k + 1)) / (2 ** n) + return min(1.0, 2 * tail) + +A, srA, shA = load(sys.argv[1]) +B, srB, shB = load(sys.argv[2]) +shared = set(A) & set(B) +print(f" {sys.argv[1].split('/')[-1][:-5]:26s} SR {srA:.3f} n={len(A)}") +print(f" {sys.argv[2].split('/')[-1][:-5]:26s} SR {srB:.3f} n={len(B)}") +nsha = sum(1 for k in shared if shA.get(k) and shA[k] == shB.get(k)) +print(f" matched episodes: {len(shared)}/{min(len(A),len(B))}" + f" ({'PAIRED' if len(shared)==min(len(A),len(B)) else 'PARTIAL'})" + f" [identical init hash on {nsha}/{len(shared)}" + f"{'' if nsha==len(shared) else ' — rest differ only in float bits across nodes'}]") +if not shared: + print(" no shared inits; arms used different seeds"); raise SystemExit +b = sum(1 for k in shared if A[k] and not B[k]) +c = sum(1 for k in shared if B[k] and not A[k]) +agree = len(shared) - b - c +p = mcnemar(b, c) +d = srA - srB +print(f" concordant {agree} A-only {b} B-only {c}") +print(f" diff {d:+.3f} McNemar exact p = {p:.4g}" + f" {'SIGNIFICANT' if p < 0.05 else 'not significant'} at 0.05") diff --git a/frozen/rsm_libero_rsmpi/parl_rsm.py b/frozen/rsm_libero_rsmpi/parl_rsm.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb1a34c8995c9acbf5d00fb91e0404d42f98a42 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/parl_rsm.py @@ -0,0 +1,305 @@ +"""PARL with the RSM occupancy value: rank proposal samples by Q, distill the argmax. + +Faithful to the lane's PARL recipe (MaxSobolMark/PolicyAgnosticRL action +optimisation): sample N action chunks from a base proposal policy, rank them by +Q, keep the best, and distill those into a fresh head with the ordinary flow +loss. Our Q is the RSM occupancy read-out rather than a TD value. + +Why this is different from the Q-filtering already tried, and why that one was +handicapped: PARL's own note is that it "only helps if the proposal policy's N +samples are DIVERSE -- an overtrained flow collapses to the mean, so there is +nothing to rank". Our behaviour clones are trained 120k steps and then the +checkpoint is selected by BEST held-out sampled reconstruction MSE, which selects +precisely the most mean-collapsed checkpoint. Measured here as `proposal_std`, +which is reported before any distillation so a collapsed proposal is visible +rather than silently wasting the run. + +Selection uses depth 1 by default so the recursion never has to re-draw an action +in a latent the flow only imagined, which a raw-feature policy cannot be queried +for. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, make_policy, policy_nll, policy_features, \ + q_recursive, sampled_action_mse +from awr import offline_score + + +@torch.no_grad() +def proposal_diversity(pol, pfeat, d, rng, device, n_states=256, n_samp=16, + temp=1.0, sde=0.0): + """Mean per-dimension std across N samples at a FIXED state. + + This is the quantity PARL lives or dies on. A collapsed proposal gives the + ranker N copies of the same action and the argmax is then meaningless. + """ + b = d.sample_frames(n_states, rng, "val", device) + z = pfeat(b["x"]) + acts = torch.stack([pol.sample(z, b["task"], temp=temp, sde=sde) + for _ in range(n_samp)]) + return float(acts.std(0).mean()), float(b["a"].std()) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--proposal", required=True, help="base policy checkpoint") + ap.add_argument("--out", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--proposal-sde", type=float, default=0.0, + help="noise injected during integration. Unlike temp it " + "follows the learned drift, so candidates stay near " + "the manifold instead of being thrown off it.") + ap.add_argument("--proposal-temp", type=float, default=1.0, + help="scales the proposal's initial noise; >1 widens the " + "candidate set the value ranks over") + ap.add_argument("--n-actions", type=int, default=32, + help="candidates per state (PARL repo default 32)") + ap.add_argument("--select-pool", default="demos", + choices=["demos", "succ", "demos_succ", "all"], + help="states the distillation set is drawn from") + ap.add_argument("--qf-ckpt", default="", + help="rank with the SUPERVISED student Q from rsm_main.py " + "instead of the counterfactual-conditioned occupancy " + "read-out. The student is fit on real (s,a,s') " + "transitions and is the only reader measured to rank " + "actions correctly on this corpus.") + ap.add_argument("--num-keep", type=int, default=4, + help="keep the top-k candidates, not only the arg-max. " + "Distilling a single arg-max concentrates all of the " + "estimator's error into the target.") + ap.add_argument("--margin-quantile", type=float, default=0.7, + help="confidence GATE. Keep only states whose critic margin " + "(best minus median candidate) is above this quantile; " + "apply selection only where the value actually separates " + "candidates, and leave the rest to the anchor. 0 = off.") + ap.add_argument("--include-demos", type=int, default=1, + help="anchor the distillation set on (state, LOGGED demo " + "action) pairs alongside the selected ones. PA-RL's " + "distil set is selected pairs PLUS demonstrations; " + "without the anchor the student has nothing holding it " + "on the demonstration manifold.") + ap.add_argument("--distill-states", type=int, default=200000) + ap.add_argument("--distill-steps", type=int, default=60000) + ap.add_argument("--batch", type=int, default=1024) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=1) + ap.add_argument("--particles", type=int, default=8) + ap.add_argument("--q-pessimism", type=float, default=2.0) + ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"]) + ap.add_argument("--feat-scale", default="center", choices=["zscore", "center"]) + ap.add_argument("--policy-family", default="concat", + choices=["concat", "flow", "gauss"]) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--reward-mode", default="dense", choices=["dense", "terminal", "subgoal", "soft"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--proposal-sde-anneal", type=int, default=0, + help="1 = anneal --proposal-sde to zero by the last integration step") + ap.add_argument("--rank", default="critic", choices=["critic", "random"], + help="random = keep --num-keep random candidates (critic-free control)") + ap.add_argument("--hop-policy", default="", + help="latent-feature BC checkpoint for hops >= 2 (required if --depth > 1)") + ap.add_argument("--crn", type=int, default=1, + help="common random numbers across candidates when scoring") + ap.add_argument("--save-every", type=int, default=10000, + help="save policy_s.pt during distillation; policy_last.pt is always saved") + args = ap.parse_args() + + 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, + 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"] + qstud = qenc = None + if args.qf_ckpt: + 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(d.feat_dim, _c["d_z"], _c["enc_width"]).to(dev) + qenc.load_state_dict(_ck["enc"]); qenc.eval() + qstud = QStudent(_c["d_z"], _ck["d_act"], d.n_task).to(dev) + qstud.load_state_dict(_ck["qf"]); qstud.eval() + print(f"[parl] ranking with the SUPERVISED student Q " + f"(arrival AUC {_ck.get('arrival_auc', float('nan')):.4f})", flush=True) + pfeat, d_pol = policy_features(args, enc, d, cfg, dev) + hop = None + if args.depth > 1: + if not args.hop_policy: + raise SystemExit("--depth > 1 needs --hop-policy") + _hk = torch.load(args.hop_policy, map_location=dev, weights_only=False) + class _HA: pass + _ha = _HA(); [setattr(_ha, k, v) for k, v in _hk["config"].items()] + hop = make_policy(_ha, d, dev, d_z=cfg["d_z"]); hop.load_state_dict(_hk["pol"]); hop.eval() + print(f"[parl] hop policy loaded for depth {args.depth}", flush=True) + + pk = torch.load(args.proposal, map_location=dev, weights_only=False) + # the distilled head inherits the proposal's architecture (width/depth) + args.pol_width = int(pk["config"].get("pol_width", 1024) or 1024) + args.pol_depth = int(pk["config"].get("pol_depth", 4) or 4) + base = make_policy(args, d, dev, d_z=d_pol) + base.load_state_dict(pk["pol"]); base.eval() + + rng = np.random.default_rng(args.seed + 31) + std_a, std_data = proposal_diversity(base, pfeat, d, rng, dev, + temp=args.proposal_temp, + sde=args.proposal_sde) + print(f"[parl] proposal action std {std_a:.5f} vs data action std {std_data:.5f} " + f"(ratio {std_a / max(std_data, 1e-9):.3f})", flush=True) + if std_a < 0.02 * std_data: + print("[parl] WARNING: the proposal has collapsed to the mean; ranking " + "N copies of one action cannot improve anything", flush=True) + + ok = {"demos": d.ep_demo, "succ": d.ep_success, + "demos_succ": d.ep_demo | d.ep_success, + "all": np.ones(d.n_ep, bool)}[args.select_pool] + pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) + + # ---- build the distillation set: argmax_a Q(z, a) over N proposal draws ---- + xs, acts, tasks, margins = [], [], [], [] + got, bs = 0, 256 + sel = np.random.default_rng(args.seed + 41) + t_report = 0 + while got < args.distill_states: + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = sel.choice(pool, size=bs, p=w) + t = d.ep_from[e] + (sel.random(bs) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + with torch.no_grad(): + zc = enc(x) # critic latent for scoring + zp = pfeat(x) # policy features for proposing + cand = torch.stack([base.sample(zp, tk, temp=args.proposal_temp, + sde=args.proposal_sde, + sde_anneal=bool(args.proposal_sde_anneal)) + for _ in range(args.n_actions)]) + N, B, A = cand.shape + qs = [] + zq = qenc(x) if qstud is not None else None + _seed_i = int(args.seed * 1000003 + got) + for i in range(N): + if args.crn: + torch.manual_seed(_seed_i) # same MC noise for every candidate of this batch + if qstud is not None: + q = qstud(zq, cand[i], tk) + else: + q, _ = q_recursive(zc, cand[i], tk, rew=rew, flow=flow, rms=rms, + pol=hop, wend=None, beta=args.beta_q, + gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, + pessimism=args.q_pessimism) + qs.append(q) + Q = torch.stack(qs) # [N, B] + k = max(1, min(args.num_keep, Q.shape[0])) + if args.rank == "random": + topk = torch.stack([torch.randperm(N, device=dev)[:k] for _ in range(B)], 1) # [k, B] + else: + topk = Q.topk(k, dim=0).indices # [k, B] + # margin: how far the best candidate stands above the typical one. + # Small margin means the value does not separate the candidates here. + margin = Q.max(0).values - Q.median(0).values # [B] + ar = torch.arange(B, device=dev) + for j in range(k): + xs.append(x.cpu()); acts.append(cand[topk[j], ar].cpu()) + tasks.append(tk.cpu()); margins.append(margin.cpu()) + got += bs + if got - t_report >= 25600: + t_report = got + print(f"[parl] selected {got}/{args.distill_states}", flush=True) + X = torch.cat(xs); A_ = torch.cat(acts); T = torch.cat(tasks) + Mg = torch.cat(margins) + if args.margin_quantile > 0: + thr = torch.quantile(Mg, args.margin_quantile) + keep = Mg >= thr + print(f"[parl] margin gate q={args.margin_quantile} thr={float(thr):.4f} " + f"keeps {int(keep.sum())}/{len(keep)}", flush=True) + X, A_, T = X[keep], A_[keep], T[keep] + n_sel = len(X) + if args.include_demos: + # the anchor: raw (state, LOGGED action) pairs from demonstrations + dm = np.array([e for e in d.train_eps if d.ep_demo[e]], dtype=np.int64) + ax, aa, at = [], [], [] + need, dr = max(n_sel, 1), np.random.default_rng(args.seed + 51) + while sum(len(t) for t in ax) < need: + w = d.ep_len[dm].astype(np.float64); w /= w.sum() + e = dr.choice(dm, size=1024, p=w) + t = d.ep_from[e] + (dr.random(1024) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + ax.append(torch.from_numpy(d._feat(t))) + aa.append(torch.from_numpy(d._chunk_at(t, e))) + at.append(torch.from_numpy(d.ep_task[e]).long()) + X = torch.cat([X] + ax); A_ = torch.cat([A_] + aa); T = torch.cat([T] + at) + print(f"[parl] demo anchor: {len(X) - n_sel} demo pairs + {n_sel} selected " + f"= {len(X)} ({100.0 * (len(X) - n_sel) / len(X):.1f}% demo share)", + flush=True) + print(f"[parl] distillation set {tuple(X.shape)} from {args.select_pool}", flush=True) + + # ---- distill a FRESH head onto the selected actions ---- + new = make_policy(args, d, dev, d_z=d_pol) + opt = torch.optim.Adam(new.parameters(), lr=args.lr) + ev = np.random.default_rng(args.seed + 77) + best_mse, best_sd, best_step = float("inf"), None, 0 + for step in range(1, args.distill_steps + 1): + idx = torch.randint(0, len(X), (args.batch,)) + xb = X[idx].to(dev); ab = A_[idx].to(dev); tb = T[idx].to(dev) + loss = policy_nll(new, pfeat(xb), tb, ab) + opt.zero_grad(); loss.backward() + torch.nn.utils.clip_grad_norm_(new.parameters(), 1.0); opt.step() + if step % max(1, args.distill_steps // 20) == 0 or step == args.distill_steps: + new.eval() + m = sampled_action_mse(new, d, pfeat, ev, dev, ok) + new.train() + tag = "" + if m == m and m < best_mse: + best_mse, best_step = m, step + best_sd = {k: v.detach().clone() for k, v in new.state_dict().items()} + tag = " <- best" + print(f"[parl] distill {step} loss={float(loss):.4f} " + f"sampled_mse_vs_LOGGED={m:.5f}{tag}", flush=True) + if args.save_every and step % args.save_every == 0: + torch.save({"pol": new.state_dict(), "round": 1, "step": step, "config": vars(args), + "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")}, out / f"policy_s{step}.pt") + # The LAST distilled head is the deployable one: the logged-action MSE proxy selects + # AGAINST the Q-preferred actions PARL is supposed to move toward (and picked a + # checkpoint 0.10 SR below the last one for plain BC). policy_r1.pt keeps the + # proxy-best for comparison; select between them on validation inits. + torch.save({"pol": new.state_dict(), "round": 1, "step": args.distill_steps, "config": vars(args), + "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch"), + "note": "LAST distilled checkpoint"}, out / "policy_last.pt") + if best_sd is not None: + new.load_state_dict(best_sd) + new.eval() + + torch.save({"pol": new.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") + sc = offline_score(d, enc, new, np.random.default_rng(args.seed + 23), dev, + pfeat=pfeat) + sc["proposal_action_std"] = std_a + sc["data_action_std"] = std_data + # NOTE: sampled_mse against the LOGGED action is not the objective here -- a + # working PARL run should move AWAY from the logged action toward the + # Q-preferred one, so a higher value is expected and is not a failure. + (out / "parl.json").write_text(json.dumps( + {"config": vars(args), "score": sc, "best_distill_step": best_step}, + indent=2)) + print(f"[parl] {sc}", flush=True) + print("[parl] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/pooled_test.py b/frozen/rsm_libero_rsmpi/pooled_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d065243928d079355e8e9c12b1f8c7406992d23b --- /dev/null +++ b/frozen/rsm_libero_rsmpi/pooled_test.py @@ -0,0 +1,25 @@ +"""Pool paired McNemar counts across seeds. Each seed is an independent draw of +500 initial conditions on protocol B, so discordant pairs add.""" +import json, sys +from math import comb, sqrt, erfc +def counts(pa, pb): + def load(p): + r=json.load(open(p)); o={} + for t,eps in r["episodes_detail"].items(): + for e in eps: o[(t,e["episode"])]=bool(e["success"]) + return o, r["pooled_SR"] + A,sa=load(pa); B,sb=load(pb); sh=set(A)&set(B) + return (sum(1 for k in sh if A[k] and not B[k]), + sum(1 for k in sh if B[k] and not A[k]), len(sh), sa, sb) +B=C=N=0; srs=[] +for i in range(1,len(sys.argv),2): + b,c,n,sa,sb = counts(sys.argv[i], sys.argv[i+1]) + B+=b; C+=c; N+=n; srs.append((sa,sb)) + print(f" seed pair {i//2}: SR {sa:.3f} vs {sb:.3f} b={b} c={c} diff {sa-sb:+.3f}") +z=(B-C)/sqrt(B+C) if B+C else 0.0 +p=erfc(abs(z)/sqrt(2)) +msr=sum(a for a,_ in srs)/len(srs); mbs=sum(b for _,b in srs)/len(srs) +print(f"\n POOLED over {len(srs)} seeds, {N} paired episodes") +print(f" mean SR {msr:.3f} vs {mbs:.3f} diff {msr-mbs:+.3f}") +print(f" discordant b={B} c={C} z={z:.2f} p={p:.4f} " + f"{'SIGNIFICANT' if p<0.05 else 'NOT significant'} at 0.05") diff --git a/frozen/rsm_libero_rsmpi/probe_actcon.py b/frozen/rsm_libero_rsmpi/probe_actcon.py new file mode 100644 index 0000000000000000000000000000000000000000..f355db89470063931af07e049ed7548d0204881e --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_actcon.py @@ -0,0 +1,95 @@ +"""Which negative does the action-contrast term actually need? + +Two candidate negatives for the flow-matching error at a state z: + (A) shuffle the ACTION only (s, a_rand, s') <- what we implement + (B) shuffle the action AND the target (s, a_rand, s'_rand) + +(B) is the intuitive reading, but it confounds two effects. Its error is large +partly because the conditioning action is wrong and partly because the TARGET is +an unrelated future. A successor that ignores the action entirely still scores +well on (B), because predicting the true future from z is easy and predicting an +unrelated one is hard -- which is exactly the failure the term exists to prevent. + +This measures the decomposition on a trained critic: + e_pos true action, true target + e_act shuffled action, TRUE target -> isolates the action + e_both shuffled action, shuffled target -> action + target confounded + e_tgt TRUE action, shuffled target -> isolates the target +If (e_both - e_pos) is dominated by (e_tgt - e_pos), then (B) is mostly a +target-mismatch test and says little about action sensitivity. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta", type=float, default=0.90) + ap.add_argument("--batch", type=int, default=4096) + ap.add_argument("--reps", type=int, default=8) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + rng = np.random.default_rng(args.seed + 13) + acc = {k: 0.0 for k in ("pos", "act", "both", "tgt")} + with torch.no_grad(): + for _ in range(args.reps): + b = d.sample(args.batch, rng, args.beta, args.beta, "val", dev) + z = enc(b["x_now"]); zf = enc(b["x_fut"]) + y = (zf - z) / rms # true normalised residual + k = torch.rand(args.batch, device=dev) + noise = torch.randn_like(y) + x_k = (1 - k)[:, None] * y + k[:, None] * noise + u = y - noise + p = torch.randperm(args.batch, device=dev) + a_t, a_r = b["a_now"], b["a_now"][p] + # shuffled TARGET: rebuild the path from the permuted residual + y_r = y[p]; n_r = noise[p] + x_k_r = (1 - k)[:, None] * y_r + k[:, None] * n_r + u_r = y_r - n_r + + def err(a, xk, tgt): + return (flow(z, a, b["task"], b["beta"], xk, k) + - tgt).pow(2).mean(-1).mean() + acc["pos"] += float(err(a_t, x_k, u)) + acc["act"] += float(err(a_r, x_k, u)) # action only + acc["both"] += float(err(a_r, x_k_r, u_r)) # action + target + acc["tgt"] += float(err(a_t, x_k_r, u_r)) # target only + for kk in acc: + acc[kk] /= args.reps + print(f"\n{'negative':<34s} {'flow-matching error':>20s} {'gap vs true':>13s}") + print(f"{'(true action, true target)':<34s} {acc['pos']:20.5f} {0.0:13.5f}") + print(f"{'A: shuffled ACTION, true target':<34s} {acc['act']:20.5f} " + f"{acc['act'] - acc['pos']:+13.5f}") + print(f"{' true action, shuffled target':<34s} {acc['tgt']:20.5f} " + f"{acc['tgt'] - acc['pos']:+13.5f}") + print(f"{'B: shuffled action AND target':<34s} {acc['both']:20.5f} " + f"{acc['both'] - acc['pos']:+13.5f}") + ga, gb = acc["act"] - acc["pos"], acc["both"] - acc["pos"] + gt = acc["tgt"] - acc["pos"] + print(f"\naction-only gap as a share of the both-shuffled gap: " + f"{100.0 * ga / gb:.1f}%" if gb else "") + print(f"target-only gap as a share of the both-shuffled gap: " + f"{100.0 * gt / gb:.1f}%" if gb else "") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/probe_action_info.py b/frozen/rsm_libero_rsmpi/probe_action_info.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ed7896cb7a8e9a74f36919134390950265a6f4 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_action_info.py @@ -0,0 +1,97 @@ +"""Does the ACTION carry outcome information beyond the state, in this corpus? + +Everything in this lane hinges on it. The RSM Q takes its action dependence from +the occupancy model extrapolating to actions never observed at that state, which +is unsupervised in the action direction, and was measured to have arbitrary sign. +A directly supervised head has that dependence SUPERVISED by real outcomes. + +Two heads, same latent, same data, same budget, held-out AUC against episode +success: + V(z) state only + Q(z, a) state and the logged action chunk +If Q does not beat V, the action carries nothing beyond the state at this +granularity and NO critic of any kind can rank actions here -- the ceiling is the +data, not the model. If Q does beat V, the action signal exists and the defect is +the occupancy model's extrapolation, which is fixable. + +Reported on rollouts (which contain failures); demonstrations alone are almost +all successes and cannot answer the question. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch +import torch.nn.functional as F + +from data import LiberoRSMData +from is_ope import load_critic +from model import mlp +from train_rsm import auc + + +def train_head(d, enc, dev, use_action, steps, batch, lr, seed, tag): + torch.manual_seed(seed) + d_act = d.chunk * d.adim + din = 264 + (d_act if use_action else 0) + net = mlp([din, 1024, 1024, 1], norm=True).to(dev) + emb = torch.nn.Embedding(d.n_task, 0).to(dev) # task enters via the latent + opt = torch.optim.Adam(net.parameters(), lr=lr) + rng = np.random.default_rng(seed + 3) + for step in range(1, steps + 1): + b = d.sample_frames(batch, rng, "train", dev) + with torch.no_grad(): + z = enc(b["x"]) + x = torch.cat([z, b["a"]], -1) if use_action else z + loss = F.binary_cross_entropy_with_logits(net(x).squeeze(-1), b["succ"]) + opt.zero_grad(); loss.backward(); opt.step() + if step % max(1, steps // 5) == 0: + print(f" [{tag}] {step} bce={float(loss):.4f}", flush=True) + # held-out AUC against EPISODE success + net.eval() + ev = np.random.default_rng(seed + 77) + P, Y = [], [] + with torch.no_grad(): + for _ in range(8): + b = d.sample_frames(2048, ev, "val", dev) + z = enc(b["x"]) + x = torch.cat([z, b["a"]], -1) if use_action else z + P.append(torch.sigmoid(net(x).squeeze(-1)).cpu().numpy()) + Y.append(b["succ"].cpu().numpy()) + return float(auc(np.concatenate(P), np.concatenate(Y))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--steps", type=int, default=20000) + ap.add_argument("--batch", type=int, default=1024) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, _r, _f, _rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + print(f"[probe] corpus success rate {float(d.ep_success.mean()):.3f}", flush=True) + a_v = train_head(d, enc, dev, False, args.steps, args.batch, args.lr, + args.seed, "V(z)") + a_q = train_head(d, enc, dev, True, args.steps, args.batch, args.lr, + args.seed, "Q(z,a)") + print(f"\nheld-out AUC vs episode success") + print(f" V(z) state only {a_v:.4f}") + print(f" Q(z,a) state and action {a_q:.4f}") + print(f" delta {a_q - a_v:+.4f}") + print("\ndelta ~ 0 means the action adds nothing beyond the state at this " + "granularity, and no critic can rank actions on this corpus.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/probe_crn.py b/frozen/rsm_libero_rsmpi/probe_crn.py new file mode 100644 index 0000000000000000000000000000000000000000..085b28516f2b3b3b5f36c991953ae86653062de2 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_crn.py @@ -0,0 +1,105 @@ +"""Is Q blind to the action, or is its ESTIMATOR too noisy to see the action? + +q_recursive draws fresh flow noise on every call, so comparing Q(a1) with Q(a2) +compares two noisy Monte-Carlo estimates. If the per-call noise is larger than the +effect an action has, the comparison is pure coin-flip -- which is exactly what +probe_perturb saw (expert wins 0.483-0.508, mean Q moving 1% when the action is +destroyed). That is equally consistent with "Q ignores the action" and with "the +estimator cannot resolve the action". + +This separates them: + repeat noise |Q(a) - Q'(a)| same action, INDEPENDENT noise + paired effect |Q(a) - Q(a+e)| different action, COMMON noise (CRN) +If the paired effect is comparable to or larger than the repeat noise, the signal +is there and was being drowned; common random numbers recover it. If the paired +effect is ~0 under CRN, the model genuinely ignores the action. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic +from train_rsm import sample_future + + +def q_fixed_noise(enc_z, a, tk, *, rew, flow, rms, beta, gamma, n_particles, + flow_steps, noise): + """Q with the flow's initial noise SUPPLIED, so candidates share it.""" + B, D = enc_z.shape + z = enc_z.repeat_interleave(n_particles, 0) + aa = a.repeat_interleave(n_particles, 0) + t = tk.repeat_interleave(n_particles, 0) + bq = torch.full((z.shape[0],), beta, device=z.device) + x = noise.clone() + for s in range(flow_steps): + k = torch.full((z.shape[0],), 1.0 - s / flow_steps, device=z.device) + x = x + flow(z, aa, t, bq, x, k) / flow_steps + z_end = z + x * rms + r = torch.sigmoid(rew(z_end, t)).view(B, n_particles) + return r.mean(1) / (1 - gamma) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--flow-steps", type=int, default=8) + ap.add_argument("--n", type=int, default=1024) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + pool = np.array([e for e in d.val_eps if d.ep_demo[e]], dtype=np.int64) + if not len(pool): + pool = np.array([e for e in d.train_eps if d.ep_demo[e]], dtype=np.int64) + rng = np.random.default_rng(args.seed + 9) + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = rng.choice(pool, size=args.n, p=w) + t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + + with torch.no_grad(): + z = enc(x) + D = z.shape[1] + kw = dict(rew=rew, flow=flow, rms=rms, beta=args.beta_q, gamma=args.gamma, + n_particles=args.particles, flow_steps=args.flow_steps) + n1 = torch.randn(args.n * args.particles, D, device=dev) + n2 = torch.randn(args.n * args.particles, D, device=dev) + q_a = q_fixed_noise(z, a0, tk, noise=n1, **kw) + q_b = q_fixed_noise(z, a0, tk, noise=n2, **kw) + repeat = (q_a - q_b).abs().mean() + print(f"repeat noise, same action different noise : {float(repeat):.5f}") + print(f"{'noise':>7s} {'|dQ| CRN':>10s} {'expert wins CRN':>16s} " + f"{'|dQ|/repeat':>12s}") + for sig in (0.1, 0.2, 0.4, 0.8): + q_p = q_fixed_noise(z, a0 + sig * torch.randn_like(a0), tk, + noise=n1, **kw) # COMMON noise + dq = (q_a - q_p) + win = float((dq > 0).float().mean()) + print(f"{sig:7.2f} {float(dq.abs().mean()):10.5f} {win:16.3f} " + f"{float(dq.abs().mean() / repeat.clamp_min(1e-9)):12.2f}", + flush=True) + print("\nexpert wins CRN > 0.5 means the model DOES prefer the expert action " + "once the shared noise is removed.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/probe_inits.py b/frozen/rsm_libero_rsmpi/probe_inits.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf86c1210f2a7a2f284d115f6b748adcb17496c --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_inits.py @@ -0,0 +1,46 @@ +"""Characterise the two initial-condition distributions the evaluator can use. + +Protocol A replays LIBERO's 50 stored init states; protocol B lets the task's BDDL +placement region resample. Both are full sim-state vectors, so they are directly +comparable. Reports, per task, how much each distribution actually spreads and +whether A's 50 states are a subset of B's support. +""" +import os, sys, numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from libero.libero import benchmark, get_libero_path +from libero.libero.envs import OffScreenRenderEnv +from pathlib import Path + +bench = benchmark.get_benchmark_dict()["libero_10"]() +rows = [] +for tid in range(10): + task = bench.get_task(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) + inits = np.asarray(bench.get_task_init_states(tid)) # protocol A + fresh = [] + for k in range(50): # protocol B, eval seeds + env.seed(0 * 100003 + tid * 1009 + k) + env.reset() + fresh.append(np.asarray(env.env.sim.get_state().flatten())) + fresh = np.stack(fresh) + n = min(inits.shape[1], fresh.shape[1]) + A, B = inits[:, :n], fresh[:, :n] + # dims that actually vary in either protocol = the randomised object DoF + var = (A.std(0) > 1e-6) | (B.std(0) > 1e-6) + sa, sb = A[:, var].std(0), B[:, var].std(0) + # is every stock state inside the fresh support? + lo, hi = B[:, var].min(0), B[:, var].max(0) + inside = ((A[:, var] >= lo - 1e-6) & (A[:, var] <= hi + 1e-6)).all(1).mean() + rows.append((tid, task.name[:34], int(var.sum()), sa.mean(), sb.mean(), inside)) + print(f"t{tid} {task.name[:34]:34s} varying_dof={int(var.sum()):3d} " + f"std_stock={sa.mean():.4f} std_fresh={sb.mean():.4f} " + f"stock_inside_fresh_support={inside:.2f}", flush=True) + env.close() +print() +print(f"MEAN std_stock={np.mean([r[3] for r in rows]):.4f} " + f"std_fresh={np.mean([r[4] for r in rows]):.4f} " + f"ratio={np.mean([r[4] for r in rows])/max(np.mean([r[3] for r in rows]),1e-9):.2f}x " + f"stock_inside={np.mean([r[5] for r in rows]):.2f}") diff --git a/frozen/rsm_libero_rsmpi/probe_inits.sbatch b/frozen/rsm_libero_rsmpi/probe_inits.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..8f380172f6aceae582026565487b28ee2bf5598c --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_inits.sbatch @@ -0,0 +1,17 @@ +#!/bin/bash +#SBATCH --job-name=probe_inits +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=4 +#SBATCH --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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +PY=$B/venvs/rlinf-libero-eval-venv/bin/python +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl PYTHONUNBUFFERED=1 +_G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)" +export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G" +$PY /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/probe_inits.py diff --git a/frozen/rsm_libero_rsmpi/probe_inits2.py b/frozen/rsm_libero_rsmpi/probe_inits2.py new file mode 100644 index 0000000000000000000000000000000000000000..a75d29fe0353eb974d93872c4bd35f92ff6135d6 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_inits2.py @@ -0,0 +1,39 @@ +"""Exactly what each protocol randomises: per-DoF comparison + the sampler ranges.""" +import os, sys, numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from libero.libero import benchmark, get_libero_path +from libero.libero.envs import OffScreenRenderEnv +from pathlib import Path + +bench = benchmark.get_benchmark_dict()["libero_10"]() +for tid in [0, 3]: + task = bench.get_task(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) + print(f"\n===== t{tid} {task.name} =====") + pi = env.env.placement_initializer + for smp in getattr(pi, "samplers", {}).values() if hasattr(pi, "samplers") else []: + xr = getattr(smp, "x_range", None); yr = getattr(smp, "y_range", None) + rot = getattr(smp, "rotation", None) + if xr is None: continue + xs = float(np.ptp(np.asarray(xr))); ys = float(np.ptp(np.asarray(yr))) + print(f" sampler {smp.name[:38]:38s} x-span {xs*100:6.2f} cm y-span {ys*100:6.2f} cm rot {rot}") + inits = np.asarray(bench.get_task_init_states(tid)) + fresh = [] + for k in range(50): + env.seed(tid*1009 + k); env.reset() + fresh.append(np.asarray(env.env.sim.get_state().flatten())) + fresh = np.stack(fresh) + n = min(inits.shape[1], fresh.shape[1]); A, B = inits[:, :n], fresh[:, :n] + va, vb = A.std(0) > 1e-6, B.std(0) > 1e-6 + both, only_a, only_b = va & vb, va & ~vb, vb & ~va + print(f" DoF varying in BOTH: {both.sum():3d} stdA {A[:,both].std(0).mean():.4f} " + f"stdB {B[:,both].std(0).mean():.4f}") + print(f" DoF varying in STOCK ONLY (A randomises, B holds fixed): {only_a.sum():3d}" + f" stdA {A[:,only_a].std(0).mean() if only_a.any() else 0:.4f}") + print(f" DoF varying in FRESH ONLY: {only_b.sum():3d}") + nq = env.env.sim.model.nq + print(f" (nq={nq}; robot joints are the first ~7-9 dims, objects are free joints after)") + env.close() diff --git a/frozen/rsm_libero_rsmpi/probe_inits2.sbatch b/frozen/rsm_libero_rsmpi/probe_inits2.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..449ab30216af74856425de93022034bb35c9246b --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_inits2.sbatch @@ -0,0 +1,15 @@ +#!/bin/bash +#SBATCH --job-name=probe_inits2 +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 --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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl PYTHONUNBUFFERED=1 +_G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)" +export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G" +$B/venvs/rlinf-libero-eval-venv/bin/python \ + /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero/probe_inits2.py diff --git a/frozen/rsm_libero_rsmpi/probe_perturb.py b/frozen/rsm_libero_rsmpi/probe_perturb.py new file mode 100644 index 0000000000000000000000000000000000000000..cc8552cafa865f8bb464f69f537cacbd8654bbbb --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_perturb.py @@ -0,0 +1,81 @@ +"""Does Q prefer the EXPERT action over noisy perturbations of it? + +This is the question PARL actually asks, and it has unambiguous ground truth: on +a demonstration frame the logged chunk IS the good action, and adding noise can +only make it worse. The earlier action-gap probe compared the logged action +against a DIFFERENT episode's action, which is dominated by on-support versus +off-support and says little about ranking candidates near the mode. + +Reports, per noise scale: the fraction of states where Q ranks the expert action +above the perturbed one, and mean Q as a function of noise. If mean Q RISES with +noise the critic is inverted, and the fix is a sign, not more training. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, q_recursive + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=1) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--n", type=int, default=1024) + ap.add_argument("--pool", default="demos", choices=["demos", "succ", "all"]) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--pessimism", type=float, default=0.0) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + ok = {"demos": d.ep_demo, "succ": d.ep_success, + "all": np.ones(d.n_ep, bool)}[args.pool] + pool = np.array([e for e in d.val_eps if ok[e]], dtype=np.int64) + if not len(pool): + pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) + rng = np.random.default_rng(args.seed + 9) + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = rng.choice(pool, size=args.n, p=w) + t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + + def Q(a): + q, _ = q_recursive(enc(x), a, tk, rew=rew, flow=flow, rms=rms, pol=None, + wend=None, beta=args.beta_q, gamma=args.gamma, + depth=args.depth, n_particles=args.particles, + use_is=False, pessimism=args.pessimism) + return q + + with torch.no_grad(): + q0 = Q(a0) + print(f"expert action: mean Q {float(q0.mean()):+.5f}", flush=True) + print(f"{'noise':>7s} {'mean Q':>10s} {'expert wins':>12s}") + for sig in (0.05, 0.1, 0.2, 0.4, 0.8): + qn = Q(a0 + sig * torch.randn_like(a0)) + win = float((q0 > qn).float().mean()) + print(f"{sig:7.2f} {float(qn.mean()):+10.5f} {win:12.3f}", flush=True) + print("\nexpert wins > 0.5 = the critic prefers the expert action.", flush=True) + print("mean Q RISING with noise = the critic is inverted.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/probe_pessimism.py b/frozen/rsm_libero_rsmpi/probe_pessimism.py new file mode 100644 index 0000000000000000000000000000000000000000..13a8593b4e34a92bacaea1502954a2f7fda91059 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_pessimism.py @@ -0,0 +1,73 @@ +"""Does a disagreement penalty fix the critic's inverted action ranking? + +Measures the held-out action win rate -- how often Q ranks the action actually +taken above a different action taken in the SAME task -- as a function of the +pessimism coefficient. Within-task negatives on purpose: cross-task negatives +measure support violation, not preference. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, train_bc, policy_features + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=3) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--n", type=int, default=1024) + ap.add_argument("--batch", type=int, default=256) + ap.add_argument("--bc-steps", type=int, default=4000) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--policy-family", default="concat") + args = ap.parse_args() + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense") + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + args.d_z = cfg["d_z"] + # continuation policy in the critic's latent space, as the recursion needs + cont = train_bc(d, enc, args, dev, only_success=True, steps=args.bc_steps) + + rng = np.random.default_rng(args.seed + 5) + b = d.sample_frames(args.n, rng, "val", dev) + # within-task negative: another frame's action chunk from the SAME task + task = b["task"].cpu().numpy() + perm = np.arange(len(task)) + for t in np.unique(task): + idx = np.where(task == t)[0] + perm[idx] = rng.permutation(idx) + a_neg = b["a"][torch.from_numpy(perm).to(dev)] + + with torch.no_grad(): + z = enc(b["x"]) + print(f"{'pessimism':>10s} {'win rate':>9s} {'gap':>10s}") + for pe in (0.0, 0.5, 1.0, 2.0, 4.0): + qp, _ = q_recursive(z, b["a"], b["task"], rew=rew, flow=flow, rms=rms, + pol=cont, wend=None, beta=args.beta_q, + gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, + pessimism=pe) + qn, _ = q_recursive(z, a_neg, b["task"], rew=rew, flow=flow, rms=rms, + pol=cont, wend=None, beta=args.beta_q, + gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, + pessimism=pe) + win = float((qp > qn).float().mean()) + print(f"{pe:10.1f} {win:9.3f} {float((qp - qn).mean()):+10.5f}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/probe_qf.py b/frozen/rsm_libero_rsmpi/probe_qf.py new file mode 100644 index 0000000000000000000000000000000000000000..a8dc50e5a32e27c176decf45a7882b480d8707e5 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/probe_qf.py @@ -0,0 +1,76 @@ +"""Does main's SUPERVISED student Q rank actions where our counterfactual Q cannot? + +Same test as probe_perturb/probe_crn, applied to qf(z,a) from rsm_main.py. qf is +fit by regression onto r + gamma(1-done)V(s') using the REAL logged s', so its +action dependence is supervised rather than extrapolated. It is also +deterministic, so there is no sampling noise to cancel -- the comparison is exact. + +expert wins > 0.5 means it prefers the expert chunk over a perturbation of it. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from model import Encoder +from rsm_main import QStudent + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--ckpt", required=True) + ap.add_argument("--n", type=int, default=2048) + ap.add_argument("--pool", default="demos", choices=["demos", "succ", "all"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + dev = "cuda" + ck = torch.load(args.ckpt, map_location=dev, weights_only=False) + c = ck["config"] + d = LiberoRSMData(args.cache, chunk=c["chunk"], k_success=c["k_success"], + seed=args.seed, in_ram=bool(args.in_ram), + reward_mode="terminal", norm_pool=c["norm_pool"]) + enc = Encoder(d.feat_dim, c["d_z"], c["enc_width"]).to(dev) + enc.load_state_dict(ck["enc"]); enc.eval() + qf = QStudent(c["d_z"], ck["d_act"], d.n_task).to(dev) + qf.load_state_dict(ck["qf"]); qf.eval() + + ok = {"demos": d.ep_demo, "succ": d.ep_success, + "all": np.ones(d.n_ep, bool)}[args.pool] + pool = np.array([e for e in d.val_eps if ok[e]], dtype=np.int64) + if not len(pool): + pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) + rng = np.random.default_rng(args.seed + 9) + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = rng.choice(pool, size=args.n, p=w) + t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + + with torch.no_grad(): + z = enc(x) + q0 = qf(z, a0, tk) + print(f"expert chunk: mean Q {float(q0.mean()):+.4f} sd {float(q0.std()):.4f}") + print(f"{'noise':>7s} {'mean Q':>10s} {'expert wins':>12s} {'mean dQ':>10s}") + for sig in (0.05, 0.1, 0.2, 0.4, 0.8): + qn = qf(z, a0 + sig * torch.randn_like(a0), tk) + print(f"{sig:7.2f} {float(qn.mean()):+10.4f} " + f"{float((q0 > qn).float().mean()):12.3f} " + f"{float((q0 - qn).mean()):+10.4f}", flush=True) + # in-support control: a real chunk from a DIFFERENT frame of the same task + tt = tk.cpu().numpy(); perm = np.arange(len(tt)) + for task in np.unique(tt): + idx = np.where(tt == task)[0] + perm[idx] = rng.permutation(idx) + qo = qf(z, a0[torch.from_numpy(perm).to(dev)], tk) + print(f"\nwithin-task other real chunk: expert wins " + f"{float((q0 > qo).float().mean()):.3f}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/proposer_bias_diag.py b/frozen/rsm_libero_rsmpi/proposer_bias_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..b1a52ecbfa1ec085e54a8bf0e78f470754e547b0 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/proposer_bias_diag.py @@ -0,0 +1,105 @@ +"""Does the critic prefer one PROPOSER's action style regardless of state? + +At held-out frames, grouped by where they come from (demo episodes, successful +rollouts, failed rollouts), draw N chunks from the BC-demos policy and N from the +BC-successes policy and score every chunk with the same recursive Q the closed-loop +mixed arms use. Reports, per frame source: mean Q by proposer, how often the +arg-max over the 2N pool lands on a successes chunk, and the Q of the logged action. + +A critic that evaluates ACTIONS should prefer neither proposer on the demo frames +(where the demos policy is at home) in particular. A critic that identifies the +POLICY from the action style prefers the successes proposer everywhere, because the +demos are <1% of the frames it was fit on. + +usage: proposer_bias_diag.py --cache ... --critic ... --hop-policy ... --pol1 + --pol2 [--n 8 --frames 512 --beta 0.95 --depth 3 --particles 16] +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +import numpy as np +import torch +from data import LiberoRSMData +from is_ope import load_critic, make_policy, policy_features, q_recursive + + +def load_pol(path, d, dev, d_pol): + pk = torch.load(path, map_location=dev, weights_only=False) + class _A: pass + a = _A(); [setattr(a, k, v) for k, v in pk["config"].items()] + a.pol_width = int(pk["config"].get("pol_width", 1024) or 1024) + a.pol_depth = int(pk["config"].get("pol_depth", 4) or 4) + pol = make_policy(a, d, dev, d_z=d_pol); pol.load_state_dict(pk["pol"]); pol.eval() + return pol + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) + ap.add_argument("--hop-policy", default=""); ap.add_argument("--pol1", required=True) + ap.add_argument("--pol2", required=True); ap.add_argument("--out", required=True) + ap.add_argument("--n", type=int, default=8); ap.add_argument("--frames", type=int, default=512) + ap.add_argument("--beta", type=float, default=0.95); ap.add_argument("--gamma", type=float, default=0.98) + ap.add_argument("--depth", type=int, default=3); ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--norm-pool", default="all"); ap.add_argument("--reward-mode", default="dense") + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=10, seed=0, in_ram=False, reward_mode=args.reward_mode, + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + enc.eval() + class _P: pass + _p = _P(); _p.policy_features = "raw" + pfeat, d_pol = policy_features(_p, enc, d, cfg, dev) + hop = None + if args.hop_policy: + hop = load_pol(args.hop_policy, d, dev, cfg["d_z"]) + pol1 = load_pol(args.pol1, d, dev, d_pol); pol2 = load_pol(args.pol2, d, dev, d_pol) + rng = np.random.default_rng(args.seed) + val = d.val_eps + groups = {"demo": val[d.ep_demo[val]], + "roll_succ": val[d.ep_success[val] & ~d.ep_demo[val]], + "roll_fail": val[~d.ep_success[val] & ~d.ep_demo[val]]} + res = {} + for g, eps in groups.items(): + if len(eps) == 0: + continue + e = rng.choice(eps, size=args.frames, replace=True) + t = d.ep_from[e] + (rng.random(args.frames) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + a_log = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(args.frames, -1) + with torch.no_grad(): + zc = enc(x); zp = pfeat(x) + c1 = torch.stack([pol1.sample(zp, tk) for _ in range(args.n)]) + c2 = torch.stack([pol2.sample(zp, tk) for _ in range(args.n)]) + cand = torch.cat([c1, c2, a_log[None]], 0) # [2N+1, B, A] + qs = [] + for i in range(cand.shape[0]): + torch.manual_seed(args.seed * 7919 + 1) # CRN across candidates + q, _ = q_recursive(zc, cand[i], tk, rew=rew, flow=flow, rms=rms, pol=hop, + wend=None, beta=args.beta, gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, pessimism=0.0) + qs.append(q) + Q = torch.stack(qs).cpu().numpy() # [2N+1, B] + q1, q2, ql = Q[:args.n], Q[args.n:2 * args.n], Q[-1] + am = Q[:2 * args.n].argmax(0) + # action-style distance: how far each proposer's chunks sit from the logged one + d1 = (c1 - a_log[None]).pow(2).mean(-1).sqrt().mean().item() + d2 = (c2 - a_log[None]).pow(2).mean(-1).sqrt().mean().item() + r = {"frames": int(args.frames), "mean_q_demoBC": float(q1.mean()), "mean_q_succBC": float(q2.mean()), + "mean_q_logged": float(ql.mean()), "argmax_is_succBC": float((am >= args.n).mean()), + "frac_frames_succ_mean_higher": float((q2.mean(0) > q1.mean(0)).mean()), + "within_demoBC_std": float(q1.std(0).mean()), "within_succBC_std": float(q2.std(0).mean()), + "rms_dist_to_logged_demoBC": d1, "rms_dist_to_logged_succBC": d2, + "mean_r_at_frame": float(d.r[t].mean())} + res[g] = r + print(f"[bias] {g:10s} " + " ".join(f"{k}={v:.3f}" for k, v in r.items() if isinstance(v, float)), flush=True) + json.dump({"args": vars(args), "res": res}, open(args.out, "w"), indent=1) + print("[bias] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/q_vs_return_diag.py b/frozen/rsm_libero_rsmpi/q_vs_return_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..0c6ade5b3d36fb8c578d79b66bd86c85367d5a33 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/q_vs_return_diag.py @@ -0,0 +1,85 @@ +"""Policy-evaluation quality of the critics on HELD-OUT logged (state, action) pairs: +Spearman / Pearson between each estimated Q(s,a) and the logged discounted return G_t. + G_sub = (1-g) * sum_k g^k r_{t+k} r = per-frame BDDL subgoal fraction (dense) + G_succ = g^(steps to success) if the episode succeeds else 0 (sparse, terminal) +Arms: RSM restart-Q at depth 1 and 3 (16 particles, shared noise), RSM depth 1 with 256 +particles, the IQL Q trained on the same latent, the reward head alone r_hat(z_t) (no +future), and the per-task constant (the null every pooled correlation has to beat). +Pooled AND within-task (mean of per-task Spearman) are reported: pooled rank correlation +is dominated by task identity (tasks differ in mean subgoal fraction). +usage: q_vs_return_diag.py --cache C --critic ckpt --subgoal-dir D --mask M [--iql iql_q.pt] [--hop hop.pt]""" +import argparse, os, sys, numpy as np, torch +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, make_policy +from scipy.stats import spearmanr, pearsonr + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) +ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="") +ap.add_argument("--iql", default=""); ap.add_argument("--hop", default="") +ap.add_argument("--n", type=int, default=6000); ap.add_argument("--gamma", type=float, default=0.99) +ap.add_argument("--beta", type=float, default=0.98) +a = ap.parse_args() +dev = "cuda" if torch.cuda.is_available() else "cpu" +d = LiberoRSMData(a.cache, chunk=10, seed=0, in_ram=False, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, + success_mask=a.mask, norm_pool="demos") +enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d) +hop = None +if a.hop: + hk = torch.load(a.hop, map_location=dev, weights_only=False) + class _A: pass + ha = _A(); [setattr(ha, k, v) for k, v in hk["config"].items()] + hop = make_policy(ha, d, dev, d_z=cfg["d_z"]); hop.load_state_dict(hk["pol"]); hop.eval() +qnet = None +if a.iql: + from iql import QNet + ck = torch.load(a.iql, map_location=dev, weights_only=False) + qnet = QNet(ck["d_z"], ck["d_act"], ck["n_task"]).to(dev); qnet.load_state_dict(ck["q"]); qnet.eval() +rng = np.random.default_rng(0) +g = a.gamma +# ---- sample held-out frames with their logged action chunk and compute logged returns +eps = d.val_eps; w = d.ep_len[eps].astype(np.float64); w /= w.sum() +e = rng.choice(eps, size=a.n, p=w) +t = d.ep_from[e] + (rng.random(a.n) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64) +G_sub = np.zeros(a.n); G_succ = np.zeros(a.n); to_end = np.zeros(a.n) +for i in range(a.n): + lo, hi = int(t[i]), int(d.ep_to[e[i]]) + rr = np.asarray(d.r[lo:hi], np.float64); k = np.arange(len(rr)) + G_sub[i] = (1 - g) * float((g ** k * rr).sum()) + G_succ[i] = (g ** (hi - lo)) if bool(d.ep_success[e[i]]) else 0.0 + to_end[i] = hi - lo +x = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev) +act = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(a.n, -1) +res = {} +with torch.no_grad(): + z = enc(x) + res["reward head r_hat(z_t) (no future)"] = torch.sigmoid(rew(z, tk)).cpu().numpy() + def rsm(depth, part, crn=True): + out = [] + for i in range(0, a.n, 256): + q, _ = q_recursive(z[i:i+256], act[i:i+256], tk[i:i+256], rew=rew, flow=flow, rms=rms, pol=hop, wend=None, + beta=a.beta, gamma=g, depth=depth, n_particles=part, use_is=False, crn=crn) + out.append(q.cpu()) + return torch.cat(out).numpy() + res["RSM depth 1, 16 particles"] = rsm(1, 16) + res["RSM depth 1, 256 particles"] = rsm(1, 256) + if hop is not None: + res["RSM depth 3, 16 particles"] = rsm(3, 16) + res["RSM depth 3, 256 particles"] = rsm(3, 256) + if qnet is not None: + res["IQL Q(z,a)"] = qnet(z, act, tk).squeeze(-1).cpu().numpy() +tk_np = tk.cpu().numpy() +res["per-task constant (null)"] = np.array([G_sub[tk_np == tt].mean() for tt in tk_np]) +def report(name, q): + rows = [] + for gname, G in (("G_sub", G_sub), ("G_succ", G_succ)): + sp = spearmanr(q, G).correlation; pe = pearsonr(q, G)[0] + wt = [spearmanr(q[tk_np == tt], G[tk_np == tt]).correlation for tt in range(d.n_task) if (tk_np == tt).sum() > 30] + wt = [v for v in wt if v == v] + rows.append(f"{gname}: spearman {sp:+.3f} pearson {pe:+.3f} within-task spearman {np.mean(wt):+.3f}") + print(f"{name:36} | " + " | ".join(rows), flush=True) +print(f"held-out frames n={a.n} from {len(eps)} val episodes; mean G_sub={G_sub.mean():.3f} mean G_succ={G_succ.mean():.3f}") +for k, v in res.items(): + report(k, np.asarray(v, np.float64)) +print("[diag] DONE") diff --git a/frozen/rsm_libero_rsmpi/recheck128_cpu.sbatch b/frozen/rsm_libero_rsmpi/recheck128_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f7ad1280f16c095baf2ca5d548765e99e191f872 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/recheck128_cpu.sbatch @@ -0,0 +1,32 @@ +#!/bin/bash +#SBATCH --job-name=recheck128 +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export 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=osmesa +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export 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/recheck_encoding.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --n-ep 6 --frames 4 --pool rollsucc --src-res 128 --flips none + +echo "[cap] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_rsmpi/recheckD_cpu.sbatch b/frozen/rsm_libero_rsmpi/recheckD_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..6c16f87851322228a6b5fcb2c7cba2ad91747774 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/recheckD_cpu.sbatch @@ -0,0 +1,32 @@ +#!/bin/bash +#SBATCH --job-name=recheckD +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export 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=osmesa +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export 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/recheck_encoding.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --n-ep 6 --frames 4 --pool demos + +echo "[cap] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_rsmpi/recheck_cpu.sbatch b/frozen/rsm_libero_rsmpi/recheck_cpu.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f44b969cbb26f1766f0bec36775f8fe7c8ccb3df --- /dev/null +++ b/frozen/rsm_libero_rsmpi/recheck_cpu.sbatch @@ -0,0 +1,32 @@ +#!/bin/bash +#SBATCH --job-name=recheck +#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.err +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export 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=osmesa +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export 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/recheck_encoding.py \ + --cache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo \ + --n-ep 6 --frames 4 + +echo "[cap] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_rsmpi/recheck_encoding.py b/frozen/rsm_libero_rsmpi/recheck_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..80d1cb52af890616d1ea25d6a38b82afb8816021 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/recheck_encoding.py @@ -0,0 +1,157 @@ +"""Was the ROLLOUT cache built with the same image preprocessing as the evaluator? + +Hypothesis 2 of williamd4112/gen_q#251. The demo cache and the rollout cache have +different producers, and demo frames sit 48.7-61.5 from the nearest rollout frame +against 7.5-9.2 within the rollout cloud. `to224`'s own docstring records that uint8 +quantisation alone moves the latent 3 sigma on the dimensions that matter and cost a +working policy 0.46 -> 0/50, with cosine similarity 0.999898 hiding it completely. + +So: take a rollout episode's OWN raw frames (the parquets carry `image` and +`wrist_image`), push them through the EVALUATOR's exact path, and compare against that +frame's cached latent. Agreement means the rollout cache matches the evaluator and the +support gap is real scene difference. Disagreement means every rollout latent is in a +space the evaluator never produces, and no policy or critic trained on them can be read +online. + +Reports L2 in z-scored feature units, so the numbers are directly comparable to the +48.7-61.5 / 7.5-9.2 gap measured in #251 -- cosine similarity is deliberately NOT the +headline for the reason above. +""" +from __future__ import annotations +import argparse, importlib.util, io, os, re, sys +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from eval_closed_loop import to224, BUILDER + +_spec = importlib.util.spec_from_file_location("ogpo_rc", BUILDER) +ogpo = importlib.util.module_from_spec(_spec) +sys.modules["ogpo_rc"] = ogpo +_spec.loader.exec_module(ogpo) + +PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$") +PQ_ROOT = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1" + + +def decode(cell): + """Parquet image cell -> HxWx3 uint8. LeRobot stores either raw bytes (PNG/JPEG) + or a nested list; handle both rather than guessing.""" + v = cell.as_py() if hasattr(cell, "as_py") else cell + if isinstance(v, dict) and "bytes" in v: + v = v["bytes"] + if isinstance(v, (bytes, bytearray)): + from PIL import Image + return np.asarray(Image.open(io.BytesIO(v)).convert("RGB"), np.uint8) + a = np.asarray(v) + if a.dtype != np.uint8: + a = (a * 255).round().clip(0, 255).astype(np.uint8) if a.max() <= 1.001 else a.astype(np.uint8) + if a.ndim == 1: + n = int(round((a.size / 3) ** 0.5)); a = a.reshape(n, n, 3) + if a.ndim == 3 and a.shape[0] == 3: + a = a.transpose(1, 2, 0) + return a + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--n-ep", type=int, default=6) + ap.add_argument("--frames", type=int, default=4, help="frames checked per episode") + ap.add_argument("--pool", default="rollsucc", choices=["rollsucc", "demos"], + help="demos re-encodes from the LIBERO hdf5 (agentview_rgb / " + "eye_in_hand_rgb); the demo cache's npz holds no images") + ap.add_argument("--src-res", type=int, default=0, + help="resize the source image to this square resolution BEFORE " + "to224, emulating a camera that renders at that size. The " + "rollout parquets are 256x256; the evaluator renders at 128.") + ap.add_argument("--flips", default="both,none,ud,lr", + help="flip conventions to try; the evaluator uses img[::-1,::-1] = both") + args = ap.parse_args() + + import pyarrow.parquet as pq + dev = "cuda" if torch.cuda.is_available() else "cpu" + print(f"[rc] device {dev}", flush=True) + tower = ogpo.build_paligemma(dev) + from libero.libero import benchmark + bench = benchmark.get_benchmark_dict()["libero_10"]() + + C = Path(args.cache) + m = np.load(C / "meta.npz", allow_pickle=True) + fr, to = m["ep_from"].astype(int), m["ep_to"].astype(int) + dem = m["ep_demo"].astype(bool); suc = m["ep_success"].astype(bool) + tk = m["ep_task"]; dim = int(m["dim"]) + Z = np.load(C / "z.f16.npy", mmap_mode="r").reshape(-1, dim) + st = np.load(C / "feat_stats_demos.npz") + sd_vis = st["sd"][:dim] # visual block only + + flips = {"both": (slice(None, None, -1), slice(None, None, -1)), + "none": (slice(None), slice(None)), + "ud": (slice(None, None, -1), slice(None)), + "lr": (slice(None), slice(None, None, -1))} + want = [f for f in args.flips.split(",") if f in flips] + + def frames_of(e): + """(n_frames, getter(r) -> (agentview, wrist)) for episode e, from the raw + image source that produced its cached latents.""" + if args.pool == "rollsucc": + g = PAT.search(str(m["ep_src"][e])) + t, b, i, idx = g.groups() + p = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + if not os.path.exists(p): + return 0, None + tb = pq.read_table(p, columns=["image", "wrist_image"]) + return tb.num_rows, (lambda r: (decode(tb["image"][int(r)]), + decode(tb["wrist_image"][int(r)]))) + import h5py + sp = str(m["ep_src"][e]) # .../_demo/demo_7.npz + tdir = Path(sp).parent.name # _demo + k = Path(sp).stem # demo_7 + H = h5py.File(f"/data/pulkitag/users/rli14/libero_datasets/libero_10/{tdir}.hdf5", "r") + ob = H["data"][k]["obs"] + return ob["agentview_rgb"].shape[0], (lambda r: (np.asarray(ob["agentview_rgb"][int(r)]), + np.asarray(ob["eye_in_hand_rgb"][int(r)]))) + + eps = np.where((suc & ~dem) if args.pool == "rollsucc" else dem)[0][:args.n_ep] + print(f"[rc] pool={args.pool}: {len(eps)} episodes, {args.frames} frames each\n", flush=True) + agg = {f: [] for f in want} + for e in eps: + t = int(tk[e]) + n_src, get = frames_of(e) + if get is None: + print(f" ep {e}: source missing"); continue + ids = ogpo.tokenize_prompt(bench.get_task(t).language) + n = min(n_src, int(to[e] - fr[e])) + rows = np.linspace(0, n - 1, args.frames).astype(int) + for r in rows: + im0, im1 = get(r) + if args.src_res and im0.shape[0] != args.src_res: + from PIL import Image + _rs = lambda a: np.asarray(Image.fromarray(a).resize( + (args.src_res, args.src_res), Image.BILINEAR), np.uint8) + im0, im1 = _rs(im0), _rs(im1) + z_cache = np.asarray(Z[fr[e] + int(r)], np.float32) + for f in want: + a, bb = flips[f] + cams = [to224(im0[a, bb])[None], to224(im1[a, bb])[None]] + z = np.concatenate( + [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0] + # L2 in z-scored units: comparable to the #251 support-gap numbers + agg[f].append(float(np.linalg.norm((z - z_cache) / sd_vis))) + print(f" ep {e} t{t} done " + " ".join( + f"{f}={np.mean(agg[f][-args.frames:]):.2f}" for f in want), flush=True) + + print(f"\n=== pool={args.pool}: re-encode vs cached latent, L2 in z-scored units ===") + print("(reference from #251: rollout->nearest rollout 7.5-9.2, demo->nearest rollout 48.7-61.5)") + for f in want: + v = np.array(agg[f]) + print(f" flip={f:<5} n={len(v):<4} mean={v.mean():>8.2f} min={v.min():>8.2f} max={v.max():>8.2f}") + best = min(want, key=lambda f: np.mean(agg[f])) + print(f"\nbest convention: {best} (evaluator uses 'both')") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/reencode.sbatch b/frozen/rsm_libero_rsmpi/reencode.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..f2c96c460c5510608d788af4f4a698d55e357514 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/reencode.sbatch @@ -0,0 +1,28 @@ +#!/bin/bash +#SBATCH --job-name=reenc +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=64G +#SBATCH --time=6: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 +# Re-encode rollout latents at the evaluator's 128 camera resolution (i251). +# Same venv + env as eval_slurm.sbatch so the encoder is the evaluator's encoder. +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export REPO_PATH=$B/external/rlinf PYTHONPATH="$B/external/rlinf:${PYTHONPATH:-}" +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')" +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +OUT=${OUT:-/data/pulkitag/scratch/rli14/pi05_lib10_ogpo_fl15_v1_r128} +$B/venvs/rlinf-libero-eval-venv/bin/python $G/reencode_rollouts.py \ + --out "$OUT" --cam-res "${CAMRES:-128}" --shard "${SHARD:-0}" --num-shards "${NSHARDS:-1}" \ + ${ONLYCACHE:+--only-cache "$ONLYCACHE"} ${LIMIT:+--limit "$LIMIT"} +echo "[re] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_rsmpi/reencode_rollouts.py b/frozen/rsm_libero_rsmpi/reencode_rollouts.py new file mode 100644 index 0000000000000000000000000000000000000000..32b31d495e4fb47d84528ba37d581a35876404d7 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/reencode_rollouts.py @@ -0,0 +1,121 @@ +"""Re-encode the rollout corpus at the resolution the evaluator actually renders. + +Finding (williamd4112/gen_q#251): the rollout latents in `pi05_lib10_ogpo_fl15_v1` +were encoded from the collector's 256x256 renders. The closed-loop evaluator renders +at 128x128 (`camera_heights=128`), and so does the demo hdf5. Re-encoding a rollout +frame through the evaluator's own path puts it 74.97 z-scored units from its cached +latent (within-cloud scale 7.5-9.2; demo cache re-encoded the same way: 4.27). Every +rollout latent is therefore off the manifold the evaluator produces -- which is why +BC on rollout successes is 0/500 with held-out action MSE 0.0008, and why a critic +trained on a 90%-rollout corpus is read off-support online. + +This rebuilds the rollout npz tree with latents from: parquet image (256, stored +upright) -> 128 (PIL bilinear, emulating the 128 camera) -> 224 (PIL bilinear, the +builder's own step) -> the SAME encoder. No flip: the parquet images are already in +the serving orientation (verified visually and by L2: flip=none matches at 4.26). +proprio / actions / success / prompt / task_index are copied from the original npz, +which are bit-identical to the parquet fields. + +Output tree mirrors the input so pack.py runs unchanged with --src . +""" +from __future__ import annotations +import argparse, importlib.util, io, os, re, sys, time +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from eval_closed_loop import BUILDER +from recheck_encoding import decode, PAT, PQ_ROOT + +_spec = importlib.util.spec_from_file_location("ogpo_re", BUILDER) +ogpo = importlib.util.module_from_spec(_spec) +sys.modules["ogpo_re"] = ogpo +_spec.loader.exec_module(ogpo) + + +def prep(img, cam_res): + """uint8 HxWx3 (upright) -> uint8 224x224x3 via the camera resolution.""" + from PIL import Image + im = Image.fromarray(img) + if im.size != (cam_res, cam_res): + im = im.resize((cam_res, cam_res), Image.BILINEAR) + if im.size != (224, 224): + im = im.resize((224, 224), Image.BILINEAR) # builder's own step + return np.asarray(im, np.uint8) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", default="/data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1") + ap.add_argument("--out", required=True) + ap.add_argument("--cam-res", type=int, default=128) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--num-shards", type=int, default=1) + ap.add_argument("--only-cache", default="", + help="meta.npz of a cache: re-encode only the episodes it uses " + "(the 4,500-rollout subset first, the full corpus after)") + ap.add_argument("--batch", type=int, default=128) + ap.add_argument("--limit", type=int, default=0, help="smoke: stop after N episodes") + args = ap.parse_args() + + import pyarrow.parquet as pq + dev = "cuda" if torch.cuda.is_available() else "cpu" + tower = ogpo.build_paligemma(dev) + + if args.only_cache: + m = np.load(args.only_cache, allow_pickle=True) + srcs = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] + else: + srcs = sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) + srcs = srcs[args.shard::args.num_shards] + if args.limit: + srcs = srcs[:args.limit] + print(f"[re] shard {args.shard}/{args.num_shards}: {len(srcs)} episodes -> {args.out} " + f"(cam_res={args.cam_res}, device={dev})", flush=True) + + t0 = time.time(); n_done = n_skip = 0 + for k, sp in enumerate(srcs): + rel = Path(sp).relative_to(args.src) + op = Path(args.out) / rel + if op.exists(): + n_skip += 1; continue + g = PAT.search(sp) + t, b, i, idx = g.groups() + pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + if not os.path.exists(pp): + print(f"[re] MISSING parquet for {rel}", flush=True); continue + z0 = np.load(sp, allow_pickle=True) + T = int(z0["z"].shape[0]) + tb = pq.read_table(pp, columns=["image", "wrist_image"]) + if tb.num_rows < T: + print(f"[re] {rel}: parquet has {tb.num_rows} rows < npz {T}; truncating", + flush=True); T = tb.num_rows + ids = ogpo.tokenize_prompt(str(z0["prompt"])) + zs = [] + for cam in ("image", "wrist_image"): + frames = np.stack([prep(decode(tb[cam][j]), args.cam_res) for j in range(T)]) + outs = [] + for s in range(0, T, args.batch): + outs.append(ogpo.encode_frames(tower, frames[s:s + args.batch], ids, dev, + args.batch)) + zs.append(np.concatenate(outs, 0)) + z = np.concatenate(zs, 1).astype(np.float16) # [T, 4096] base||wrist + assert z.shape == (T, z0["z"].shape[1]), (z.shape, z0["z"].shape) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=z0["proprio"][:T], actions=z0["actions"][:T], + success=z0["success"], prompt=z0["prompt"], task_index=z0["task_index"]) + os.replace(tmp, op) + n_done += 1 + if n_done % 25 == 0: + el = time.time() - t0 + print(f"[re] {k+1}/{len(srcs)} done={n_done} skip={n_skip} " + f"{el/n_done:.1f}s/ep eta {(len(srcs)-k-1)*el/n_done/60:.0f} min", flush=True) + print(f"[re] DONE shard {args.shard}: {n_done} written, {n_skip} existed", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/report.py b/frozen/rsm_libero_rsmpi/report.py new file mode 100644 index 0000000000000000000000000000000000000000..e3beba245705a8fdeaaa97408d4bdeb020329fd2 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/report.py @@ -0,0 +1,96 @@ +"""Collect run artifacts into one honest table. + +Reports what was actually measured and labels what was NOT. In particular the +offline metrics here are NOT closed-loop LIBERO success, so they cannot by +themselves support a claim of beating behaviour cloning; that requires the lane's +per-task closed-loop eval. This script prints the distinction rather than hiding it. +""" +from __future__ import annotations +import argparse, json +from pathlib import Path + + +def row(k, v, w=34): + print(f" {k:<{w}} {v}") + + +def winrate_ci(win, n, z=1.96): + """Wilson interval for a win rate. The action gap is a heavy-tailed mean and + swings between evals (+0.045 / +0.063 / +0.018 on consecutive checkpoints); + the win rate over the same pairs is the stable statistic, so report it with + an interval rather than quoting a point estimate.""" + if not n: + return (float("nan"), float("nan")) + p = win + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / d + return (c - h, c + h) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--critic", default="") + ap.add_argument("--ope-signal", default="") + ap.add_argument("--ope-null", default="") + ap.add_argument("--awr", default="") + a = ap.parse_args() + + if a.critic: + h = json.loads((Path(a.critic) / "history.json").read_text()) + last, best = h[-1], max(h, key=lambda r: r["q_action_gap"]) + print("\n== CRITIC (occupancy + reward latent) ==") + row("reward AUC (held-out)", f"{last['reward_auc']:.4f}") + row("occupancy CFM val loss", f"{last['cfm_val']:.4f}") + row("latent std min (collapse guard)", f"{last['latent_std_min']:.4f}") + lo, hi = winrate_ci(last["q_action_winrate"], 1024) + row("ACTION gap (headline)", f"{last['q_action_gap']:+.5f} " + f"(win {last['q_action_winrate']:.3f}, 95% CI [{lo:.3f},{hi:.3f}])") + bh = last.get("by_horizon", {}) + for k, v in bh.items(): + blo, bhi = winrate_ci(v["action_winrate"], v["n"]) + sig = "" if blo <= 0.5 <= bhi else " <-- excludes chance" + row(f" frames-to-end {k}", + f"gap {v['action_gap']:+.5f} win {v['action_winrate']:.3f} " + f"[{blo:.3f},{bhi:.3f}] n={v['n']}{sig}") + row(" best over training", f"{best['q_action_gap']:+.5f} @ step {best['step']}") + row("state success AUC", f"{last['q_success_auc']:.4f}") + print(" NOTE action gap is the metric that matters: COLLAPSE_ANALYSIS shows a") + print(" state-ranking value with a flat action gap dies in closed loop.") + + for tag, path in (("SIGNAL pi=BC(successes)", a.ope_signal), + ("NULL pi=BC(all)~mu", a.ope_null)): + if not path: + continue + r = json.loads((Path(path) / "report.json").read_text()) + c, v = r["calibration"], r["value"] + print(f"\n== OPE GATE :: {tag} ==") + row("E_mu[w] after calibration", f"{c['E_mu[w_endpoint]']:.4f} (target 1.000)") + row("calibration factor applied", f"{c['calib_scale']:.3f}") + row("E_mu[W] raw chunk product", f"{c['E_mu[W_chunk]']:.4f} (target 1.000)") + row("corr(endpoint w, chunk W)", f"{c['corr_w_vs_W']:.4f}") + row("weight ESS fraction", f"{c['ess_frac']:.3f}") + row("particle ESS fraction", f"{v['ess_particles']:.3f}") + row("success AUC with IS", f"{v['auc_success_IS']:.4f}") + row("success AUC without IS", f"{v['auc_success_noIS']:.4f}") + row("relative |dQ| from IS", f"{v['rel_shift_IS_vs_noIS']:.4f}") + row("expectation", v["gate_expectation"]) + + if a.awr: + L = json.loads((Path(a.awr) / "loop.json").read_text()) + print("\n== AWR LOOP ==") + row("pi_0 offline score", json.dumps(L["pi_0"])) + for r in L["rounds"]: + adv = r["awr"][-1] if r["awr"] else {} + row(f"round {r['round']} mean|adv|", + f"{adv.get('mean_abs_adv', float('nan')):.4f} " + f"(smolvla null result was 0.0190)") + row(f"round {r['round']} score", json.dumps(r["score"])) + + print("\nNOT MEASURED HERE: closed-loop LIBERO success. Every number above is") + print("offline. Beating BC on demos (0.584 +- 0.025 step-matched in this lane)") + print("requires the per-task closed-loop harness and is not claimed by this table.") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/report_arms.py b/frozen/rsm_libero_rsmpi/report_arms.py new file mode 100644 index 0000000000000000000000000000000000000000..5dcd3bdd892113d594ffe67080fcee9a606002f8 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/report_arms.py @@ -0,0 +1,95 @@ +"""The headline table: closed-loop LIBERO-10 success and throughput, four arms. + +Throughput = pooled_SR * max_steps / mean_steps, reported two ways because they +answer different questions: + succ : mean steps over SUCCESSFUL episodes -- how fast it is when it works + all : mean steps over ALL episodes -- a failure burns the full horizon, so + this penalises failing twice (once in SR, once in wasted time) + +Success rates are pooled over all task-episodes and carry a Wilson interval. +Arms are compared against A_bc_demos, the BC-on-demonstrations bar an RSM recipe +has to clear; a difference is only called a win when the intervals separate. +""" +from __future__ import annotations +import argparse, json +from pathlib import Path + +ARMS = [("LANE_CONTROL", "lane bcdemos (reference bar)"), + ("A_bc_demos", "BC on demos, our pipeline"), + ("B_bc_succ", "behaviour-policy extraction"), + ("C_iql", "IQL critic + AWR"), + ("D_rsm", "RSM critic + AWR (ours)")] + + +def wilson(k, n, z=1.96): + if not n: + return float("nan"), float("nan") + p = k / n + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / d + return c - h, c + h + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--eval-dir", default="/data/pulkitag/users/rli14/rsm_libero_runs/eval") + a = ap.parse_args() + d = Path(a.eval_dir) + + got = {} + for tag, _ in ARMS: + f = d / f"{tag}.json" + if f.exists(): + got[tag] = json.loads(f.read_text()) + + print("\n== CLOSED-LOOP LIBERO-10 (10 tasks x 10 inits, max 520 steps) ==") + print(f" {'arm':<12} {'what it is':<30} {'succ/n':>9} {'pooled SR':>10} " + f"{'95% CI':>16} {'thr_succ':>9} {'thr_all':>8}") + for tag, what in ARMS: + r = got.get(tag) + if r is None: + print(f" {tag:<12} {what:<30} {'--':>9} {'not yet run':>10}") + continue + k, n = r["successes"], r["episodes"] + lo, hi = wilson(k, n) + print(f" {tag:<12} {what:<30} {f'{k}/{n}':>9} {r['pooled_SR']:>10.3f} " + f"{f'[{lo:.3f},{hi:.3f}]':>16} {r['throughput_succ']:>9.3f} " + f"{r['throughput_all']:>8.3f}") + + # The bar is the REFERENCE policy when we have it: comparing our arms + # against our own broken BC would let a 0.02 arm look like a "win". + base = got.get("LANE_CONTROL") or got.get("A_bc_demos") + if base: + blo, bhi = wilson(base["successes"], base["episodes"]) + print(f"\n== vs the BC-on-demos bar ({base['pooled_SR']:.3f}) ==") + for tag, what in ARMS: + if got.get(tag) is base: + continue + r = got.get(tag) + if r is None: + continue + lo, hi = wilson(r["successes"], r["episodes"]) + if lo > bhi: + v = "WIN (intervals separate)" + elif hi < blo: + v = "LOSS (intervals separate)" + else: + v = "no separation at 95%" + print(f" {tag:<12} {r['pooled_SR'] - base['pooled_SR']:+.3f} {v}") + + if got: + print("\n== per-task pooled SR ==") + tasks = sorted({t for r in got.values() for t in r["per_task"]}) + print(f" {'task':<52}" + "".join(f"{t:>12}" for t, _ in ARMS if t in got)) + for tk in tasks: + print(f" {tk[:50]:<52}" + + "".join(f"{got[t]['per_task'].get(tk, float('nan')):>12.2f}" + for t, _ in ARMS if t in got)) + missing = [t for t, _ in ARMS if t not in got] + if missing: + print(f"\n NOT YET MEASURED: {', '.join(missing)} -- the table above is incomplete.") + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/rerender.sbatch b/frozen/rsm_libero_rsmpi/rerender.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7033c7b65baa2ecf815376047760da2e9a447ee9 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/rerender.sbatch @@ -0,0 +1,28 @@ +#!/bin/bash +#SBATCH --job-name=rerender +#SBATCH --account=vision-pulkitag +#SBATCH --gres=gpu:1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=64G +#SBATCH --time=6: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 +# Re-encode rollout latents at the evaluator's 128 camera resolution (i251). +# Same venv + env as eval_slurm.sbatch so the encoder is the evaluator's encoder. +set -uo pipefail +B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation +S=/data/pulkitag/users/rli14/rlinf_recap_task_expansion +export REPO_PATH=$B/external/rlinf PYTHONPATH="$B/external/rlinf:${PYTHONPATH:-}" +export LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export HF_HOME=/data/pulkitag/users/rli14/hf_cache HF_HUB_OFFLINE=1 +export HF_TOKEN=$(cat /data/pulkitag/users/rli14/hf_cache/token 2>/dev/null || echo "") +export HUGGINGFACE_HUB_TOKEN=$HF_TOKEN +export FL15_TASKS="$(tr '\n' ',' < $B/logs/09052026_lib10_tasks.txt | sed 's/,,*/,/g; s/,$//')" +G=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_libero +OUT=${OUT:-/data/pulkitag/scratch/rli14/pi05_lib10_ogpo_fl15_v1_rr} +$B/venvs/rlinf-libero-eval-venv/bin/python $G/rerender_rollouts.py \ + --out "$OUT" --shard "${SHARD:-0}" --num-shards "${NSHARDS:-1}" \ + ${ONLYCACHE:+--only-cache "$ONLYCACHE"} ${LIMIT:+--limit "$LIMIT"} ${VALDEMOS:+--validate-demos "$VALDEMOS"} ${VALROLL:+--validate-rollouts "$VALROLL"} --cam-res "${CAMRES:-256}" --pool "${POOL:-rollouts}" ${DEMOCACHE:+--demo-cache "$DEMOCACHE"} +echo "[re] rc=$? $(date -u +%T)" diff --git a/frozen/rsm_libero_rsmpi/rerender_rollouts.py b/frozen/rsm_libero_rsmpi/rerender_rollouts.py new file mode 100644 index 0000000000000000000000000000000000000000..0b752e30d6a1025e0356829db4739fb70798fbae --- /dev/null +++ b/frozen/rsm_libero_rsmpi/rerender_rollouts.py @@ -0,0 +1,318 @@ +"""Re-render every rollout frame INSIDE the evaluator's environment, then encode. + +Why not resize the collector's 256x256 pixels (reencode_rollouts.py)? Measured: a +256->128 bilinear downsample lands in a THIRD region -- 63.7 from the live evaluator +feature, 71.5 from the demo cloud, 81.5 from the old rollout cloud -- no closer to the +evaluator than the cache it was meant to fix. SigLIP features do not survive an +approximate raster (to224's docstring: uint8 rounding alone is 3 sigma). + +So do the only thing that is evaluator-consistent BY CONSTRUCTION: the parquets log +`sim_state` for every frame; set it in the evaluator's own OffScreenRenderEnv +(camera_heights=128, EGL), read both cameras exactly as eval_closed_loop does +([::-1, ::-1], to224), encode with the evaluator's encoder. This is the admissibility +rule applied to features: a latent is admissible only if the eval environment can +produce it. + +Built-in validation (--validate-demos N): the demo hdf5 stores `states`; re-rendering +those through this path must land ~4 z-scored units from the demo cache (which was +built from the hdf5's own recorded images). If it does not, the path is wrong and no +rollout output should be trusted. + +Output mirrors the input npz tree so pack.py runs unchanged. Idempotent (skips +existing), atomic writes, requeue-safe. +""" +from __future__ import annotations +import argparse, importlib.util, os, re, sys, time +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from eval_closed_loop import BUILDER, to224, _eef_ori +from recheck_encoding import PAT, PQ_ROOT + +_spec = importlib.util.spec_from_file_location("ogpo_rr", BUILDER) +ogpo = importlib.util.module_from_spec(_spec) +sys.modules["ogpo_rr"] = ogpo +_spec.loader.exec_module(ogpo) + +DEMO_H5 = os.environ.get("RSM_DEMO_H5", "/data/pulkitag/users/rli14/libero_datasets/libero_10") + + +class Renderer: + """One evaluator env per task, reused across episodes.""" + def __init__(self, cam_res=128): + self.cam_res = cam_res + from libero.libero import benchmark, get_libero_path + from libero.libero.envs import OffScreenRenderEnv + self.bench = benchmark.get_benchmark_dict()["libero_10"]() + self.get_libero_path = get_libero_path; self.Env = OffScreenRenderEnv + self.envs, self.ids = {}, {} + + def env(self, tid): + # ONE live env at a time. robosuite's offscreen EGL context is shared across + # OffScreenRenderEnv instances in a process: with several alive, a render can + # come from whichever model last touched the context (measured: a task-0 state + # rendered as task-4's mugs and plates; one frame came back black). The + # evaluator builds one env per task and closes it; do the same. + if tid not in self.envs: + for _k in list(self.envs): + try: + self.envs[_k].close() + except Exception: + pass + self.envs.pop(_k, None) + t = self.bench.get_task(tid) + e = self.Env(bddl_file_name=str(Path(self.get_libero_path("bddl_files")) + / t.problem_folder / t.bddl_file), + camera_heights=self.cam_res, camera_widths=self.cam_res) + e.reset(); e.step(np.zeros(7)) + self.envs[tid] = e; self.ids[tid] = ogpo.tokenize_prompt(t.language) + return self.envs[tid], self.ids[tid] + + def frames(self, tid, states): + """states [T, nq+nv] -> (agent [T,224,224,3], wrist [T,224,224,3], proprio [T,8])""" + env, _ = self.env(tid) + sim = env.env.sim + A, W, P = [], [], [] + for st in states: + sim.set_state_from_flattened(np.asarray(st, np.float64)); sim.forward() + # Python-side visuals are NOT in the MuJoCo state: the stove burner is a + # site_rgba alpha in sim.model toggled by set_visualization() from + # turn_on(qpos), which the env runs inside step() via _check_success -> + # _post_process. Replay that update or a mid-episode kitchen frame renders + # with the burner off while the logged image has it on (measured: kitchen + # tasks drift 10-37, living-room tasks 3-4). + try: + env.env._check_success() + except Exception: + pass + if hasattr(env.env, "set_visualization"): + env.env.set_visualization() + sim.forward() + obs = env.env._get_observations(force_update=True) + A.append(to224(obs["agentview_image"][::-1, ::-1])) + W.append(to224(obs["robot0_eye_in_hand_image"][::-1, ::-1])) + P.append(np.concatenate([obs["robot0_eef_pos"], _eef_ori(obs), + obs["robot0_gripper_qpos"]]).astype(np.float32)) + return np.stack(A), np.stack(W), np.stack(P) + + +def encode(tower, ids, A, W, dev, bs): + za = ogpo.encode_frames(tower, A, ids, dev, bs) + zw = ogpo.encode_frames(tower, W, ids, dev, bs) + return np.concatenate([za, zw], 1).astype(np.float16) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", default="/data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1") + 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("--only-cache", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--batch", type=int, default=128) + ap.add_argument("--cam-res", type=int, default=256, + help="256 = RLinf libero_10 env (lane evaluator + collector); 128 = demo hdf5") + ap.add_argument("--pool", default="rollouts", choices=["rollouts", "demos", "demos_replay"], + help="demos: re-render the 500 demo episodes from hdf5 `states` into a " + "new demo cache tree (/_demo/demo_k.npz)") + ap.add_argument("--validate-rollouts", type=int, default=0, + help="re-render N rollout episodes (4 frames each) and report L2 to the " + "CACHED rollout latent. ~4 at --cam-res 256 means our evaluator at 256 " + "reproduces the collector, and the 43k latents are on-manifold as-is.") + ap.add_argument("--validate-demos", type=int, default=0, + help="re-render N demo episodes' hdf5 states and report L2 to the " + "demo cache (z-scored, demo stats). Run BEFORE trusting output.") + ap.add_argument("--demo-cache", default="/data/pulkitag/users/rli14/libero10_demo_ogpo_cache_cam128") + ap.add_argument("--stats", default="/data/pulkitag/users/rli14/rsm_libero_cache/full_demo_cam256/feat_stats_demos.npz") + args = ap.parse_args() + + dev = "cuda" if torch.cuda.is_available() else "cpu" + tower = ogpo.build_paligemma(dev) + R = Renderer(args.cam_res) + print(f"[rr] cam_res={args.cam_res} pool={args.pool}", flush=True) + + if args.validate_demos: + import h5py, glob + st = np.load(args.stats); mu, sd = st["mu"][:4096], st["sd"][:4096] + dists = [] + h5s = sorted(glob.glob(f"{DEMO_H5}/*.hdf5")) + for tid, h5 in enumerate(h5s[:args.validate_demos]): + tname = Path(h5).stem[:-5] # strip _demo + tids = [i for i in range(10) if R.bench.get_task(i).name == tname] + if not tids: print(f"[rr] validate: no task for {tname}"); continue + tid = tids[0] + with h5py.File(h5, "r") as H: + states = np.asarray(H["data"]["demo_0"]["states"][:]) + rows = np.linspace(0, len(states) - 1, 4).astype(int) + A, W, _ = R.frames(tid, states[rows]) + _, ids = R.env(tid) + z = encode(tower, ids, A, W, dev, args.batch).astype(np.float32) + zc = np.load(f"{args.demo_cache}/{tname}_demo/demo_0.npz")["z"][rows].astype(np.float32) + print(f"[rr] validate demo task {tid}: comparing against {args.demo_cache}", flush=True) + dd = np.linalg.norm((z - zc) / sd, axis=1) + dists += dd.tolist() + print(f"[rr] validate demo task {tid} ({tname[:30]}): L2 to demo cache " + f"{np.round(dd, 2).tolist()}", flush=True) + print(f"[rr] VALIDATE demos: mean {np.mean(dists):.2f} max {np.max(dists):.2f} " + f"(demo cache re-encoded from its own hdf5 images: 3.7-4.3; " + f"anything >10 means this path is NOT the evaluator's)", flush=True) + + import pyarrow.parquet as pq + if args.validate_rollouts: + st = np.load(args.stats); sd = st["sd"][:4096] + m = np.load(args.only_cache, allow_pickle=True) if args.only_cache else None + cand = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] if m is not None \ + else sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) + dists = [] + for sp in cand[:args.validate_rollouts]: + g = PAT.search(sp); t, b, i, idx = g.groups() + pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + z0 = np.load(sp, allow_pickle=True); T = int(z0["z"].shape[0]) + tb = pq.read_table(pp, columns=["sim_state"]) + rows = np.linspace(0, min(T, tb.num_rows) - 1, 4).astype(int) + states = np.stack([np.asarray(tb["sim_state"][int(r)].as_py(), np.float64) for r in rows]) + tid = int(t) # from the FILENAME: the npz task_index field is wrong in the raw corpus (#234) + A, W, P = R.frames(tid, states); _, ids = R.env(tid) + z = encode(tower, ids, A, W, dev, args.batch).astype(np.float32) + dd = np.linalg.norm((z - z0["z"][rows].astype(np.float32)) / sd, axis=1) + dists += dd.tolist() + # Is the LOGGED image the same scene as the LOGGED sim_state? Compare the + # re-rendered proprio to the logged proprio (consistency of sim_state with + # state/actions), and save frame-0 side by side for the eye. + dp = float(np.abs(P - z0["proprio"][rows]).mean()) + print(f"[rr] validate rollout t{t} {Path(sp).name}: L2 to cached " + f"{np.round(dd, 2).tolist()} |rerendered proprio - logged| = {dp:.4f}", flush=True) + try: + from PIL import Image + from recheck_encoding import decode + tbi = pq.read_table(pp, columns=["image"]) + logged = Image.fromarray(decode(tbi["image"][int(rows[0])])).resize((224, 224)) + pair = Image.new("RGB", (448, 224)); pair.paste(logged, (0, 0)); pair.paste(Image.fromarray(A[0]), (224, 0)) + od = Path(args.out) / "validate_pairs"; od.mkdir(parents=True, exist_ok=True) + pair.save(od / f"{Path(sp).stem}_L2_{dd[0]:.0f}.png") + except Exception as e: + print(f"[rr] (pair save failed: {e})", flush=True) + print(f"[rr] VALIDATE rollouts @{args.cam_res}: mean {np.mean(dists):.2f} " + f"max {np.max(dists):.2f} (cache re-encoded from its own 256 pixels: 4.0-4.3)", + flush=True) + + if args.pool == "demos_replay": + # REPLAY the demonstration's logged actions live in the evaluator env from its + # logged initial state, recording what the env actually renders. Re-rendering + # from per-frame sim_state cannot reproduce a live render on the kitchen/study + # scenes (two fresh renders of the same state differ by 10-37 z-scored units; + # living rooms 3-4), so the only demo frames that are guaranteed to be in the + # evaluator's space are ones the evaluator itself produced along a trajectory. + # A demo whose replay does not end in success is inadmissible (same rule as + # rollouts) and is written with success=False so pack/BC can drop it. + import h5py, glob + n_done = n_ok = 0 + for h5 in sorted(glob.glob(f"{DEMO_H5}/*.hdf5")): + tname = Path(h5).stem[:-5] + tids = [i for i in range(10) if R.bench.get_task(i).name == tname] + if not tids: print(f"[rr] no task for {tname}"); continue + tid = tids[0]; env, ids = R.env(tid) + src_npz = sorted(glob.glob(f"{args.demo_cache}/{tname}_demo/demo_*.npz")) + with h5py.File(h5, "r") as H: + for sp in src_npz: + k = Path(sp).stem; op = Path(args.out) / f"{tname}_demo" / f"{k}.npz" + if op.exists(): continue + z0 = np.load(sp, allow_pickle=True) + acts = np.asarray(H["data"][k]["actions"][:], np.float32) + st0 = np.asarray(H["data"][k]["states"][0], np.float64) + env.reset(); env.env.sim.set_state_from_flattened(st0); env.env.sim.forward() + obs, _, _, _ = env.step(np.zeros(7)) + A, W, P = [], [], []; done = False + for a in acts: + A.append(to224(obs["agentview_image"][::-1, ::-1])) + W.append(to224(obs["robot0_eye_in_hand_image"][::-1, ::-1])) + P.append(np.concatenate([obs["robot0_eef_pos"], _eef_ori(obs), + obs["robot0_gripper_qpos"]]).astype(np.float32)) + obs, _, done, _ = env.step(a) + if done: break + T = len(A) + z = encode(tower, ids, np.stack(A), np.stack(W), dev, args.batch) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=np.stack(P), actions=acts[:T], prompt=z0["prompt"], + success=bool(done), replayed=True) + os.replace(tmp, op); n_done += 1; n_ok += int(bool(done)) + print(f"[rr] demos_replay task {tid}: {len(src_npz)} episodes, replay success so far " + f"{n_ok}/{n_done}", flush=True) + print(f"[rr] DONE demos_replay: {n_done} episodes, {n_ok} reproduce success " + f"({n_ok / max(n_done, 1):.3f}) at cam_res={args.cam_res}", flush=True) + return + + if args.pool == "demos": + import h5py, glob + n_done = 0 + for h5 in sorted(glob.glob(f"{DEMO_H5}/*.hdf5")): + tname = Path(h5).stem[:-5] + tids = [i for i in range(10) if R.bench.get_task(i).name == tname] + if not tids: print(f"[rr] no task for {tname}"); continue + tid = tids[0]; _, ids = R.env(tid) + src_npz = sorted(glob.glob(f"{args.demo_cache}/{tname}_demo/demo_*.npz")) + with h5py.File(h5, "r") as H: + for sp in src_npz: + k = Path(sp).stem; op = Path(args.out) / f"{tname}_demo" / f"{k}.npz" + if op.exists(): continue + z0 = np.load(sp, allow_pickle=True) + states = np.asarray(H["data"][k]["states"][:]) + T = min(len(states), int(z0["z"].shape[0])) + A, W, P = R.frames(tid, states[:T]) + z = encode(tower, ids, A, W, dev, args.batch) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=P, actions=z0["actions"][:T], prompt=z0["prompt"]) + os.replace(tmp, op); n_done += 1 + print(f"[rr] demos task {tid}: {len(src_npz)} episodes -> {args.out}/{tname}_demo " + f"(total written {n_done})", flush=True) + print(f"[rr] DONE demos: {n_done} episodes at cam_res={args.cam_res}", flush=True) + return + + if args.only_cache: + m = np.load(args.only_cache, allow_pickle=True) + srcs = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] + else: + srcs = sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) + srcs = srcs[args.shard::args.num_shards] + if args.limit: srcs = srcs[:args.limit] + print(f"[rr] shard {args.shard}/{args.num_shards}: {len(srcs)} episodes -> {args.out}", flush=True) + + t0 = time.time(); n_done = n_skip = 0 + for k, sp in enumerate(srcs): + rel = Path(sp).relative_to(args.src); op = Path(args.out) / rel + if op.exists(): n_skip += 1; continue + g = PAT.search(sp); t, b, i, idx = g.groups() + pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + if not os.path.exists(pp): print(f"[rr] MISSING parquet {rel}", flush=True); continue + z0 = np.load(sp, allow_pickle=True); T = int(z0["z"].shape[0]) + tb = pq.read_table(pp, columns=["sim_state"]) + T = min(T, tb.num_rows) + states = np.stack([np.asarray(tb["sim_state"][j].as_py(), np.float64) for j in range(T)]) + tid = int(t) # from the FILENAME: the npz task_index field is wrong in the raw corpus (#234) + A, W, P = R.frames(tid, states) + _, ids = R.env(tid) + z = encode(tower, ids, A, W, dev, args.batch) + # proprio: the re-rendered observation, which is what the evaluator would feed; + # agrees with the logged `state` to float precision (checked: mean |d| = 0.0) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=P, actions=z0["actions"][:T], success=z0["success"], + prompt=z0["prompt"], task_index=z0["task_index"]) + os.replace(tmp, op); n_done += 1 + if n_done % 25 == 0: + el = time.time() - t0 + print(f"[rr] {k+1}/{len(srcs)} done={n_done} skip={n_skip} {el/n_done:.1f}s/ep " + f"eta {(len(srcs)-k-1)*el/n_done/60:.0f} min", flush=True) + print(f"[rr] DONE shard {args.shard}: {n_done} written, {n_skip} existed", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/results/awr_is.json b/frozen/rsm_libero_rsmpi/results/awr_is.json new file mode 100644 index 0000000000000000000000000000000000000000..e0e2edacbd8d7e92f9f78c0a8400a977dd1ecb25 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/awr_is.json @@ -0,0 +1,108 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/awr_is", + "rounds": 2, + "batch": 256, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "awr_beta": 3.0, + "w_max": 20.0, + "awr_steps": 2000, + "bc_steps": 6000, + "ratio_steps": 3000, + "wend_steps": 3000, + "use_is": true, + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "ratio_smooth": 0.0, + "d_z": 256 + }, + "rounds": [ + { + "round": 1, + "awr": [ + { + "step": 500, + "loss": 0.16257646679878235, + "mean_abs_adv": 1.6013294458389282, + "adv_std": 4.7013840675354, + "w_max_batch": 9.430573463439941 + }, + { + "step": 1000, + "loss": 0.1544513702392578, + "mean_abs_adv": 1.835625171661377, + "adv_std": 5.795838832855225, + "w_max_batch": 6.571922302246094 + }, + { + "step": 1500, + "loss": 0.15181061625480652, + "mean_abs_adv": 2.207453727722168, + "adv_std": 6.558887004852295, + "w_max_batch": 11.571876525878906 + }, + { + "step": 2000, + "loss": 0.15949973464012146, + "mean_abs_adv": 1.663811445236206, + "adv_std": 4.831233024597168, + "w_max_batch": 10.90399169921875 + } + ], + "score": { + "bc_nll_success": 0.17084458470344543, + "bc_nll_failure": 0.17130279541015625, + "act_gap": 0.00045821070671081543 + } + }, + { + "round": 2, + "awr": [ + { + "step": 500, + "loss": 0.15983301401138306, + "mean_abs_adv": 1.0695834159851074, + "adv_std": 3.722569704055786, + "w_max_batch": 9.685918807983398 + }, + { + "step": 1000, + "loss": 0.15429604053497314, + "mean_abs_adv": 0.7141176462173462, + "adv_std": 2.485543966293335, + "w_max_batch": 11.612875938415527 + }, + { + "step": 1500, + "loss": 0.20286273956298828, + "mean_abs_adv": 1.0271759033203125, + "adv_std": 3.73201847076416, + "w_max_batch": 11.328639030456543 + }, + { + "step": 2000, + "loss": 0.13324297964572906, + "mean_abs_adv": 0.9385720491409302, + "adv_std": 3.4402856826782227, + "w_max_batch": 11.071598052978516 + } + ], + "score": { + "bc_nll_success": 0.17699238657951355, + "bc_nll_failure": 0.1672143042087555, + "act_gap": -0.009778082370758057 + } + } + ], + "pi_0": { + "bc_nll_success": 0.17064538598060608, + "bc_nll_failure": 0.1876475065946579, + "act_gap": 0.01700212061405182 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/awr_nois.json b/frozen/rsm_libero_rsmpi/results/awr_nois.json new file mode 100644 index 0000000000000000000000000000000000000000..be7c798a4a449d5411a50204727d4988c3d4c535 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/awr_nois.json @@ -0,0 +1,109 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/awr_nois", + "rounds": 2, + "batch": 256, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "awr_beta": 3.0, + "w_max": 20.0, + "awr_steps": 2000, + "bc_steps": 6000, + "ratio_steps": 3000, + "wend_steps": 3000, + "use_is": false, + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "awr_pool": "all", + "ratio_smooth": 0.0, + "d_z": 256 + }, + "rounds": [ + { + "round": 1, + "awr": [ + { + "step": 500, + "loss": 0.195926696062088, + "mean_abs_adv": 1.5207128524780273, + "adv_std": 3.9703404903411865, + "w_max_batch": 9.167509078979492 + }, + { + "step": 1000, + "loss": 0.1670464277267456, + "mean_abs_adv": 1.6043593883514404, + "adv_std": 3.9212582111358643, + "w_max_batch": 10.829105377197266 + }, + { + "step": 1500, + "loss": 0.15901966392993927, + "mean_abs_adv": 1.8362610340118408, + "adv_std": 5.85999870300293, + "w_max_batch": 10.425881385803223 + }, + { + "step": 2000, + "loss": 0.1412782222032547, + "mean_abs_adv": 1.9440784454345703, + "adv_std": 6.391367435455322, + "w_max_batch": 8.848503112792969 + } + ], + "score": { + "bc_nll_success": 0.17096398770809174, + "bc_nll_failure": 0.17207448184490204, + "act_gap": 0.0011104941368103027 + } + }, + { + "round": 2, + "awr": [ + { + "step": 500, + "loss": 0.1808767318725586, + "mean_abs_adv": 1.7913116216659546, + "adv_std": 5.498270034790039, + "w_max_batch": 8.57076644897461 + }, + { + "step": 1000, + "loss": 0.18697738647460938, + "mean_abs_adv": 1.5218538045883179, + "adv_std": 3.9496538639068604, + "w_max_batch": 6.969772815704346 + }, + { + "step": 1500, + "loss": 0.13867154717445374, + "mean_abs_adv": 2.0528721809387207, + "adv_std": 5.918031692504883, + "w_max_batch": 8.451258659362793 + }, + { + "step": 2000, + "loss": 0.19296662509441376, + "mean_abs_adv": 2.0750231742858887, + "adv_std": 6.377630710601807, + "w_max_batch": 6.74656867980957 + } + ], + "score": { + "bc_nll_success": 0.17648011445999146, + "bc_nll_failure": 0.16832603514194489, + "act_gap": -0.00815407931804657 + } + } + ], + "pi_0": { + "bc_nll_success": 0.17538213729858398, + "bc_nll_failure": 0.18425589799880981, + "act_gap": 0.00887376070022583 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/awr_pool_succ.json b/frozen/rsm_libero_rsmpi/results/awr_pool_succ.json new file mode 100644 index 0000000000000000000000000000000000000000..d3928448f0904cbde94b699feb62d947004a4652 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/awr_pool_succ.json @@ -0,0 +1,95 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/awr_pool_succ", + "rounds": 2, + "batch": 256, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "awr_beta": 3.0, + "w_max": 20.0, + "awr_steps": 1500, + "bc_steps": 3000, + "ratio_steps": 1500, + "wend_steps": 1500, + "use_is": false, + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "awr_pool": "succ", + "ratio_smooth": 0.0, + "d_z": 256 + }, + "rounds": [ + { + "round": 1, + "awr": [ + { + "step": 500, + "loss": 0.203533336520195, + "mean_abs_adv": 3.2522952556610107, + "adv_std": 7.032632350921631, + "w_max_batch": 5.746964454650879 + }, + { + "step": 1000, + "loss": 0.1729510873556137, + "mean_abs_adv": 2.6058743000030518, + "adv_std": 5.858712673187256, + "w_max_batch": 11.027697563171387 + }, + { + "step": 1500, + "loss": 0.241312637925148, + "mean_abs_adv": 1.988947868347168, + "adv_std": 3.9411566257476807, + "w_max_batch": 10.441418647766113 + } + ], + "score": { + "bc_nll_success": 0.19998064637184143, + "bc_nll_failure": 0.21658773720264435, + "act_gap": 0.016607090830802917 + } + }, + { + "round": 2, + "awr": [ + { + "step": 500, + "loss": 0.14199835062026978, + "mean_abs_adv": 3.5519473552703857, + "adv_std": 8.122130393981934, + "w_max_batch": 6.081887245178223 + }, + { + "step": 1000, + "loss": 0.16939425468444824, + "mean_abs_adv": 2.661106824874878, + "adv_std": 5.243246555328369, + "w_max_batch": 5.711920738220215 + }, + { + "step": 1500, + "loss": 0.12747256457805634, + "mean_abs_adv": 2.00933575630188, + "adv_std": 4.834885120391846, + "w_max_batch": 7.9043755531311035 + } + ], + "score": { + "bc_nll_success": 0.20760184526443481, + "bc_nll_failure": 0.21295753121376038, + "act_gap": 0.0053556859493255615 + } + } + ], + "pi_0": { + "bc_nll_success": 0.18510574102401733, + "bc_nll_failure": 0.2062300741672516, + "act_gap": 0.021124333143234253 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/critic_actcon01_history.json b/frozen/rsm_libero_rsmpi/results/critic_actcon01_history.json new file mode 100644 index 0000000000000000000000000000000000000000..34e202e884f3e65b1903716ae2474f1b57a39e3e --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/critic_actcon01_history.json @@ -0,0 +1,786 @@ +[ + { + "step": 2000, + "reward_auc": 0.9876610505450941, + "cfm_val": 0.25738441944122314, + "per_task": { + "0": { + "n": 100, + "action_gap": 0.004566409159451723, + "success_auc": 0.5842985842985843, + "succ_rate": 0.3700000047683716 + }, + "1": { + "n": 137, + "action_gap": -0.005876636598259211, + "success_auc": 0.4227956989247312, + "succ_rate": 0.45255473256111145 + }, + "2": { + "n": 156, + "action_gap": 0.01211931649595499, + "success_auc": 0.5297852474323063, + "succ_rate": 0.32692307233810425 + }, + "3": { + "n": 107, + "action_gap": 0.002370755886659026, + "success_auc": 0.45433996383363473, + "succ_rate": 0.2616822421550751 + }, + "4": { + "n": 76, + "action_gap": -0.013497255742549896, + "success_auc": 0.5821000704721635, + "succ_rate": 0.43421053886413574 + }, + "5": { + "n": 26, + "action_gap": -0.010058850049972534, + "success_auc": 0.6470588235294118, + "succ_rate": 0.6538461446762085 + }, + "6": { + "n": 93, + "action_gap": 0.010616077110171318, + "success_auc": 0.40674603174603174, + "succ_rate": 0.22580644488334656 + }, + "7": { + "n": 129, + "action_gap": 0.0065583945252001286, + "success_auc": 0.6056045666839647, + "succ_rate": 0.3643410801887512 + }, + "8": { + "n": 97, + "action_gap": -0.022468166425824165, + "success_auc": 0.5272078501338091, + "succ_rate": 0.39175257086753845 + }, + "9": { + "n": 103, + "action_gap": 0.006738460157066584, + "success_auc": 0.5214676034348166, + "succ_rate": 0.5922330021858215 + } + }, + "by_horizon": { + "0-50": { + "n": 115, + "action_gap": 0.037848301231861115, + "action_winrate": 0.6521739130434783, + "q_mean": 0.2682979106903076 + }, + "50-100": { + "n": 130, + "action_gap": -0.006974631920456886, + "action_winrate": 0.47692307692307695, + "q_mean": 0.055154867470264435 + }, + "100-200": { + "n": 245, + "action_gap": -0.01264046411961317, + "action_winrate": 0.4448979591836735, + "q_mean": 0.03335871174931526 + }, + "200+": { + "n": 534, + "action_gap": 0.0009504547924734652, + "action_winrate": 0.46441947565543074, + "q_mean": 0.0198063962161541 + } + }, + "latent_std_min": 0.18378838896751404, + "q_action_gap": 0.0008364089298993349, + "q_action_winrate": 0.482421875, + "q_success_auc": 0.5158398905234348, + "q_mean": 0.055443257093429565 + }, + { + "step": 4000, + "reward_auc": 0.9876276512175962, + "cfm_val": 0.17982925474643707, + "per_task": { + "0": { + "n": 104, + "action_gap": -0.018495649099349976, + "success_auc": 0.6214526214526215, + "succ_rate": 0.25961539149284363 + }, + "1": { + "n": 109, + "action_gap": -0.013799305073916912, + "success_auc": 0.4601889338731444, + "succ_rate": 0.47706422209739685 + }, + "2": { + "n": 134, + "action_gap": 0.015660826116800308, + "success_auc": 0.49041656018400204, + "succ_rate": 0.3208955228328705 + }, + "3": { + "n": 110, + "action_gap": 0.007917151786386967, + "success_auc": 0.4323962516733601, + "succ_rate": 0.2454545497894287 + }, + "4": { + "n": 104, + "action_gap": 0.007151569705456495, + "success_auc": 0.4701797385620915, + "succ_rate": 0.3461538553237915 + }, + "5": { + "n": 24, + "action_gap": -0.008169957436621189, + "success_auc": 0.75, + "succ_rate": 0.3333333432674408 + }, + "6": { + "n": 66, + "action_gap": 0.015843722969293594, + "success_auc": 0.7058823529411765, + "succ_rate": 0.25757575035095215 + }, + "7": { + "n": 147, + "action_gap": -0.005361799616366625, + "success_auc": 0.6405058209554396, + "succ_rate": 0.36054420471191406 + }, + "8": { + "n": 142, + "action_gap": -0.007460034918040037, + "success_auc": 0.4775747508305648, + "succ_rate": 0.39436620473861694 + }, + "9": { + "n": 84, + "action_gap": 0.020410602912306786, + "success_auc": 0.48788265306122447, + "succ_rate": 0.6666666865348816 + } + }, + "by_horizon": { + "0-50": { + "n": 129, + "action_gap": 0.040712807327508926, + "action_winrate": 0.5736434108527132, + "q_mean": 0.22582679986953735 + }, + "50-100": { + "n": 115, + "action_gap": -0.01250066515058279, + "action_winrate": 0.5130434782608696, + "q_mean": 0.031353823840618134 + }, + "100-200": { + "n": 246, + "action_gap": -0.014171958900988102, + "action_winrate": 0.516260162601626, + "q_mean": 0.013526356779038906 + }, + "200+": { + "n": 534, + "action_gap": 0.0012622518697753549, + "action_winrate": 0.5187265917602997, + "q_mean": 0.021329164505004883 + } + }, + "latent_std_min": 0.10585425049066544, + "q_action_gap": 0.000978628871962428, + "q_action_winrate": 0.5244140625, + "q_success_auc": 0.5189727786337955, + "q_mean": 0.0463423877954483 + }, + { + "step": 6000, + "reward_auc": 0.987619517466582, + "cfm_val": 0.1564761996269226, + "per_task": { + "0": { + "n": 108, + "action_gap": -0.0029598644468933344, + "success_auc": 0.6661812886785584, + "succ_rate": 0.37962964177131653 + }, + "1": { + "n": 111, + "action_gap": -0.012450174428522587, + "success_auc": 0.4107023411371237, + "succ_rate": 0.4144144058227539 + }, + "2": { + "n": 131, + "action_gap": 0.0009704058174975216, + "success_auc": 0.5333333333333333, + "succ_rate": 0.4580152630805969 + }, + "3": { + "n": 118, + "action_gap": 0.0006856883992440999, + "success_auc": 0.3781239857189224, + "succ_rate": 0.3305084705352783 + }, + "4": { + "n": 89, + "action_gap": 0.01947815716266632, + "success_auc": 0.600111234705228, + "succ_rate": 0.3483146131038666 + }, + "5": { + "n": 22, + "action_gap": -0.004661570303142071, + "success_auc": 0.7166666666666667, + "succ_rate": 0.5454545617103577 + }, + "6": { + "n": 86, + "action_gap": -0.009215174242854118, + "success_auc": 0.6065934065934065, + "succ_rate": 0.24418604373931885 + }, + "7": { + "n": 153, + "action_gap": 0.0005523079307749867, + "success_auc": 0.7152777777777778, + "succ_rate": 0.37254902720451355 + }, + "8": { + "n": 110, + "action_gap": 0.011075697839260101, + "success_auc": 0.5532801110725443, + "succ_rate": 0.3909091055393219 + }, + "9": { + "n": 96, + "action_gap": 0.026935627683997154, + "success_auc": 0.4722858451672011, + "succ_rate": 0.6145833134651184 + } + }, + "by_horizon": { + "0-50": { + "n": 131, + "action_gap": 0.0486595593392849, + "action_winrate": 0.5954198473282443, + "q_mean": 0.22337323427200317 + }, + "50-100": { + "n": 138, + "action_gap": -0.0038172707427293062, + "action_winrate": 0.572463768115942, + "q_mean": 0.03140514716506004 + }, + "100-200": { + "n": 256, + "action_gap": -0.0018287473358213902, + "action_winrate": 0.5078125, + "q_mean": 0.017960501834750175 + }, + "200+": { + "n": 499, + "action_gap": -0.004300427623093128, + "action_winrate": 0.4348697394789579, + "q_mean": 0.02231152355670929 + } + }, + "latent_std_min": 0.1156306192278862, + "q_action_gap": 0.0031577597837895155, + "q_action_winrate": 0.4921875, + "q_success_auc": 0.5466356570656171, + "q_mean": 0.048171039670705795 + }, + { + "step": 8000, + "reward_auc": 0.9923620933521924, + "cfm_val": 0.1500718593597412, + "per_task": { + "0": { + "n": 88, + "action_gap": 0.001879670424386859, + "success_auc": 0.6567493112947659, + "succ_rate": 0.375 + }, + "1": { + "n": 112, + "action_gap": -0.013231679797172546, + "success_auc": 0.428890306122449, + "succ_rate": 0.5 + }, + "2": { + "n": 156, + "action_gap": 0.011789332143962383, + "success_auc": 0.6479665940450254, + "succ_rate": 0.3461538553237915 + }, + "3": { + "n": 110, + "action_gap": -7.351743261096999e-05, + "success_auc": 0.4026442307692308, + "succ_rate": 0.290909081697464 + }, + "4": { + "n": 114, + "action_gap": 0.02756674960255623, + "success_auc": 0.6703964194373402, + "succ_rate": 0.4035087823867798 + }, + "5": { + "n": 23, + "action_gap": -0.0038583874702453613, + "success_auc": 0.8384615384615385, + "succ_rate": 0.5652173757553101 + }, + "6": { + "n": 88, + "action_gap": 0.030580373480916023, + "success_auc": 0.6935483870967742, + "succ_rate": 0.2954545319080353 + }, + "7": { + "n": 129, + "action_gap": 0.003452255390584469, + "success_auc": 0.7311827956989247, + "succ_rate": 0.27906978130340576 + }, + "8": { + "n": 126, + "action_gap": -0.003117024665698409, + "success_auc": 0.3851744186046512, + "succ_rate": 0.3174603283405304 + }, + "9": { + "n": 78, + "action_gap": 0.00961407832801342, + "success_auc": 0.5909722222222222, + "succ_rate": 0.6153846383094788 + } + }, + "by_horizon": { + "0-50": { + "n": 129, + "action_gap": 0.050272565335035324, + "action_winrate": 0.5038759689922481, + "q_mean": 0.21413478255271912 + }, + "50-100": { + "n": 115, + "action_gap": 0.004295047372579575, + "action_winrate": 0.591304347826087, + "q_mean": 0.010329574346542358 + }, + "100-200": { + "n": 276, + "action_gap": -0.0049506304785609245, + "action_winrate": 0.5036231884057971, + "q_mean": 0.009217144921422005 + }, + "200+": { + "n": 504, + "action_gap": 0.0028754533268511295, + "action_winrate": 0.49404761904761907, + "q_mean": 0.013028163462877274 + } + }, + "latent_std_min": 0.11352813243865967, + "q_action_gap": 0.006896430626511574, + "q_action_winrate": 0.5087890625, + "q_success_auc": 0.585498046875, + "q_mean": 0.037032630294561386 + }, + { + "step": 10000, + "reward_auc": 0.9923778851315084, + "cfm_val": 0.12619173526763916, + "per_task": { + "0": { + "n": 98, + "action_gap": 0.008085733279585838, + "success_auc": 0.6601477618426771, + "succ_rate": 0.3979591727256775 + }, + "1": { + "n": 117, + "action_gap": -0.017585037276148796, + "success_auc": 0.45784198113207547, + "succ_rate": 0.45299145579338074 + }, + "2": { + "n": 145, + "action_gap": -0.006606878712773323, + "success_auc": 0.7018947368421052, + "succ_rate": 0.3448275923728943 + }, + "3": { + "n": 102, + "action_gap": -0.0062676831148564816, + "success_auc": 0.45077220077220076, + "succ_rate": 0.27450981736183167 + }, + "4": { + "n": 94, + "action_gap": 0.008275660686194897, + "success_auc": 0.6149193548387096, + "succ_rate": 0.3404255211353302 + }, + "5": { + "n": 23, + "action_gap": 0.0049131689593195915, + "success_auc": 0.9705882352941176, + "succ_rate": 0.260869562625885 + }, + "6": { + "n": 90, + "action_gap": 0.024443859234452248, + "success_auc": 0.6631016042780749, + "succ_rate": 0.24444444477558136 + }, + "7": { + "n": 158, + "action_gap": 0.016934383660554886, + "success_auc": 0.7546551724137931, + "succ_rate": 0.3670886158943176 + }, + "8": { + "n": 119, + "action_gap": 0.001397809013724327, + "success_auc": 0.4739952718676123, + "succ_rate": 0.3949579894542694 + }, + "9": { + "n": 78, + "action_gap": 0.022675467655062675, + "success_auc": 0.5071010860484545, + "succ_rate": 0.7307692170143127 + } + }, + "by_horizon": { + "0-50": { + "n": 123, + "action_gap": 0.05798455327749252, + "action_winrate": 0.5772357723577236, + "q_mean": 0.2775479257106781 + }, + "50-100": { + "n": 123, + "action_gap": 0.004857067484408617, + "action_winrate": 0.5121951219512195, + "q_mean": 0.03623020276427269 + }, + "100-200": { + "n": 281, + "action_gap": -0.0038929434958845377, + "action_winrate": 0.45907473309608543, + "q_mean": 0.0360763780772686 + }, + "200+": { + "n": 497, + "action_gap": -0.003614547196775675, + "action_winrate": 0.47283702213279677, + "q_mean": 0.026242343708872795 + } + }, + "latent_std_min": 0.12484024465084076, + "q_action_gap": 0.004725754261016846, + "q_action_winrate": 0.486328125, + "q_success_auc": 0.595913523637303, + "q_mean": 0.060326773673295975 + }, + { + "step": 12000, + "reward_auc": 0.9876347116189305, + "cfm_val": 0.1233709380030632, + "per_task": { + "0": { + "n": 103, + "action_gap": 0.005045799538493156, + "success_auc": 0.7376760563380281, + "succ_rate": 0.3106796145439148 + }, + "1": { + "n": 118, + "action_gap": -0.00090402876958251, + "success_auc": 0.6080069124423964, + "succ_rate": 0.47457626461982727 + }, + "2": { + "n": 129, + "action_gap": 0.004968222696334124, + "success_auc": 0.7342696629213483, + "succ_rate": 0.3100775182247162 + }, + "3": { + "n": 105, + "action_gap": 0.002376304008066654, + "success_auc": 0.6008163265306122, + "succ_rate": 0.3333333432674408 + }, + "4": { + "n": 97, + "action_gap": 0.0065465266816318035, + "success_auc": 0.756021409455843, + "succ_rate": 0.39175257086753845 + }, + "5": { + "n": 24, + "action_gap": 0.01102861762046814, + "success_auc": 0.9785714285714285, + "succ_rate": 0.5833333134651184 + }, + "6": { + "n": 86, + "action_gap": 0.0038813373539596796, + "success_auc": 0.4214963119072708, + "succ_rate": 0.151162788271904 + }, + "7": { + "n": 140, + "action_gap": -0.0022797761484980583, + "success_auc": 0.7220990391722099, + "succ_rate": 0.2928571403026581 + }, + "8": { + "n": 128, + "action_gap": 0.007921185344457626, + "success_auc": 0.5657476139978791, + "succ_rate": 0.359375 + }, + "9": { + "n": 94, + "action_gap": -0.0014507672749459743, + "success_auc": 0.4441391941391941, + "succ_rate": 0.5531914830207825 + } + }, + "by_horizon": { + "0-50": { + "n": 124, + "action_gap": 0.027390604838728905, + "action_winrate": 0.5887096774193549, + "q_mean": 0.19646181166172028 + }, + "50-100": { + "n": 126, + "action_gap": 0.008937668986618519, + "action_winrate": 0.5952380952380952, + "q_mean": 0.035325318574905396 + }, + "100-200": { + "n": 255, + "action_gap": -0.0027388862799853086, + "action_winrate": 0.4980392156862745, + "q_mean": 0.018841728568077087 + }, + "200+": { + "n": 519, + "action_gap": -0.0014043253613635898, + "action_winrate": 0.47398843930635837, + "q_mean": 0.00328398821875453 + } + }, + "latent_std_min": 0.13129401206970215, + "q_action_gap": 0.0030227736569941044, + "q_action_winrate": 0.5087890625, + "q_success_auc": 0.6288637560706539, + "q_mean": 0.034493446350097656 + }, + { + "step": 14000, + "reward_auc": 0.9906342913776016, + "cfm_val": 0.11462379992008209, + "per_task": { + "0": { + "n": 89, + "action_gap": 0.005121784750372171, + "success_auc": 0.665079365079365, + "succ_rate": 0.3932584226131439 + }, + "1": { + "n": 115, + "action_gap": -0.007077975198626518, + "success_auc": 0.5030637254901961, + "succ_rate": 0.4434782564640045 + }, + "2": { + "n": 167, + "action_gap": 0.012538731098175049, + "success_auc": 0.7364824717765894, + "succ_rate": 0.4071856141090393 + }, + "3": { + "n": 110, + "action_gap": 0.0010763962054625154, + "success_auc": 0.6112637362637363, + "succ_rate": 0.23636363446712494 + }, + "4": { + "n": 63, + "action_gap": 0.0034723386634141207, + "success_auc": 0.7493606138107417, + "succ_rate": 0.2698412835597992 + }, + "5": { + "n": 23, + "action_gap": -0.007009751163423061, + "success_auc": 0.9230769230769231, + "succ_rate": 0.5652173757553101 + }, + "6": { + "n": 88, + "action_gap": 0.00752568244934082, + "success_auc": 0.7718550106609808, + "succ_rate": 0.23863635957241058 + }, + "7": { + "n": 177, + "action_gap": -0.004055559169501066, + "success_auc": 0.7535563751317176, + "succ_rate": 0.4124293923377991 + }, + "8": { + "n": 107, + "action_gap": 0.010423188097774982, + "success_auc": 0.5270785659801678, + "succ_rate": 0.35514017939567566 + }, + "9": { + "n": 85, + "action_gap": 0.03035472333431244, + "success_auc": 0.5923645320197044, + "succ_rate": 0.658823549747467 + } + }, + "by_horizon": { + "0-50": { + "n": 118, + "action_gap": 0.029233518987894058, + "action_winrate": 0.6016949152542372, + "q_mean": 0.3040999472141266 + }, + "50-100": { + "n": 123, + "action_gap": 0.004453870002180338, + "action_winrate": 0.5284552845528455, + "q_mean": 0.050180476158857346 + }, + "100-200": { + "n": 242, + "action_gap": 0.0020689768716692924, + "action_winrate": 0.48760330578512395, + "q_mean": 0.015485279262065887 + }, + "200+": { + "n": 541, + "action_gap": 0.001947433571331203, + "action_winrate": 0.48613678373382624, + "q_mean": 0.013620138168334961 + } + }, + "latent_std_min": 0.12894012033939362, + "q_action_gap": 0.005421518348157406, + "q_action_winrate": 0.5048828125, + "q_success_auc": 0.6192664600960072, + "q_mean": 0.05192571133375168 + }, + { + "step": 16000, + "reward_auc": 0.9956026204792247, + "cfm_val": 0.13298256695270538, + "per_task": { + "0": { + "n": 81, + "action_gap": 0.012630690820515156, + "success_auc": 0.8055944055944056, + "succ_rate": 0.32098764181137085 + }, + "1": { + "n": 129, + "action_gap": -0.0008594573009759188, + "success_auc": 0.6262183235867447, + "succ_rate": 0.44186046719551086 + }, + "2": { + "n": 152, + "action_gap": 0.010547131299972534, + "success_auc": 0.8338224504768892, + "succ_rate": 0.3815789520740509 + }, + "3": { + "n": 109, + "action_gap": -0.00010792343528009951, + "success_auc": 0.6195238095238095, + "succ_rate": 0.2293577939271927 + }, + "4": { + "n": 105, + "action_gap": 0.02172073908150196, + "success_auc": 0.6946938775510204, + "succ_rate": 0.3333333432674408 + }, + "5": { + "n": 24, + "action_gap": -0.0010894726729020476, + "success_auc": 0.993006993006993, + "succ_rate": 0.5416666865348816 + }, + "6": { + "n": 77, + "action_gap": 0.0006615500897169113, + "success_auc": 0.5631578947368421, + "succ_rate": 0.25974026322364807 + }, + "7": { + "n": 132, + "action_gap": -0.002495224354788661, + "success_auc": 0.788235294117647, + "succ_rate": 0.35606059432029724 + }, + "8": { + "n": 123, + "action_gap": 0.004555290564894676, + "success_auc": 0.6388888888888888, + "succ_rate": 0.2926829159259796 + }, + "9": { + "n": 92, + "action_gap": 0.00992683507502079, + "success_auc": 0.5723958333333333, + "succ_rate": 0.6521739363670349 + } + }, + "by_horizon": { + "0-50": { + "n": 120, + "action_gap": 0.04743295535445213, + "action_winrate": 0.5416666666666666, + "q_mean": 0.16258755326271057 + }, + "50-100": { + "n": 123, + "action_gap": -0.004087105859071016, + "action_winrate": 0.5040650406504065, + "q_mean": 0.012095688842236996 + }, + "100-200": { + "n": 241, + "action_gap": 0.0004168970917817205, + "action_winrate": 0.43983402489626555, + "q_mean": 0.00493627181276679 + }, + "200+": { + "n": 540, + "action_gap": 0.0012288391590118408, + "action_winrate": 0.46296296296296297, + "q_mean": 0.005437801126390696 + } + }, + "latent_std_min": 0.11616120487451553, + "q_action_gap": 0.00581375602632761, + "q_action_winrate": 0.4716796875, + "q_success_auc": 0.6760932932653873, + "q_mean": 0.02453547902405262 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/critic_base_history.json b/frozen/rsm_libero_rsmpi/results/critic_base_history.json new file mode 100644 index 0000000000000000000000000000000000000000..a4b18afb4b012336c8203146d106e40120423540 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/critic_base_history.json @@ -0,0 +1,786 @@ +[ + { + "step": 2000, + "reward_auc": 0.9877931945820945, + "cfm_val": 0.2719613313674927, + "per_task": { + "0": { + "n": 100, + "action_gap": 0.006409567780792713, + "success_auc": 0.5019305019305019, + "succ_rate": 0.3700000047683716 + }, + "1": { + "n": 137, + "action_gap": -0.0006269386503845453, + "success_auc": 0.42838709677419357, + "succ_rate": 0.45255473256111145 + }, + "2": { + "n": 156, + "action_gap": -0.007360421121120453, + "success_auc": 0.48328664799253035, + "succ_rate": 0.32692307233810425 + }, + "3": { + "n": 107, + "action_gap": -0.0035040834918618202, + "success_auc": 0.4421338155515371, + "succ_rate": 0.2616822421550751 + }, + "4": { + "n": 76, + "action_gap": 0.00958211813122034, + "success_auc": 0.5010570824524313, + "succ_rate": 0.43421053886413574 + }, + "5": { + "n": 26, + "action_gap": 0.016778195276856422, + "success_auc": 0.7712418300653595, + "succ_rate": 0.6538461446762085 + }, + "6": { + "n": 93, + "action_gap": 0.0034999591298401356, + "success_auc": 0.4662698412698413, + "succ_rate": 0.22580644488334656 + }, + "7": { + "n": 129, + "action_gap": 0.002188619691878557, + "success_auc": 0.5111572392319668, + "succ_rate": 0.3643410801887512 + }, + "8": { + "n": 97, + "action_gap": 0.004824227187782526, + "success_auc": 0.49910793933987513, + "succ_rate": 0.39175257086753845 + }, + "9": { + "n": 103, + "action_gap": 0.0015593749703839421, + "success_auc": 0.49882903981264637, + "succ_rate": 0.5922330021858215 + } + }, + "by_horizon": { + "0-50": { + "n": 115, + "action_gap": 0.04457010701298714, + "action_winrate": 0.5391304347826087, + "q_mean": 0.258619099855423 + }, + "50-100": { + "n": 130, + "action_gap": 0.0029214469250291586, + "action_winrate": 0.5538461538461539, + "q_mean": 0.059412311762571335 + }, + "100-200": { + "n": 245, + "action_gap": -0.006007762625813484, + "action_winrate": 0.4489795918367347, + "q_mean": 0.03499697521328926 + }, + "200+": { + "n": 534, + "action_gap": -0.00487018097192049, + "action_winrate": 0.5056179775280899, + "q_mean": 0.016915302723646164 + } + }, + "latent_std_min": 0.15928788483142853, + "q_action_gap": 0.0013991909800097346, + "q_action_winrate": 0.501953125, + "q_success_auc": 0.49751061560443544, + "q_mean": 0.05378107726573944 + }, + { + "step": 4000, + "reward_auc": 0.9918061033043611, + "cfm_val": 0.17078743875026703, + "per_task": { + "0": { + "n": 90, + "action_gap": 0.006965033244341612, + "success_auc": 0.6233836206896551, + "succ_rate": 0.35555556416511536 + }, + "1": { + "n": 104, + "action_gap": -0.004016174003481865, + "success_auc": 0.4863636363636364, + "succ_rate": 0.42307692766189575 + }, + "2": { + "n": 138, + "action_gap": -0.007320027332752943, + "success_auc": 0.4710648148148148, + "succ_rate": 0.3478260934352875 + }, + "3": { + "n": 124, + "action_gap": 0.016234273090958595, + "success_auc": 0.4537373737373737, + "succ_rate": 0.2016129046678543 + }, + "4": { + "n": 101, + "action_gap": 0.004218746442347765, + "success_auc": 0.542572463768116, + "succ_rate": 0.31683167815208435 + }, + "5": { + "n": 18, + "action_gap": 0.028326719999313354, + "success_auc": 0.7901234567901234, + "succ_rate": 0.5 + }, + "6": { + "n": 80, + "action_gap": 0.028160223737359047, + "success_auc": 0.6538201487491548, + "succ_rate": 0.36250001192092896 + }, + "7": { + "n": 159, + "action_gap": 0.0043665445409715176, + "success_auc": 0.609965034965035, + "succ_rate": 0.3459119498729706 + }, + "8": { + "n": 129, + "action_gap": 0.005183717235922813, + "success_auc": 0.6113013698630136, + "succ_rate": 0.43410852551460266 + }, + "9": { + "n": 81, + "action_gap": 0.028182461857795715, + "success_auc": 0.4458064516129032, + "succ_rate": 0.6172839403152466 + } + }, + "by_horizon": { + "0-50": { + "n": 134, + "action_gap": 0.06312573701143265, + "action_winrate": 0.5970149253731343, + "q_mean": 0.28379589319229126 + }, + "50-100": { + "n": 121, + "action_gap": 0.012869387865066528, + "action_winrate": 0.5537190082644629, + "q_mean": 0.03760857135057449 + }, + "100-200": { + "n": 249, + "action_gap": -0.0013214896898716688, + "action_winrate": 0.5461847389558233, + "q_mean": 0.022991467267274857 + }, + "200+": { + "n": 520, + "action_gap": -0.003154587931931019, + "action_winrate": 0.43653846153846154, + "q_mean": 0.016621064394712448 + } + }, + "latent_std_min": 0.1195826530456543, + "q_action_gap": 0.007858015596866608, + "q_action_winrate": 0.498046875, + "q_success_auc": 0.5521330500163452, + "q_mean": 0.05561242252588272 + }, + { + "step": 6000, + "reward_auc": 0.9877277214394687, + "cfm_val": 0.14670471847057343, + "per_task": { + "0": { + "n": 114, + "action_gap": -0.0017151666106656194, + "success_auc": 0.6476650563607085, + "succ_rate": 0.3947368562221527 + }, + "1": { + "n": 117, + "action_gap": -0.00499859219416976, + "success_auc": 0.36208955223880596, + "succ_rate": 0.4273504316806793 + }, + "2": { + "n": 151, + "action_gap": -0.009663020260632038, + "success_auc": 0.48579545454545453, + "succ_rate": 0.3642384111881256 + }, + "3": { + "n": 95, + "action_gap": 0.013272133655846119, + "success_auc": 0.3953846153846154, + "succ_rate": 0.31578946113586426 + }, + "4": { + "n": 92, + "action_gap": 0.008168470114469528, + "success_auc": 0.6130831643002028, + "succ_rate": 0.3695652186870575 + }, + "5": { + "n": 28, + "action_gap": 0.010491804219782352, + "success_auc": 0.5935828877005348, + "succ_rate": 0.3928571343421936 + }, + "6": { + "n": 79, + "action_gap": -0.0009604941587895155, + "success_auc": 0.6393034825870647, + "succ_rate": 0.15189872682094574 + }, + "7": { + "n": 143, + "action_gap": 0.002327292924746871, + "success_auc": 0.6429769392033543, + "succ_rate": 0.37062937021255493 + }, + "8": { + "n": 123, + "action_gap": 0.003327814396470785, + "success_auc": 0.48412698412698413, + "succ_rate": 0.3414634168148041 + }, + "9": { + "n": 82, + "action_gap": 0.004303997382521629, + "success_auc": 0.3740350877192982, + "succ_rate": 0.6951219439506531 + } + }, + "by_horizon": { + "0-50": { + "n": 120, + "action_gap": 0.017688516527414322, + "action_winrate": 0.5833333333333334, + "q_mean": 0.19690124690532684 + }, + "50-100": { + "n": 140, + "action_gap": -0.0035559427924454212, + "action_winrate": 0.5142857142857142, + "q_mean": 0.035192739218473434 + }, + "100-200": { + "n": 248, + "action_gap": -0.006306999828666449, + "action_winrate": 0.5, + "q_mean": 0.010996377095580101 + }, + "200+": { + "n": 516, + "action_gap": 0.0019867457449436188, + "action_winrate": 0.48643410852713176, + "q_mean": 0.012091262266039848 + } + }, + "latent_std_min": 0.12486922740936279, + "q_action_gap": 0.00106036604847759, + "q_action_winrate": 0.5048828125, + "q_success_auc": 0.5337773009736251, + "q_mean": 0.0366419181227684 + }, + { + "step": 8000, + "reward_auc": 0.9926145839060238, + "cfm_val": 0.13243581354618073, + "per_task": { + "0": { + "n": 103, + "action_gap": -0.007044427562505007, + "success_auc": 0.6183978873239436, + "succ_rate": 0.3106796145439148 + }, + "1": { + "n": 115, + "action_gap": 0.00042230208055116236, + "success_auc": 0.5823244552058111, + "succ_rate": 0.5130434632301331 + }, + "2": { + "n": 144, + "action_gap": 0.0024494652170687914, + "success_auc": 0.5689453125, + "succ_rate": 0.4444444477558136 + }, + "3": { + "n": 112, + "action_gap": 0.005480488296598196, + "success_auc": 0.4014336917562724, + "succ_rate": 0.2767857015132904 + }, + "4": { + "n": 102, + "action_gap": 0.0025110540445894003, + "success_auc": 0.5699013157894737, + "succ_rate": 0.37254902720451355 + }, + "5": { + "n": 26, + "action_gap": 0.00364819192327559, + "success_auc": 0.7810650887573964, + "succ_rate": 0.5 + }, + "6": { + "n": 79, + "action_gap": -0.0009238740894943476, + "success_auc": 0.6669085631349783, + "succ_rate": 0.3291139304637909 + }, + "7": { + "n": 127, + "action_gap": -0.00818592868745327, + "success_auc": 0.6187012987012988, + "succ_rate": 0.3937007784843445 + }, + "8": { + "n": 134, + "action_gap": 0.01101685967296362, + "success_auc": 0.4859437751004016, + "succ_rate": 0.3805970251560211 + }, + "9": { + "n": 82, + "action_gap": 0.03006887063384056, + "success_auc": 0.5240384615384616, + "succ_rate": 0.6829268336296082 + } + }, + "by_horizon": { + "0-50": { + "n": 117, + "action_gap": 0.06807809323072433, + "action_winrate": 0.6068376068376068, + "q_mean": 0.29577046632766724 + }, + "50-100": { + "n": 125, + "action_gap": 0.007352953311055899, + "action_winrate": 0.552, + "q_mean": 0.035094257444143295 + }, + "100-200": { + "n": 277, + "action_gap": -0.011254442855715752, + "action_winrate": 0.4729241877256318, + "q_mean": 0.031610190868377686 + }, + "200+": { + "n": 505, + "action_gap": -0.004548436962068081, + "action_winrate": 0.4316831683168317, + "q_mean": 0.014708572998642921 + } + }, + "latent_std_min": 0.13052812218666077, + "q_action_gap": 0.003388490993529558, + "q_action_winrate": 0.4775390625, + "q_success_auc": 0.5410753705455692, + "q_mean": 0.05388259142637253 + }, + { + "step": 10000, + "reward_auc": 0.9952735788801362, + "cfm_val": 0.12641239166259766, + "per_task": { + "0": { + "n": 93, + "action_gap": 0.00958632118999958, + "success_auc": 0.5436280137772675, + "succ_rate": 0.2795698940753937 + }, + "1": { + "n": 114, + "action_gap": 0.004666919354349375, + "success_auc": 0.5947611710323575, + "succ_rate": 0.5175438523292542 + }, + "2": { + "n": 149, + "action_gap": 0.008862324059009552, + "success_auc": 0.617196056955093, + "succ_rate": 0.4429530203342438 + }, + "3": { + "n": 115, + "action_gap": -8.788835839368403e-05, + "success_auc": 0.4393939393939394, + "succ_rate": 0.2869565188884735 + }, + "4": { + "n": 112, + "action_gap": -0.0038778905291110277, + "success_auc": 0.7638474295190714, + "succ_rate": 0.4017857015132904 + }, + "5": { + "n": 23, + "action_gap": 0.013691545464098454, + "success_auc": 0.8409090909090909, + "succ_rate": 0.52173912525177 + }, + "6": { + "n": 83, + "action_gap": 0.009849518537521362, + "success_auc": 0.6374807987711214, + "succ_rate": 0.2530120611190796 + }, + "7": { + "n": 134, + "action_gap": -0.0017945445142686367, + "success_auc": 0.7155835080363382, + "succ_rate": 0.3955223858356476 + }, + "8": { + "n": 140, + "action_gap": -9.543576743453741e-05, + "success_auc": 0.5804810360777058, + "succ_rate": 0.3285714387893677 + }, + "9": { + "n": 61, + "action_gap": -0.0006616313476115465, + "success_auc": 0.5769230769230769, + "succ_rate": 0.5737704634666443 + } + }, + "by_horizon": { + "0-50": { + "n": 110, + "action_gap": 0.04189131036400795, + "action_winrate": 0.6090909090909091, + "q_mean": 0.22503556311130524 + }, + "50-100": { + "n": 145, + "action_gap": 0.002932266565039754, + "action_winrate": 0.503448275862069, + "q_mean": 0.01357592549175024 + }, + "100-200": { + "n": 255, + "action_gap": -0.0037341732531785965, + "action_winrate": 0.4470588235294118, + "q_mean": 0.008922974579036236 + }, + "200+": { + "n": 514, + "action_gap": -0.0018349618185311556, + "action_winrate": 0.4669260700389105, + "q_mean": 0.007097852881997824 + } + }, + "latent_std_min": 0.11313363909721375, + "q_action_gap": 0.0030642952769994736, + "q_action_winrate": 0.482421875, + "q_success_auc": 0.5804743292800618, + "q_mean": 0.0318809375166893 + }, + { + "step": 12000, + "reward_auc": 0.9875996015936255, + "cfm_val": 0.14582675695419312, + "per_task": { + "0": { + "n": 106, + "action_gap": 0.019602810963988304, + "success_auc": 0.5134803921568627, + "succ_rate": 0.3207547068595886 + }, + "1": { + "n": 127, + "action_gap": 0.006570063065737486, + "success_auc": 0.5638350720317934, + "succ_rate": 0.4803149700164795 + }, + "2": { + "n": 150, + "action_gap": -0.005994896870106459, + "success_auc": 0.618923449431924, + "succ_rate": 0.3933333456516266 + }, + "3": { + "n": 114, + "action_gap": 0.0037662810645997524, + "success_auc": 0.44189016602809705, + "succ_rate": 0.2368421107530594 + }, + "4": { + "n": 89, + "action_gap": 0.016635524109005928, + "success_auc": 0.6725571725571725, + "succ_rate": 0.4157303273677826 + }, + "5": { + "n": 17, + "action_gap": 0.027434324845671654, + "success_auc": 1.0, + "succ_rate": 0.529411792755127 + }, + "6": { + "n": 80, + "action_gap": 0.008997109718620777, + "success_auc": 0.7337526205450734, + "succ_rate": 0.3375000059604645 + }, + "7": { + "n": 123, + "action_gap": -0.0023393582087010145, + "success_auc": 0.738204833141542, + "succ_rate": 0.35772356390953064 + }, + "8": { + "n": 135, + "action_gap": 0.012750799767673016, + "success_auc": 0.5908029878618114, + "succ_rate": 0.3777777850627899 + }, + "9": { + "n": 83, + "action_gap": 0.04165320843458176, + "success_auc": 0.6290322580645161, + "succ_rate": 0.6265060305595398 + } + }, + "by_horizon": { + "0-50": { + "n": 141, + "action_gap": 0.06903799623250961, + "action_winrate": 0.6453900709219859, + "q_mean": 0.1966162919998169 + }, + "50-100": { + "n": 137, + "action_gap": 0.013401753269135952, + "action_winrate": 0.5693430656934306, + "q_mean": 0.04996121674776077 + }, + "100-200": { + "n": 262, + "action_gap": -0.002184053650125861, + "action_winrate": 0.5229007633587787, + "q_mean": 0.00442706560716033 + }, + "200+": { + "n": 484, + "action_gap": -0.0020624196622520685, + "action_winrate": 0.47107438016528924, + "q_mean": 0.004376966040581465 + } + }, + "latent_std_min": 0.11370516568422318, + "q_action_gap": 0.009765589609742165, + "q_action_winrate": 0.521484375, + "q_success_auc": 0.598435692470269, + "q_mean": 0.03695891052484512 + }, + { + "step": 14000, + "reward_auc": 0.9930000897424393, + "cfm_val": 0.11024355888366699, + "per_task": { + "0": { + "n": 105, + "action_gap": 0.006106030195951462, + "success_auc": 0.647887323943662, + "succ_rate": 0.32380953431129456 + }, + "1": { + "n": 100, + "action_gap": 0.0031750958878546953, + "success_auc": 0.5752709755118426, + "succ_rate": 0.4699999988079071 + }, + "2": { + "n": 146, + "action_gap": 0.0011619975557550788, + "success_auc": 0.7397233586596532, + "succ_rate": 0.4041095972061157 + }, + "3": { + "n": 132, + "action_gap": -0.001316036214120686, + "success_auc": 0.5952871870397644, + "succ_rate": 0.2651515007019043 + }, + "4": { + "n": 85, + "action_gap": 0.03164169192314148, + "success_auc": 0.5798368298368298, + "succ_rate": 0.38823530077934265 + }, + "5": { + "n": 22, + "action_gap": 0.0435030423104763, + "success_auc": 1.0, + "succ_rate": 0.5454545617103577 + }, + "6": { + "n": 87, + "action_gap": 0.019851239398121834, + "success_auc": 0.6884920634920635, + "succ_rate": 0.27586206793785095 + }, + "7": { + "n": 129, + "action_gap": -0.0024974446278065443, + "success_auc": 0.7235294117647059, + "succ_rate": 0.26356589794158936 + }, + "8": { + "n": 137, + "action_gap": 0.0035060448572039604, + "success_auc": 0.5772413793103448, + "succ_rate": 0.36496350169181824 + }, + "9": { + "n": 81, + "action_gap": 0.03467779606580734, + "success_auc": 0.4585714285714286, + "succ_rate": 0.6913580298423767 + } + }, + "by_horizon": { + "0-50": { + "n": 128, + "action_gap": 0.05899292230606079, + "action_winrate": 0.609375, + "q_mean": 0.30233797430992126 + }, + "50-100": { + "n": 139, + "action_gap": 0.004043913912028074, + "action_winrate": 0.49640287769784175, + "q_mean": 0.045786742120981216 + }, + "100-200": { + "n": 248, + "action_gap": 0.0032756340224295855, + "action_winrate": 0.5, + "q_mean": 0.016110241413116455 + }, + "200+": { + "n": 509, + "action_gap": 0.0007264256710186601, + "action_winrate": 0.4911591355599214, + "q_mean": 0.014695562422275543 + } + }, + "latent_std_min": 0.1204683780670166, + "q_action_gap": 0.009077447466552258, + "q_action_winrate": 0.5087890625, + "q_success_auc": 0.6366617838541667, + "q_mean": 0.055213868618011475 + }, + { + "step": 16000, + "reward_auc": 0.9877941981390257, + "cfm_val": 0.13146889209747314, + "per_task": { + "0": { + "n": 96, + "action_gap": 0.004865909926593304, + "success_auc": 0.7935483870967742, + "succ_rate": 0.3229166567325592 + }, + "1": { + "n": 119, + "action_gap": 0.001266196253709495, + "success_auc": 0.5974431818181818, + "succ_rate": 0.462184876203537 + }, + "2": { + "n": 145, + "action_gap": 0.0035740588791668415, + "success_auc": 0.8214736842105264, + "succ_rate": 0.3448275923728943 + }, + "3": { + "n": 107, + "action_gap": -0.00022753907251171768, + "success_auc": 0.6809024979854955, + "succ_rate": 0.3177570104598999 + }, + "4": { + "n": 98, + "action_gap": 0.028498968109488487, + "success_auc": 0.662719298245614, + "succ_rate": 0.3877550959587097 + }, + "5": { + "n": 20, + "action_gap": -0.010041766799986362, + "success_auc": 0.9797979797979798, + "succ_rate": 0.44999998807907104 + }, + "6": { + "n": 84, + "action_gap": 0.003478787373751402, + "success_auc": 0.5842781557067271, + "succ_rate": 0.25 + }, + "7": { + "n": 141, + "action_gap": 0.0013932707952335477, + "success_auc": 0.7867276887871854, + "succ_rate": 0.326241135597229 + }, + "8": { + "n": 115, + "action_gap": -0.003131964011117816, + "success_auc": 0.45934959349593496, + "succ_rate": 0.2869565188884735 + }, + "9": { + "n": 99, + "action_gap": 0.009113285690546036, + "success_auc": 0.5525423728813559, + "succ_rate": 0.5959596037864685 + } + }, + "by_horizon": { + "0-50": { + "n": 134, + "action_gap": 0.029561201110482216, + "action_winrate": 0.5895522388059702, + "q_mean": 0.18105097115039825 + }, + "50-100": { + "n": 127, + "action_gap": 0.008339605294167995, + "action_winrate": 0.5433070866141733, + "q_mean": 0.015619616955518723 + }, + "100-200": { + "n": 257, + "action_gap": -0.0032016062177717686, + "action_winrate": 0.44357976653696496, + "q_mean": 0.004435449372977018 + }, + "200+": { + "n": 506, + "action_gap": 0.001061168615706265, + "action_winrate": 0.5158102766798419, + "q_mean": 0.010990219190716743 + } + }, + "latent_std_min": 0.11561814695596695, + "q_action_gap": 0.0046235048212111, + "q_action_winrate": 0.5107421875, + "q_success_auc": 0.6598699763593381, + "q_mean": 0.03217332437634468 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/ope_null_base.json b/frozen/rsm_libero_rsmpi/results/ope_null_base.json new file mode 100644 index 0000000000000000000000000000000000000000..f7cede01501b5cf3eec74d2a9d2e352e54c85667 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/ope_null_base.json @@ -0,0 +1,51 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/ope_null_base", + "batch": 512, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 16, + "bc_steps": 6000, + "ratio_steps": 4000, + "wend_steps": 4000, + "pi_mode": "all", + "seed": 0, + "in_ram": 0, + "d_z": 256 + }, + "calibration": { + "calib_scale": 5.237595756905884, + "E_mu[W_chunk]": 0.18588261306285858, + "E_mu[w_endpoint]": 1.0162439346313477, + "w_p05": 0.178162083029747, + "w_p50": 0.769451379776001, + "w_p95": 2.4898264408111572, + "ess_frac": 0.5588774085044861, + "corr_w_vs_W": 0.4341499684578188 + }, + "horizon": { + "restart_p": 0.505050505050505, + "mean_hops": 1.505050505050505, + "mean_hops_untruncated": 2.020408163265306, + "effective_frames": 75.25252525252519, + "gamma_effective": 0.9867114093959731, + "gamma_nominal": 0.99, + "truncation_mass": 0.25507601265177016 + }, + "value": { + "pi_mode": "all", + "rel_shift_IS_vs_noIS": 0.18422631919384003, + "gate_expectation": "null: weights ~1 and rel_shift should be SMALL", + "auc_success_IS": 0.6577155507688626, + "auc_success_noIS": 0.6631035720696464, + "q_mean_IS": 4.157533168792725, + "q_mean_noIS": 4.162613391876221, + "ess_particles": 0.6232997179031372, + "depth": 2, + "beta": 0.98, + "gamma": 0.99 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/ope_signal_base.json b/frozen/rsm_libero_rsmpi/results/ope_signal_base.json new file mode 100644 index 0000000000000000000000000000000000000000..f3ee9d545264b17c20a9aefa1444adb5615de8d6 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/ope_signal_base.json @@ -0,0 +1,51 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/ope_signal_base", + "batch": 512, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 16, + "bc_steps": 6000, + "ratio_steps": 4000, + "wend_steps": 4000, + "pi_mode": "succ", + "seed": 0, + "in_ram": 0, + "d_z": 256 + }, + "calibration": { + "calib_scale": 5.228771711827236, + "E_mu[W_chunk]": 0.1858443021774292, + "E_mu[w_endpoint]": 1.0155830383300781, + "w_p05": 0.18472248315811157, + "w_p50": 0.7708338499069214, + "w_p95": 2.5086076259613037, + "ess_frac": 0.5631883144378662, + "corr_w_vs_W": 0.4324678136650354 + }, + "horizon": { + "restart_p": 0.505050505050505, + "mean_hops": 1.505050505050505, + "mean_hops_untruncated": 2.020408163265306, + "effective_frames": 75.25252525252519, + "gamma_effective": 0.9867114093959731, + "gamma_nominal": 0.99, + "truncation_mass": 0.25507601265177016 + }, + "value": { + "pi_mode": "succ", + "rel_shift_IS_vs_noIS": 0.19249221682548523, + "gate_expectation": "signal: pi is better than mu, Q should move UP", + "auc_success_IS": 0.6645485550170526, + "auc_success_noIS": 0.6625660663355871, + "q_mean_IS": 4.31668758392334, + "q_mean_noIS": 4.41709566116333, + "ess_particles": 0.63212651014328, + "depth": 2, + "beta": 0.98, + "gamma": 0.99 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/ope_smoketest_smooth.json b/frozen/rsm_libero_rsmpi/results/ope_smoketest_smooth.json new file mode 100644 index 0000000000000000000000000000000000000000..4e510bf928ac191025f9036e3b34c895f94f950c --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/ope_smoketest_smooth.json @@ -0,0 +1,53 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/ope_smoketest_smooth", + "batch": 512, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "bc_steps": 3000, + "ratio_steps": 3000, + "wend_steps": 3000, + "pi_mode": "all", + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "ratio_smooth": 0.5, + "d_z": 256 + }, + "calibration": { + "calib_scale": 4.564842539855811, + "E_mu[W_chunk]": 0.22500823438167572, + "E_mu[w_endpoint]": 1.0092662572860718, + "w_p05": 0.18696357309818268, + "w_p50": 0.8847378492355347, + "w_p95": 2.304257869720459, + "ess_frac": 0.6249898076057434, + "corr_w_vs_W": 0.23125867938004438 + }, + "horizon": { + "restart_p": 0.505050505050505, + "mean_hops": 1.505050505050505, + "mean_hops_untruncated": 2.020408163265306, + "effective_frames": 75.25252525252519, + "gamma_effective": 0.9867114093959731, + "gamma_nominal": 0.99, + "truncation_mass": 0.25507601265177016 + }, + "value": { + "pi_mode": "all", + "rel_shift_IS_vs_noIS": 0.21909917891025543, + "gate_expectation": "null: weights ~1 and rel_shift should be SMALL", + "auc_success_IS": 0.6674714294261952, + "auc_success_noIS": 0.6499461497038234, + "q_mean_IS": 4.233530044555664, + "q_mean_noIS": 4.331247329711914, + "ess_particles": 0.6933380365371704, + "depth": 2, + "beta": 0.98, + "gamma": 0.99 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/ope_smooth_signal.json b/frozen/rsm_libero_rsmpi/results/ope_smooth_signal.json new file mode 100644 index 0000000000000000000000000000000000000000..260781c0e5808442cbeefa1e9ab747c54dbdd25a --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/ope_smooth_signal.json @@ -0,0 +1,53 @@ +{ + "config": { + "cache": "/data/pulkitag/users/rli14/rsm_libero_cache/dev4k", + "critic": "/data/pulkitag/users/rli14/rsm_libero_runs/dev_base/ckpt.pt", + "out": "/data/pulkitag/users/rli14/rsm_libero_runs/ope_smooth_signal", + "batch": 512, + "beta_q": 0.98, + "gamma": 0.99, + "depth": 2, + "particles": 8, + "bc_steps": 3000, + "ratio_steps": 3000, + "wend_steps": 3000, + "pi_mode": "succ", + "seed": 0, + "in_ram": 0, + "policy_family": "flow", + "ratio_smooth": 0.5, + "d_z": 256 + }, + "calibration": { + "calib_scale": 3.764181771045251, + "E_mu[W_chunk]": 0.2209673523902893, + "E_mu[w_endpoint]": 1.008519172668457, + "w_p05": 0.31671518087387085, + "w_p50": 0.9019677042961121, + "w_p95": 2.0570905208587646, + "ess_frac": 0.7216845154762268, + "corr_w_vs_W": 0.3029320624145348 + }, + "horizon": { + "restart_p": 0.505050505050505, + "mean_hops": 1.505050505050505, + "mean_hops_untruncated": 2.020408163265306, + "effective_frames": 75.25252525252519, + "gamma_effective": 0.9867114093959731, + "gamma_nominal": 0.99, + "truncation_mass": 0.25507601265177016 + }, + "value": { + "pi_mode": "succ", + "rel_shift_IS_vs_noIS": 0.2472643256187439, + "gate_expectation": "signal: pi is better than mu, Q should move UP", + "auc_success_IS": 0.6510411057260815, + "auc_success_noIS": 0.6556542810985461, + "q_mean_IS": 4.378605842590332, + "q_mean_noIS": 4.441417694091797, + "ess_particles": 0.9089834690093994, + "depth": 2, + "beta": 0.98, + "gamma": 0.99 + } +} \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/sweep_actcon.json b/frozen/rsm_libero_rsmpi/results/sweep_actcon.json new file mode 100644 index 0000000000000000000000000000000000000000..8b8b7277e2cc8b005a41d8026622464a0371d20f --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/sweep_actcon.json @@ -0,0 +1,230 @@ +[ + { + "beta": 0.96, + "depth": 1, + "eff_frames": 24.99999999999998, + "gamma_eff": 0.96, + "gap_pooled": -51.546424865722656, + "win_pooled": 0.46142578125, + "gap_pooled_crosstask": -125.83489990234375, + "win_pooled_crosstask": 0.5009765625, + "state_auc": 0.5813405354817708, + "gap_0-50": 80.0497817993164, + "win_0-50": 0.6206896551724138, + "gap_50-100": -43.533599853515625, + "win_50-100": 0.576271186440678, + "gap_100-200": -55.44401931762695, + "win_100-200": 0.46938775510204084, + "gap_200+": -83.900634765625, + "win_200+": 0.3930254476908577 + }, + { + "beta": 0.96, + "depth": 2, + "eff_frames": 48.74999999999993, + "gamma_eff": 0.9794871794871794, + "gap_pooled": 34.69417953491211, + "win_pooled": 0.65234375, + "gap_pooled_crosstask": -4.634228706359863, + "win_pooled_crosstask": 0.69287109375, + "state_auc": 0.5486317952473958, + "gap_0-50": 162.04180908203125, + "win_0-50": 0.7509578544061303, + "gap_50-100": 40.9615592956543, + "win_50-100": 0.6694915254237288, + "gap_100-200": 11.722060203552246, + "win_100-200": 0.6224489795918368, + "gap_200+": 12.582496643066406, + "win_200+": 0.6380772855796418 + }, + { + "beta": 0.96, + "depth": 3, + "eff_frames": 71.31249999999993, + "gamma_eff": 0.985977212971078, + "gap_pooled": -28.83934211730957, + "win_pooled": 0.5517578125, + "gap_pooled_crosstask": -71.80011749267578, + "win_pooled_crosstask": 0.5625, + "state_auc": 0.5696919759114584, + "gap_0-50": 97.36705017089844, + "win_0-50": 0.6781609195402298, + "gap_50-100": -16.318790435791016, + "win_50-100": 0.5550847457627118, + "gap_100-200": -48.95175552368164, + "win_100-200": 0.4959183673469388, + "gap_200+": -53.38188552856445, + "win_200+": 0.5457115928369463 + }, + { + "beta": 0.98, + "depth": 1, + "eff_frames": 49.99999999999996, + "gamma_eff": 0.98, + "gap_pooled": -61.46691131591797, + "win_pooled": 0.46142578125, + "gap_pooled_crosstask": -128.90740966796875, + "win_pooled_crosstask": 0.515625, + "state_auc": 0.600732421875, + "gap_0-50": 79.28109741210938, + "win_0-50": 0.6130268199233716, + "gap_50-100": -55.58386993408203, + "win_50-100": 0.4830508474576271, + "gap_100-200": -63.31771469116211, + "win_100-200": 0.463265306122449, + "gap_200+": -96.5439453125, + "win_200+": 0.4184731385485391 + }, + { + "beta": 0.98, + "depth": 2, + "eff_frames": 97.49999999999986, + "gamma_eff": 0.9897435897435898, + "gap_pooled": 30.28516387939453, + "win_pooled": 0.62646484375, + "gap_pooled_crosstask": -4.869052886962891, + "win_pooled_crosstask": 0.6865234375, + "state_auc": 0.5759409586588542, + "gap_0-50": 156.78802490234375, + "win_0-50": 0.7203065134099617, + "gap_50-100": 38.11271667480469, + "win_50-100": 0.6271186440677966, + "gap_100-200": 9.85483455657959, + "win_100-200": 0.5897959183673469, + "gap_200+": 6.860384464263916, + "win_200+": 0.6201696512723845 + }, + { + "beta": 0.98, + "depth": 3, + "eff_frames": 142.62499999999986, + "gamma_eff": 0.992988606485539, + "gap_pooled": -30.98450469970703, + "win_pooled": 0.53857421875, + "gap_pooled_crosstask": -76.52243041992188, + "win_pooled_crosstask": 0.5615234375, + "state_auc": 0.6020416259765625, + "gap_0-50": 93.0474624633789, + "win_0-50": 0.685823754789272, + "gap_50-100": -7.158599853515625, + "win_50-100": 0.5550847457627118, + "gap_100-200": -56.07952880859375, + "win_100-200": 0.5122448979591837, + "gap_200+": -55.205711364746094, + "win_200+": 0.5108388312912346 + }, + { + "beta": 0.99, + "depth": 1, + "eff_frames": 99.99999999999991, + "gamma_eff": 0.99, + "gap_pooled": -60.12482452392578, + "win_pooled": 0.45654296875, + "gap_pooled_crosstask": -129.4288787841797, + "win_pooled_crosstask": 0.5185546875, + "state_auc": 0.6174367268880209, + "gap_0-50": 83.76277923583984, + "win_0-50": 0.6091954022988506, + "gap_50-100": -40.346195220947266, + "win_50-100": 0.5550847457627118, + "gap_100-200": -67.20990753173828, + "win_100-200": 0.4346938775510204, + "gap_200+": -96.64766693115234, + "win_200+": 0.4071630537229029 + }, + { + "beta": 0.99, + "depth": 2, + "eff_frames": 190.0900900900899, + "gamma_eff": 0.994739336492891, + "gap_pooled": 24.974506378173828, + "win_pooled": 0.61328125, + "gap_pooled_crosstask": -10.323814392089844, + "win_pooled_crosstask": 0.64697265625, + "state_auc": 0.5864532470703125, + "gap_0-50": 148.56842041015625, + "win_0-50": 0.7126436781609196, + "gap_50-100": 36.02408981323242, + "win_50-100": 0.6610169491525424, + "gap_100-200": 2.261622667312622, + "win_100-200": 0.5836734693877551, + "gap_200+": 2.602782964706421, + "win_200+": 0.5918944392082941 + }, + { + "beta": 0.99, + "depth": 3, + "eff_frames": 271.2523334144953, + "gamma_eff": 0.9963133957691271, + "gap_pooled": -26.120960235595703, + "win_pooled": 0.541015625, + "gap_pooled_crosstask": -76.4961929321289, + "win_pooled_crosstask": 0.53173828125, + "state_auc": 0.5991790771484375, + "gap_0-50": 91.29505157470703, + "win_0-50": 0.632183908045977, + "gap_50-100": -0.051404986530542374, + "win_50-100": 0.5932203389830508, + "gap_100-200": -51.6431999206543, + "win_100-200": 0.5040816326530613, + "gap_200+": -49.01643371582031, + "win_200+": 0.5240339302544769 + }, + { + "beta": 0.995, + "depth": 1, + "eff_frames": 199.99999999999983, + "gamma_eff": 0.995, + "gap_pooled": -68.11668395996094, + "win_pooled": 0.4619140625, + "gap_pooled_crosstask": -134.58949279785156, + "win_pooled_crosstask": 0.50146484375, + "state_auc": 0.6300608317057291, + "gap_0-50": 89.25088500976562, + "win_0-50": 0.6245210727969349, + "gap_50-100": -54.56651306152344, + "win_50-100": 0.559322033898305, + "gap_100-200": -72.14842224121094, + "win_100-200": 0.45918367346938777, + "gap_200+": -107.98023223876953, + "win_200+": 0.40150801131008484 + }, + { + "beta": 0.995, + "depth": 2, + "eff_frames": 360.1601601601599, + "gamma_eff": 0.9972234574763758, + "gap_pooled": 15.491418838500977, + "win_pooled": 0.5751953125, + "gap_pooled_crosstask": -22.10919189453125, + "win_pooled_crosstask": 0.6171875, + "state_auc": 0.6097300211588542, + "gap_0-50": 146.7181854248047, + "win_0-50": 0.7088122605363985, + "gap_50-100": 23.76041603088379, + "win_50-100": 0.5720338983050848, + "gap_100-200": -3.270139217376709, + "win_100-200": 0.5346938775510204, + "gap_200+": -9.964289665222168, + "win_200+": 0.5617342130065975 + }, + { + "beta": 0.995, + "depth": 3, + "eff_frames": 488.41654467280046, + "gamma_eff": 0.9979525673097951, + "gap_pooled": -25.263416290283203, + "win_pooled": 0.53662109375, + "gap_pooled_crosstask": -73.59703826904297, + "win_pooled_crosstask": 0.51708984375, + "state_auc": 0.6070821126302083, + "gap_0-50": 102.81361389160156, + "win_0-50": 0.6551724137931034, + "gap_50-100": -12.5304536819458, + "win_50-100": 0.5889830508474576, + "gap_100-200": -42.36178970336914, + "win_100-200": 0.5204081632653061, + "gap_200+": -51.70533752441406, + "win_200+": 0.5032987747408105 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/sweep_actcon01.json b/frozen/rsm_libero_rsmpi/results/sweep_actcon01.json new file mode 100644 index 0000000000000000000000000000000000000000..b99b04db04fb7ca934f9971c729e31c8f77a4a52 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/sweep_actcon01.json @@ -0,0 +1,230 @@ +[ + { + "beta": 0.96, + "depth": 1, + "eff_frames": 24.99999999999998, + "gamma_eff": 0.96, + "gap_pooled": 6.30864143371582, + "win_pooled": 0.48974609375, + "gap_pooled_crosstask": 5.91621732711792, + "win_pooled_crosstask": 0.4765625, + "state_auc": 0.6868655641649493, + "gap_0-50": 53.18166732788086, + "win_0-50": 0.6010050251256281, + "gap_50-100": -1.352872610092163, + "win_50-100": 0.5072324011571842, + "gap_100-200": -0.8440123200416565, + "win_100-200": 0.4645354645354645, + "gap_200+": 0.4466739594936371, + "win_200+": 0.4708994708994709 + }, + { + "beta": 0.96, + "depth": 2, + "eff_frames": 48.74999999999993, + "gamma_eff": 0.9794871794871794, + "gap_pooled": 5.7522172927856445, + "win_pooled": 0.4842529296875, + "gap_pooled_crosstask": 3.9665169715881348, + "win_pooled_crosstask": 0.478515625, + "state_auc": 0.6975916856370438, + "gap_0-50": 55.342628479003906, + "win_0-50": 0.5798994974874372, + "gap_50-100": 2.232736349105835, + "win_50-100": 0.5053037608486017, + "gap_100-200": -2.134530782699585, + "win_100-200": 0.46703296703296704, + "gap_200+": -1.439578652381897, + "win_200+": 0.46440596440596443 + }, + { + "beta": 0.96, + "depth": 3, + "eff_frames": 71.31249999999993, + "gamma_eff": 0.985977212971078, + "gap_pooled": 5.2091827392578125, + "win_pooled": 0.48828125, + "gap_pooled_crosstask": 2.6576032638549805, + "win_pooled_crosstask": 0.47998046875, + "state_auc": 0.6982983088828134, + "gap_0-50": 53.2354736328125, + "win_0-50": 0.5758793969849246, + "gap_50-100": 7.161194801330566, + "win_50-100": 0.5226615236258437, + "gap_100-200": -3.719944953918457, + "win_100-200": 0.468031968031968, + "gap_200+": -2.471020221710205, + "win_200+": 0.4684944684944685 + }, + { + "beta": 0.98, + "depth": 1, + "eff_frames": 49.99999999999996, + "gamma_eff": 0.98, + "gap_pooled": 6.295346260070801, + "win_pooled": 0.48291015625, + "gap_pooled_crosstask": 5.396781921386719, + "win_pooled_crosstask": 0.474365234375, + "state_auc": 0.6895984549860658, + "gap_0-50": 54.81524658203125, + "win_0-50": 0.6090452261306533, + "gap_50-100": -0.7992590665817261, + "win_50-100": 0.5284474445515911, + "gap_100-200": -1.1928950548171997, + "win_100-200": 0.47002997002997005, + "gap_200+": 0.05947805568575859, + "win_200+": 0.44757094757094756 + }, + { + "beta": 0.98, + "depth": 2, + "eff_frames": 97.49999999999986, + "gamma_eff": 0.9897435897435898, + "gap_pooled": 5.325685501098633, + "win_pooled": 0.48388671875, + "gap_pooled_crosstask": 3.506357192993164, + "win_pooled_crosstask": 0.4827880859375, + "state_auc": 0.7004525566035722, + "gap_0-50": 53.64113235473633, + "win_0-50": 0.5648241206030151, + "gap_50-100": 5.9683966636657715, + "win_50-100": 0.5274831243972999, + "gap_100-200": -3.4839394092559814, + "win_100-200": 0.46403596403596403, + "gap_200+": -2.1547107696533203, + "win_200+": 0.46320346320346323 + }, + { + "beta": 0.98, + "depth": 3, + "eff_frames": 142.62499999999986, + "gamma_eff": 0.992988606485539, + "gap_pooled": 5.533291816711426, + "win_pooled": 0.4918212890625, + "gap_pooled_crosstask": 1.2059924602508545, + "win_pooled_crosstask": 0.4788818359375, + "state_auc": 0.6955710735894732, + "gap_0-50": 52.95362854003906, + "win_0-50": 0.563819095477387, + "gap_50-100": 10.891581535339355, + "win_50-100": 0.5226615236258437, + "gap_100-200": -3.717881202697754, + "win_100-200": 0.4675324675324675, + "gap_200+": -2.6963698863983154, + "win_200+": 0.4785954785954786 + }, + { + "beta": 0.99, + "depth": 1, + "eff_frames": 99.99999999999991, + "gamma_eff": 0.99, + "gap_pooled": 5.030198574066162, + "win_pooled": 0.4903564453125, + "gap_pooled_crosstask": 4.482872009277344, + "win_pooled_crosstask": 0.473388671875, + "state_auc": 0.6890126312717897, + "gap_0-50": 43.38360595703125, + "win_0-50": 0.5869346733668341, + "gap_50-100": -0.8099265098571777, + "win_50-100": 0.5197685631629702, + "gap_100-200": -0.7152834534645081, + "win_100-200": 0.476023976023976, + "gap_200+": 0.07517894357442856, + "win_200+": 0.4668109668109668 + }, + { + "beta": 0.99, + "depth": 2, + "eff_frames": 190.0900900900899, + "gamma_eff": 0.994739336492891, + "gap_pooled": 3.990938425064087, + "win_pooled": 0.48388671875, + "gap_pooled_crosstask": 2.947385787963867, + "win_pooled_crosstask": 0.4820556640625, + "state_auc": 0.6884089513406015, + "gap_0-50": 41.63627243041992, + "win_0-50": 0.5738693467336683, + "gap_50-100": 4.091736793518066, + "win_50-100": 0.5380906460945034, + "gap_100-200": -2.1627180576324463, + "win_100-200": 0.45704295704295705, + "gap_200+": -2.0797717571258545, + "win_200+": 0.46176046176046176 + }, + { + "beta": 0.99, + "depth": 3, + "eff_frames": 271.2523334144953, + "gamma_eff": 0.9963133957691271, + "gap_pooled": 3.611988067626953, + "win_pooled": 0.494140625, + "gap_pooled_crosstask": 2.0005316734313965, + "win_pooled_crosstask": 0.4805908203125, + "state_auc": 0.6812484177231277, + "gap_0-50": 42.16130447387695, + "win_0-50": 0.6040201005025125, + "gap_50-100": 7.271562099456787, + "win_50-100": 0.5207328833172613, + "gap_100-200": -4.476435661315918, + "win_100-200": 0.47352647352647353, + "gap_200+": -2.63104248046875, + "win_200+": 0.47113997113997114 + }, + { + "beta": 0.995, + "depth": 1, + "eff_frames": 199.99999999999983, + "gamma_eff": 0.995, + "gap_pooled": 6.226694583892822, + "win_pooled": 0.4937744140625, + "gap_pooled_crosstask": 5.46646785736084, + "win_pooled_crosstask": 0.4813232421875, + "state_auc": 0.6890978454599711, + "gap_0-50": 53.39063262939453, + "win_0-50": 0.6060301507537689, + "gap_50-100": -0.2218518704175949, + "win_50-100": 0.5188042430086789, + "gap_100-200": -0.9892496466636658, + "win_100-200": 0.47802197802197804, + "gap_200+": 0.023074371740221977, + "win_200+": 0.46825396825396826 + }, + { + "beta": 0.995, + "depth": 2, + "eff_frames": 360.1601601601599, + "gamma_eff": 0.9972234574763758, + "gap_pooled": 5.552397727966309, + "win_pooled": 0.4931640625, + "gap_pooled_crosstask": 3.7978029251098633, + "win_pooled_crosstask": 0.4825439453125, + "state_auc": 0.6908156643631088, + "gap_0-50": 52.535335540771484, + "win_0-50": 0.5829145728643216, + "gap_50-100": 6.096987724304199, + "win_50-100": 0.5274831243972999, + "gap_100-200": -3.048335075378418, + "win_100-200": 0.4695304695304695, + "gap_200+": -1.685240626335144, + "win_200+": 0.4745069745069745 + }, + { + "beta": 0.995, + "depth": 3, + "eff_frames": 488.41654467280046, + "gamma_eff": 0.9979525673097951, + "gap_pooled": 4.832504749298096, + "win_pooled": 0.4888916015625, + "gap_pooled_crosstask": 2.0376412868499756, + "win_pooled_crosstask": 0.48095703125, + "state_auc": 0.687118537828745, + "gap_0-50": 52.42646026611328, + "win_0-50": 0.5718592964824121, + "gap_50-100": 8.476884841918945, + "win_50-100": 0.532304725168756, + "gap_100-200": -4.376927852630615, + "win_100-200": 0.45054945054945056, + "gap_200+": -3.031353235244751, + "win_200+": 0.4766714766714767 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/results/sweep_base.json b/frozen/rsm_libero_rsmpi/results/sweep_base.json new file mode 100644 index 0000000000000000000000000000000000000000..bbaa528bb0af6955eb2e55075299d45a94d6e59f --- /dev/null +++ b/frozen/rsm_libero_rsmpi/results/sweep_base.json @@ -0,0 +1,230 @@ +[ + { + "beta": 0.96, + "depth": 1, + "eff_frames": 24.99999999999998, + "gamma_eff": 0.96, + "gap_pooled": 2.919712543487549, + "win_pooled": 0.5205078125, + "gap_pooled_crosstask": 2.7210028171539307, + "win_pooled_crosstask": 0.494140625, + "state_auc": 0.6619578043619792, + "gap_0-50": 27.9962100982666, + "win_0-50": 0.6398467432950191, + "gap_50-100": -0.9122968912124634, + "win_50-100": 0.5127118644067796, + "gap_100-200": -2.5012218952178955, + "win_100-200": 0.5102040816326531, + "gap_200+": 0.10693741589784622, + "win_200+": 0.49764373232799247 + }, + { + "beta": 0.96, + "depth": 2, + "eff_frames": 48.74999999999993, + "gamma_eff": 0.9794871794871794, + "gap_pooled": 2.280273914337158, + "win_pooled": 0.5009765625, + "gap_pooled_crosstask": 1.7893123626708984, + "win_pooled_crosstask": 0.5146484375, + "state_auc": 0.6495737711588542, + "gap_0-50": 20.17959976196289, + "win_0-50": 0.6015325670498084, + "gap_50-100": -0.04096969589591026, + "win_50-100": 0.5084745762711864, + "gap_100-200": -1.4540495872497559, + "win_100-200": 0.5040816326530613, + "gap_200+": 0.11807619035243988, + "win_200+": 0.473138548539114 + }, + { + "beta": 0.96, + "depth": 3, + "eff_frames": 71.31249999999993, + "gamma_eff": 0.985977212971078, + "gap_pooled": 3.340029716491699, + "win_pooled": 0.49658203125, + "gap_pooled_crosstask": 2.551269292831421, + "win_pooled_crosstask": 0.50439453125, + "state_auc": 0.6516652425130208, + "gap_0-50": 29.56572914123535, + "win_0-50": 0.578544061302682, + "gap_50-100": -1.016560673713684, + "win_50-100": 0.4449152542372881, + "gap_100-200": -1.5416101217269897, + "win_100-200": 0.47346938775510206, + "gap_200+": 0.11217954009771347, + "win_200+": 0.49858623939679547 + }, + { + "beta": 0.98, + "depth": 1, + "eff_frames": 49.99999999999996, + "gamma_eff": 0.98, + "gap_pooled": 4.422482490539551, + "win_pooled": 0.490234375, + "gap_pooled_crosstask": 3.0656747817993164, + "win_pooled_crosstask": 0.47021484375, + "state_auc": 0.6657206217447916, + "gap_0-50": 36.3089599609375, + "win_0-50": 0.6053639846743295, + "gap_50-100": -2.8381195068359375, + "win_50-100": 0.5211864406779662, + "gap_100-200": -1.0212669372558594, + "win_100-200": 0.45918367346938777, + "gap_200+": 0.7076546549797058, + "win_200+": 0.46936852026390197 + }, + { + "beta": 0.98, + "depth": 2, + "eff_frames": 97.49999999999986, + "gamma_eff": 0.9897435897435898, + "gap_pooled": 3.420022964477539, + "win_pooled": 0.5068359375, + "gap_pooled_crosstask": 3.1979477405548096, + "win_pooled_crosstask": 0.4892578125, + "state_auc": 0.6654937744140625, + "gap_0-50": 31.808181762695312, + "win_0-50": 0.6130268199233716, + "gap_50-100": 0.33880019187927246, + "win_50-100": 0.5338983050847458, + "gap_100-200": -2.4181067943573, + "win_100-200": 0.47551020408163264, + "gap_200+": -0.18172825872898102, + "win_200+": 0.4891611687087653 + }, + { + "beta": 0.98, + "depth": 3, + "eff_frames": 142.62499999999986, + "gamma_eff": 0.992988606485539, + "gap_pooled": 3.5487027168273926, + "win_pooled": 0.50390625, + "gap_pooled_crosstask": 2.7771530151367188, + "win_pooled_crosstask": 0.50341796875, + "state_auc": 0.6565541585286458, + "gap_0-50": 27.154804229736328, + "win_0-50": 0.5977011494252874, + "gap_50-100": 1.9898091554641724, + "win_50-100": 0.4830508474576271, + "gap_100-200": -1.0167019367218018, + "win_100-200": 0.49795918367346936, + "gap_200+": 0.19691623747348785, + "win_200+": 0.4882186616399623 + }, + { + "beta": 0.99, + "depth": 1, + "eff_frames": 99.99999999999991, + "gamma_eff": 0.99, + "gap_pooled": 4.452927589416504, + "win_pooled": 0.51025390625, + "gap_pooled_crosstask": 2.8550586700439453, + "win_pooled_crosstask": 0.4912109375, + "state_auc": 0.6666798909505208, + "gap_0-50": 33.996402740478516, + "win_0-50": 0.6398467432950191, + "gap_50-100": 1.073217749595642, + "win_50-100": 0.5296610169491526, + "gap_100-200": -1.5662366151809692, + "win_100-200": 0.47959183673469385, + "gap_200+": 0.7169742584228516, + "win_200+": 0.4882186616399623 + }, + { + "beta": 0.99, + "depth": 2, + "eff_frames": 190.0900900900899, + "gamma_eff": 0.994739336492891, + "gap_pooled": 3.6026997566223145, + "win_pooled": 0.5185546875, + "gap_pooled_crosstask": 1.7554620504379272, + "win_pooled_crosstask": 0.48193359375, + "state_auc": 0.6637013753255209, + "gap_0-50": 26.31501579284668, + "win_0-50": 0.5977011494252874, + "gap_50-100": 2.8295605182647705, + "win_50-100": 0.5466101694915254, + "gap_100-200": -1.1450427770614624, + "win_100-200": 0.5020408163265306, + "gap_200+": 0.380211740732193, + "win_200+": 0.5004712535344015 + }, + { + "beta": 0.99, + "depth": 3, + "eff_frames": 271.2523334144953, + "gamma_eff": 0.9963133957691271, + "gap_pooled": 3.078533411026001, + "win_pooled": 0.50537109375, + "gap_pooled_crosstask": 1.4733316898345947, + "win_pooled_crosstask": 0.49853515625, + "state_auc": 0.6554555257161458, + "gap_0-50": 27.982181549072266, + "win_0-50": 0.5593869731800766, + "gap_50-100": 2.456202268600464, + "win_50-100": 0.5127118644067796, + "gap_100-200": -1.2090694904327393, + "win_100-200": 0.45918367346938777, + "gap_200+": -0.9290597438812256, + "win_200+": 0.5117813383600377 + }, + { + "beta": 0.995, + "depth": 1, + "eff_frames": 199.99999999999983, + "gamma_eff": 0.995, + "gap_pooled": 4.393555641174316, + "win_pooled": 0.49853515625, + "gap_pooled_crosstask": 3.221923828125, + "win_pooled_crosstask": 0.486328125, + "state_auc": 0.6645701090494792, + "gap_0-50": 39.18448257446289, + "win_0-50": 0.6283524904214559, + "gap_50-100": -1.7130212783813477, + "win_50-100": 0.5127118644067796, + "gap_100-200": -1.7897416353225708, + "win_100-200": 0.45918367346938777, + "gap_200+": 0.049102868884801865, + "win_200+": 0.4816211121583412 + }, + { + "beta": 0.995, + "depth": 2, + "eff_frames": 360.1601601601599, + "gamma_eff": 0.9972234574763758, + "gap_pooled": 5.160642147064209, + "win_pooled": 0.4912109375, + "gap_pooled_crosstask": 3.7217297554016113, + "win_pooled_crosstask": 0.4873046875, + "state_auc": 0.6655629475911459, + "gap_0-50": 39.35454559326172, + "win_0-50": 0.6168582375478927, + "gap_50-100": 2.9915273189544678, + "win_50-100": 0.4872881355932203, + "gap_100-200": -0.6084309220314026, + "win_100-200": 0.4775510204081633, + "gap_200+": -0.10406177490949631, + "win_200+": 0.46748350612629597 + }, + { + "beta": 0.995, + "depth": 3, + "eff_frames": 488.41654467280046, + "gamma_eff": 0.9979525673097951, + "gap_pooled": 4.199846267700195, + "win_pooled": 0.515625, + "gap_pooled_crosstask": 2.3940823078155518, + "win_pooled_crosstask": 0.486328125, + "state_auc": 0.6591898600260416, + "gap_0-50": 37.53031539916992, + "win_0-50": 0.6206896551724138, + "gap_50-100": 4.017754077911377, + "win_50-100": 0.559322033898305, + "gap_100-200": -4.878033638000488, + "win_100-200": 0.47959183673469385, + "gap_200+": 0.23366372287273407, + "win_200+": 0.49670122525918947 + } +] \ No newline at end of file diff --git a/frozen/rsm_libero_rsmpi/reward_diag.py b/frozen/rsm_libero_rsmpi/reward_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..d6783a88e07eeb815acc9cb124bf3ffc4588d40f --- /dev/null +++ b/frozen/rsm_libero_rsmpi/reward_diag.py @@ -0,0 +1,56 @@ +"""How good is the RSM reward head, really? Held-out (val-split) frames, per task, plus the +two failure modes that matter for ranking: (a) goal-mismatch (right state, wrong task id), +(b) imagined endpoints (flow samples) vs. the true future subgoal fraction. +usage: reward_diag.py --cache C --critic ckpt [--subgoal-dir D] [--mask M]""" +import argparse, os, sys, numpy as np, torch +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from data import LiberoRSMData +from is_ope import load_critic +from train_rsm import sample_future, auc + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) +ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="") +ap.add_argument("--n", type=int, default=20000); ap.add_argument("--beta", type=float, default=0.98) +a = ap.parse_args() +dev = "cuda" if torch.cuda.is_available() else "cpu" +d = LiberoRSMData(a.cache, chunk=10, seed=0, in_ram=False, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, + success_mask=a.mask, norm_pool="demos") +enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d) +lat = enc # load_critic already wraps the encoder with the proprio append (same as the evaluator) +rng = np.random.default_rng(0) +with torch.no_grad(): + fb = d.sample_frames(a.n, rng, "val", dev) + x, tk, r = fb["x"], fb["task"], fb["r"].float() + z = lat(x); rh = torch.sigmoid(rew(z, tk)) + e = (rh - r); print(f"VAL frames n={a.n}: MSE={float(e.pow(2).mean()):.4f} (const-null MSE={float((r-r.mean()).pow(2).mean()):.4f}) " + f"Pearson={float(np.corrcoef(rh.cpu(), r.cpu())[0,1]):.3f} mean r={float(r.mean()):.3f} mean r_hat={float(rh.mean()):.3f}") + print(f" AUC(all subgoals satisfied, r==1): {auc(rh.cpu().numpy(), (r.cpu().numpy()>=0.999).astype(float)):.3f} " + f"AUC(any progress, r>0): {auc(rh.cpu().numpy(), (r.cpu().numpy()>0.001).astype(float)):.3f}") + # calibration by true fraction + for lo, hi in ((0, 0.001), (0.001, 0.4), (0.4, 0.7), (0.7, 0.999), (0.999, 1.01)): + m = (r >= lo) & (r < hi) + if m.any(): print(f" true r in [{lo:.2f},{hi:.2f}): n={int(m.sum()):6d} mean r_hat={float(rh[m].mean()):.3f} std={float(rh[m].std()):.3f}") + # per task + for t in range(d.n_task): + m = tk == t + if m.sum() > 50: + print(f" task {t}: n={int(m.sum()):5d} Pearson={float(np.corrcoef(rh[m].cpu(), r[m].cpu())[0,1]):.3f} MSE={float(e[m].pow(2).mean()):.4f} mean r={float(r[m].mean()):.3f}") + # (a) goal mismatch: same latent, wrong task id + tk2 = (tk + torch.randint(1, d.n_task, tk.shape, device=dev)) % d.n_task + rh2 = torch.sigmoid(rew(z, tk2)) + print(f"GOAL-MISMATCH (wrong task id): mean r_hat={float(rh2.mean()):.3f} vs correct-task {float(rh.mean()):.3f}; " + f"fraction where wrong-task r_hat > correct-task r_hat: {float((rh2 > rh).float().mean()):.3f}") + # (b) imagined endpoints: flow sample at beta vs true future subgoal fraction + vb = d.sample(min(a.n, 8192), rng, a.beta, a.beta, "val", dev) + zc = lat(vb["x_now"]); zf_true = lat(vb["x_fut"]) + zf_imag = sample_future(flow, zc, vb["a_now"], vb["task"], vb["beta"], rms, 8, n=1) + r_true_fut = torch.sigmoid(rew(zf_true, vb["task"])) + r_imag = torch.sigmoid(rew(zf_imag, vb["task"])) + print(f"IMAGINED ENDPOINTS (beta={a.beta}): r_hat(true future latent) mean={float(r_true_fut.mean()):.3f}, r_hat(flow sample) mean={float(r_imag.mean()):.3f}, " + f"Pearson(imagined, true-future r_hat)={float(np.corrcoef(r_imag.cpu(), r_true_fut.cpu())[0,1]):.3f}, " + f"Pearson(imagined, TRUE future subgoal fraction)={float(np.corrcoef(r_imag.cpu(), vb['r_fut'].float().cpu())[0,1]) if 'r_fut' in vb else float('nan'):.3f}") + # (c) random latents: gaussian noise in latent space -> base-rate drift? + zr = torch.randn_like(z) * z.std(0, keepdim=True) + z.mean(0, keepdim=True) + print(f"RANDOM LATENTS (matched moments): mean r_hat={float(torch.sigmoid(rew(zr, tk)).mean()):.3f}") +print("[diag] DONE") diff --git a/frozen/rsm_libero_rsmpi/rsm_main.py b/frozen/rsm_libero_rsmpi/rsm_main.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4a18bd041b51cf2b7467d577da05157cb535f4 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/rsm_main.py @@ -0,0 +1,325 @@ +"""origin/main's MIMICGEN RSM port, applied to the LIBERO-10 latent corpus. + +SCOPE CORRECTION. This file ports mimicgen_rsm/rsm_mimicgen/rsm.py, which is +ONE variant on main and not the main RSM recipe. The headline recipe in +ogbench_unified_rsm IS action-conditioned: its flow trains on (s, a, g) -> +s_{t+K} pairs and hop 1 uses the queried action. Only the mimicgen port drops +that, stating "NOT goal-conditioned ... d_beta(s'|s), reward(s), qf(s,a)". +Both are worth running here; do not read this file as "what main does". + +Our own recipe differs from main's in four ways that matter, and this file adopts +all four. See notes/rsm_formula_comparison.pdf for the derivation side. + +1. REWARD IS AN ARRIVAL DETECTOR, NOT AN OUTCOME PREDICTOR. + main: a classifier with a CALIBRATED threshold, hard-thresholded to + r_hat(s) = 1[logit > thr] - 1 in {0, -1}; the threshold is fit on held-out + episodes because "the classifier's scores are well ordered but not centred on + 0". ours (until now): r = 1 on EVERY frame of a successful episode, i.e. + P(this episode succeeds | s). Measured consequence of ours: a directly + supervised Q(z,a) beats a state-only V(z) by AUC 0.9550 vs 0.9539, delta + +0.0012 -- the action adds nothing, because whether an episode succeeds is a + property of the state, not of the next 10 frames. + +2. THE OCCUPANCY IS STATE-ONLY in THIS port: d_beta(s'|s). The ogbench recipe + conditions on the action instead; that variant is the action-conditioned + critic this lane already has. + +3. THE ACTION ENTERS BY SUPERVISED REGRESSION, NOT BY CONDITIONING A GENERATIVE + MODEL ON A COUNTERFACTUAL. main distils a student + qf(s,a) <- r + gamma * (1-done) * V(s'), s' the REAL logged next state, + with V from the frozen occupancy and, in their words, "no TD bootstrap off + qf". Ours conditioned the flow on a candidate action, which is unsupervised in + the action direction; probe_crn measured the result to have the right + magnitude and an arbitrary sign. + +4. ARRIVAL ABSORBS AND STOPPING IS GEOMETRIC OVER MANY HOPS. + p_stop = beta(1-gamma)/(gamma(1-beta)); a rollout stops on the coin OR on + reaching the goal, over max_hops (expected ~11 at beta=0.9, gamma=0.99). Ours + read the reward once at a fixed depth of 2-3. The reduction is an optimistic + hop-weighted expectile, not a plain mean. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from data import LiberoRSMData +from model import Encoder, RewardHead, OccFlow, mlp, ema_update +from train_rsm import auc + + +# --------------------------------------------------------------------------- # +def p_stop_of(beta: float, gamma: float) -> float: + """main's geometric stopping probability. beta <= gamma is required.""" + assert beta <= gamma, f"need beta <= gamma, got {beta} > {gamma}" + return beta * (1.0 - gamma) / (gamma * (1.0 - beta)) if beta < gamma else 1.0 + + +def hop_weighted_value(r, absorb_hop, tau, rho, gamma, gain=1.0): + """main's speed-weighted upper expectile over per-rollout returns in {0,-1}.""" + A = 1.0 / (2.0 * (1.0 - tau)) + is_goal = r == 0.0 + w = torch.where(is_goal, + 1.0 + (A - 1.0) * gain * rho ** (absorb_hop.clamp_min(1) - 1).float(), + torch.ones_like(r)) + return ((w * r).sum(1) / w.sum(1).clamp_min(1e-12)) / (1.0 - gamma) + + +def value_from_at_goal_prob(q, tau, gamma): + if tau == 0.5: + m = q - 1.0 + else: + num = (1.0 - tau) * (1.0 - q) + den = tau * q + (1.0 - tau) * (1.0 - q) + m = -num / den.clamp_min(1e-12) + return m / (1.0 - gamma) + + +class MainRSM(torch.nn.Module): + """State-only occupancy + thresholded arrival reward + geometric-stop value.""" + + def __init__(self, d_lat, n_task, width=1024, depth=4): + super().__init__() + # d_act=1 with a zero action: the occupancy is state-only by construction, + # while reusing the same FiLM/Fourier successor the rest of the lane uses. + self.flow = OccFlow(d_lat, 1, n_task, width=width, depth=depth) + self.rew = RewardHead(d_lat, n_task) + self.register_buffer("rms", torch.ones(d_lat)) + self.threshold = 0.0 + + def flow_v(self, z, task, beta, x_k, k): + a0 = torch.zeros(z.shape[0], 1, device=z.device) + return self.flow(z, a0, task, beta, x_k, k) + + @torch.no_grad() + def hop(self, z, task, beta, steps=8): + x = torch.randn_like(z) + for s in range(steps): + k = torch.full((z.shape[0],), 1.0 - s / steps, device=z.device) + x = x + self.flow_v(z, task, beta, x, k) / steps + return z + x * self.rms + + @torch.no_grad() + def r_hat(self, z, task): + """Hard arrival reward in {0, -1} at the CALIBRATED threshold.""" + return (self.rew(z, task) > self.threshold).float() - 1.0 + + @torch.no_grad() + def estimate_value(self, z, task, *, beta, gamma, n_samples=16, max_hops=20, + tau=0.5, rho=0.9, gain=1.0, mode="hop", flow_steps=8): + B = z.shape[0] + p_stop = p_stop_of(beta, gamma) + s = z.repeat_interleave(n_samples, 0) + tk = task.repeat_interleave(n_samples, 0) + bq = torch.full((s.shape[0],), beta, device=z.device) + M = s.shape[0] + active = torch.ones(M, dtype=torch.bool, device=z.device) + stopped = s.clone() + absorb = torch.zeros(M, dtype=torch.long, device=z.device) + for h in range(1, max_hops + 1): + s_next = self.hop(s, tk, bq, steps=flow_steps) + s = torch.where(active.unsqueeze(-1), s_next, s) + at_goal = self.r_hat(s, tk) == 0.0 + coin = torch.rand(M, device=z.device) < p_stop + just = active & (coin | at_goal) + absorb = torch.where(just & at_goal, torch.full_like(absorb, h), absorb) + stopped = torch.where(just.unsqueeze(-1), s, stopped) + active = active & ~just + if not active.any(): + break + stopped = torch.where(active.unsqueeze(-1), s, stopped) + r = self.r_hat(stopped, tk).reshape(B, n_samples) + ah = absorb.reshape(B, n_samples) + if mode == "hop": + return hop_weighted_value(r, ah, tau, rho, gamma, gain) + q = (r == 0.0).float().mean(1) + return value_from_at_goal_prob(q, tau, gamma) + + +class QStudent(torch.nn.Module): + def __init__(self, d_lat, d_act, n_task, d_task=64, width=1024, depth=3): + super().__init__() + self.task = torch.nn.Embedding(n_task, d_task) + self.net = mlp([d_lat + d_act + d_task] + [width] * depth + [1], norm=True) + + def forward(self, z, a, task): + return self.net(torch.cat([z, a, self.task(task)], -1)).squeeze(-1) + + +def calibrate_threshold(model, d, enc, dev, rng, n=8192): + """Fit the cutoff on HELD-OUT frames, as main does. + + Chosen to match the positive base rate rather than at logit 0: main's note is + that the scores are well ordered but not centred, and estimate_value + thresholds hard, so an uncentred cutoff silently changes the arrival rate. + """ + P, Y = [], [] + with torch.no_grad(): + for _ in range(max(1, n // 2048)): + b = d.sample_frames(2048, rng, "val", dev) + z = enc(b["x"]) + P.append(model.rew(z, b["task"]).cpu().numpy()) + Y.append(b["r"].cpu().numpy()) + P = np.concatenate(P); Y = np.concatenate(Y) + pos = float(Y.mean()) + thr = float(np.quantile(P, 1.0 - pos)) if 0 < pos < 1 else 0.0 + a = auc(P, Y) + at_rate = float((P > thr).mean()) + return thr, a, pos, at_rate + + +# --------------------------------------------------------------------------- # +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--d-z", type=int, default=256) + ap.add_argument("--enc-width", type=int, default=1024) + ap.add_argument("--flow-width", type=int, default=1024) + ap.add_argument("--flow-depth", type=int, default=4) + ap.add_argument("--beta", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--k-success", type=int, default=10, + help="frames at the END of a successful episode counted as " + "AT GOAL. This is main's arrival convention; the dense " + "whole-episode label is an outcome predictor and was " + "measured to carry no action information.") + ap.add_argument("--n-value-samples", type=int, default=16) + ap.add_argument("--max-hops", type=int, default=20) + ap.add_argument("--value-expectile", type=float, default=0.7) + ap.add_argument("--expectile-mode", default="hop", choices=["hop", "reward"]) + ap.add_argument("--hop-rho", type=float, default=0.9) + ap.add_argument("--occ-steps", type=int, default=20000) + ap.add_argument("--qf-steps", type=int, default=40000) + ap.add_argument("--distill-states", type=int, default=153600, + help="transitions in the distillation buffer; V is " + "computed once per transition, not per batch") + ap.add_argument("--batch", type=int, default=512) + ap.add_argument("--qf-batch", type=int, default=256) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--ema", type=float, default=0.005) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + 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" + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + # ARRIVAL labels, not outcome labels + d = LiberoRSMData(args.cache, chunk=args.chunk, k_success=args.k_success, + seed=args.seed, in_ram=bool(args.in_ram), + reward_mode="terminal", norm_pool=args.norm_pool) + print(f"[main-rsm] {d.n_ep} eps, at-goal frames {float(d.r.mean()):.4f} " + f"(main's arrival convention), p_stop " + f"{p_stop_of(args.beta, args.gamma):.4f}, E[hops] " + f"{1.0 / max(p_stop_of(args.beta, args.gamma), 1e-9):.1f}", flush=True) + + enc = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) + enc_t = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) + enc_t.load_state_dict(enc.state_dict()) + for p in enc_t.parameters(): + p.requires_grad_(False) + m = MainRSM(args.d_z, d.n_task, args.flow_width, args.flow_depth).to(dev) + opt = torch.optim.AdamW(list(enc.parameters()) + list(m.flow.parameters()) + + list(m.rew.parameters()), lr=args.lr, weight_decay=0.01) + rng = np.random.default_rng(args.seed) + pos_w = torch.tensor(max((1 - d.r.mean()) / max(d.r.mean(), 1e-6), 1.0), device=dev) + + # ---- stage 1: state-only occupancy + arrival classifier ---- + for step in range(1, args.occ_steps + 1): + b = d.sample(args.batch, rng, args.beta, args.beta, "train", dev) + z = enc(b["x_now"]) + with torch.no_grad(): + z_fut = enc_t(b["x_fut"]) + l_rew = F.binary_cross_entropy_with_logits( + m.rew(z, b["task"]), b["r_now"], pos_weight=pos_w) + delta = z_fut - (z.detach() if step <= 2000 else z) + with torch.no_grad(): + m.rms.mul_(0.99).add_(delta.pow(2).mean(0).sqrt().clamp_min(1e-3), alpha=0.01) + y = delta / m.rms + k = torch.rand(args.batch, device=dev) + noise = torch.randn_like(y) + x_k = (1 - k)[:, None] * y + k[:, None] * noise + v = m.flow_v(z if step > 2000 else z.detach(), b["task"], b["beta"], x_k, k) + l_cfm = (v - (y - noise)).pow(2).mean() + std = z.std(0) + loss = l_rew + l_cfm + 10.0 * F.relu(0.1 - std).mean() + opt.zero_grad(); loss.backward() + torch.nn.utils.clip_grad_norm_( + list(enc.parameters()) + list(m.flow.parameters()) + + list(m.rew.parameters()), 1.0) + opt.step(); ema_update(enc_t, enc, args.ema) + if step % 2000 == 0: + print(f"[occ] {step} rew={float(l_rew):.4f} cfm={float(l_cfm):.4f}", + flush=True) + + enc.eval(); m.eval() + torch.save({"enc": enc.state_dict(), "flow": m.flow.state_dict(), + "rew": m.rew.state_dict(), "rms": m.rms.cpu(), + "config": vars(args)}, out / "stage1.pt") + thr, a_r, pos, at_rate = calibrate_threshold(m, d, enc, dev, + np.random.default_rng(args.seed + 5)) + m.threshold = thr + print(f"[main-rsm] arrival classifier AUC {a_r:.4f}; threshold {thr:+.3f} " + f"calibrated to base rate {pos:.4f} (at-goal rate {at_rate:.4f})", + flush=True) + + # ---- stage 2: distil qf(z,a) <- r + gamma (1-done) V(z'), REAL z' ---- + # Build the distillation BUFFER once. Recomputing V per batch means a fresh + # 16-rollout, 20-hop expansion every step (<1.7 steps/s measured); the target + # does not change during stage 2, so it is computed once and regressed on. + rq = np.random.default_rng(args.seed + 11) + Z, ZA, TK, TG = [], [], [], [] + got, bs = 0, 512 + while got < args.distill_states: + b = d.sample_frames(bs, rq, "train", dev) + t_next = np.minimum(b["t_idx"] + d.chunk, d.ep_to[b["ep"]] - 1) + done = torch.from_numpy( + (t_next >= d.ep_to[b["ep"]] - 1).astype(np.float32)).to(dev) + with torch.no_grad(): + z = enc(b["x"]) + zn = enc(torch.from_numpy(d._feat(t_next)).to(dev)) + r_now = m.r_hat(z, b["task"]) + v_next = m.estimate_value( + zn, b["task"], beta=args.beta, gamma=args.gamma, + n_samples=args.n_value_samples, max_hops=args.max_hops, + tau=args.value_expectile, rho=args.hop_rho, + mode=args.expectile_mode) + target = r_now + args.gamma * (1 - done) * v_next + Z.append(z.cpu()); ZA.append(b["a"].cpu()) + TK.append(b["task"].cpu()); TG.append(target.cpu()) + got += bs + if got % 25600 == 0: + print(f"[buf] {got}/{args.distill_states} " + f"target_mean={float(target.mean()):.3f}", flush=True) + Z = torch.cat(Z); ZA = torch.cat(ZA); TK = torch.cat(TK); TG = torch.cat(TG) + print(f"[buf] done {tuple(Z.shape)} target mean {float(TG.mean()):.3f} " + f"sd {float(TG.std()):.3f}", flush=True) + + qf = QStudent(args.d_z, d.chunk * d.adim, d.n_task).to(dev) + qopt = torch.optim.Adam(qf.parameters(), lr=args.lr) + for step in range(1, args.qf_steps + 1): + idx = torch.randint(0, len(Z), (args.qf_batch,)) + loss = F.mse_loss(qf(Z[idx].to(dev), ZA[idx].to(dev), TK[idx].to(dev)), + TG[idx].to(dev)) + qopt.zero_grad(); loss.backward() + torch.nn.utils.clip_grad_norm_(qf.parameters(), 1.0); qopt.step() + if step % 4000 == 0: + print(f"[qf] {step} loss={float(loss):.4f}", flush=True) + + torch.save({"enc": enc.state_dict(), "flow": m.flow.state_dict(), + "rew": m.rew.state_dict(), "rms": m.rms.cpu(), + "threshold": thr, "qf": qf.state_dict(), + "config": vars(args), "d_act": d.chunk * d.adim, + "tasks": d.tasks, "arrival_auc": a_r}, out / "main_rsm.pt") + print("[main-rsm] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/rsmpi_weights.py b/frozen/rsm_libero_rsmpi/rsmpi_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..15364fe76a4a2fec0ff49a2f0609e16ce8b46cfa --- /dev/null +++ b/frozen/rsm_libero_rsmpi/rsmpi_weights.py @@ -0,0 +1,52 @@ +"""RSM-pi hop importance weights (port of gen_q study/ocbench-rsm-qpi rsm.py `_pi_hop_weights` + +utils/rsm_datasets.py `pi_dec_*` decision slots) for the Monte-Carlo successor fit of train_rsm.py. + +The successor target of a training row is the LOGGED frame s_{t+k} (data.py: fut = t + k, k >= 0, truncated +geometric, always inside the episode). The behaviour policy mu re-decides every H env steps, so the decisions that +move s_{t+k} are the ones at t + m*H with m >= 1 and m*H <= k-1 (the chunk at t itself is the CONDITIONING action, +not reweighted). Under pi_R = mu * rho_R the occupancy is reweighted by the product of rho_R over those decisions: + + W = exp(clip(sum_{m>=1: m*H <= k-1, t+m*H <= last frame} logrho_R[t + m*H], -clip, clip)), then W /= mean_batch(W) + +logrho_R[row] = log rho_R(s_row, A_row) for the DATA chunk at that row (scripts/rsmpi/label.py). t + m*H <= last +frame is implied by m*H <= k-1 (fut <= last frame) but is kept explicit, as in the branch. +""" +from __future__ import annotations +import numpy as np + + +def pi_hop_weights(logrho, t_idx, fut_idx, ep, ep_to, H=8, clip=6.0): + """-> (w float32 [B] with mean 1, info dict). All index arrays are numpy int (data.sample's t_idx/fut_idx/ep).""" + t = np.asarray(t_idx, np.int64) + fut = np.asarray(fut_idx, np.int64) + last = np.asarray(ep_to, np.int64)[np.asarray(ep, np.int64)] - 1 + k = fut - t + B = len(t) + logw = np.zeros(B, np.float64) + ndec = np.zeros(B, np.int64) + mmax = int(((k - 1) // H).max()) if B else 0 + for m in range(1, max(mmax, 0) + 1): + dec = t + m * H + valid = (m * H <= k - 1) & (dec <= last) + if not valid.any(): + continue + logw += np.where(valid, logrho[np.minimum(dec, last)], 0.0) + ndec += valid + clipped = np.abs(logw) > clip + w = np.exp(np.clip(logw, -clip, clip)) + w = w / w.mean() + info = {"pi_hop_w_ess": float(w.sum() ** 2 / max((w ** 2).sum(), 1e-12) / max(B, 1)), + "pi_hop_w_max": float(w.max()) if B else 0.0, + "pi_hop_logw_clip_frac": float(clipped.mean()) if B else 0.0, + "pi_hop_decisions": float(ndec.mean()) if B else 0.0, + "pi_hop_logw_mean": float(logw.mean()) if B else 0.0} + return w.astype(np.float32), info + + +def load_logrho(path, n_frames): + lr = np.load(path).astype(np.float64).ravel() + if len(lr) != n_frames: + raise ValueError(f"--pi-logrho-npy {path}: {len(lr)} entries, cache has {n_frames} frames") + if not np.isfinite(lr).all(): + raise ValueError(f"--pi-logrho-npy {path}: non-finite entries") + return lr diff --git a/frozen/rsm_libero_rsmpi/run_cell.sh b/frozen/rsm_libero_rsmpi/run_cell.sh new file mode 100644 index 0000000000000000000000000000000000000000..f265e371adf207ae96d6f83c3d57599084bedf8d --- /dev/null +++ b/frozen/rsm_libero_rsmpi/run_cell.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# Self-resubmitting cell on IBM's preemptable queue (SIGINT on preemption; LSF -r does not +# requeue). Both train_rsm.py (--resume 1, ckpt.pt) and bc_arm.py (bc_resume.pt) continue +# from their last checkpoint, so a preempted cell picks up where it left off. +set -uo pipefail +B=/proj/dmfexp/zwhong/rsm_libero; PY=/proj/dmfexp/zwhong/venvs/lerobot_env/bin/python +cd $B/code; export PYTHONUNBUFFERED=1 +echo "[cell] $CELL start $(date -u +%T) on $(hostname)" +eval "$PY $CMD"; RC=$? +echo "[cell] $CELL rc=$RC $(date -u +%T)" +DONE=$(grep -qE "^\[(rsm|bc_arm|iql)\] DONE" $O/logs/$CELL.out 2>/dev/null && echo 1 || echo 0) +if [ "$RC" -ne 0 ] && [ "$DONE" = 0 ]; then + echo "[cell] $CELL incomplete -> resubmitting" + bsub -G grp_preemptable -q preemptable -r -gpu num=1 -n 8 -M 160G -R 'rusage[mem=160G]' -J $CELL \ + -o $O/logs/$CELL.out -e $O/logs/$CELL.err -env "all, CELL=$CELL, CMD=$CMD, O=$O" $B/run_cell.sh +fi +exit $RC diff --git a/frozen/rsm_libero_rsmpi/run_ope.py b/frozen/rsm_libero_rsmpi/run_ope.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d6a6167bd9d645022263ab0b9416d13a150d09 --- /dev/null +++ b/frozen/rsm_libero_rsmpi/run_ope.py @@ -0,0 +1,171 @@ +"""Driver: pi_0 -> ratio -> endpoint weight -> IS-corrected Q, with the gate. + +Order of operations is deliberate. The IS machinery is validated BEFORE any +policy is trained on it, because a critic that is never checked is how the +smolvla line shipped an advantage of 0.019 and a null AWR result. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import (load_critic, train_bc, train_ratio, train_endpoint_ratio, + train_likelihood_ratio, + q_recursive, precompute_decision_logratio, chunk_logW_fast, + effective_horizon) +from train_rsm import auc + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--batch", type=int, default=512) + 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=16) + ap.add_argument("--bc-steps", type=int, default=8000) + ap.add_argument("--ratio-steps", type=int, default=6000) + ap.add_argument("--wend-steps", type=int, default=6000) + ap.add_argument("--pi-mode", default="succ", choices=["succ", "all"], + help="succ = BC on successful rollouts (a genuinely better " + "target policy); all = BC on everything, which approximates " + "the behaviour policy and is the NULL control: with pi ~= mu " + "the weights must be ~1 and IS must not move Q.") + 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-mode", default="classifier", + choices=["classifier", "likelihood"], + help="classifier = discriminative density ratio (SHOWN BROKEN: " + "an identity control puts two same-data policies at 0.945-" + "0.977 separability, so the logit reads network identity). " + "likelihood = genuine pi/mu_hat with tractable Gaussians.") + 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("--reward-mode", default="dense", choices=["dense","terminal"], + 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="flow", choices=["flow", "gauss"]) + 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() + + # 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) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + args.d_z = cfg["d_z"] + rng = np.random.default_rng(args.seed + 7) + report = {"config": vars(args)} + + only_succ = (args.pi_mode == "succ") + print(f"=== pi_0: behaviour cloning ({'successes only' if only_succ else 'ALL data (null control)'}) ===", + flush=True) + pol = train_bc(d, enc, args, dev, only_success=only_succ, steps=args.bc_steps) + + print("=== step 1: per-decision density ratio by classification ===", flush=True) + rc = args.ratio_chunk or d.chunk + if args.ratio_mode == "likelihood": + ratio, pol_dec = train_likelihood_ratio( + d, enc, args, dev, steps=args.ratio_steps, + only_success=only_succ, chunk_len=rc) + elif rc != d.chunk: + print(f"=== fitting a DECISION-level policy (chunk {rc}) for the ratio ===", + flush=True) + print(f"=== fitting a DECISION-level policy (chunk {rc}) for the ratio ===", + flush=True) + pol_dec = train_bc(d, enc, args, dev, only_success=only_succ, + steps=args.bc_steps, chunk_len=rc) + ratio = train_ratio(d, enc, pol_dec, args, dev, steps=args.ratio_steps) + else: + pol_dec = pol + ratio = train_ratio(d, enc, pol_dec, args, dev, steps=args.ratio_steps) + + print("=== step 2/3: endpoint weight (Rao-Blackwellized) ===", flush=True) + wend = train_endpoint_ratio(d, enc, ratio, args, dev, steps=args.wend_steps) + + # ---------------- calibration: E_mu[w] should be ~1 ---------------- + b = d.sample(4096, rng, args.beta_q, args.beta_q, "val", dev) + with torch.no_grad(): + z = enc(b["x_now"]); zf = enc(b["x_fut"]) + w = wend(z, b["a_now"], zf, b["task"]) * getattr(wend, "calib", 1.0) + pre = precompute_decision_logratio(d, enc, ratio, dev, rc=rc) + W = torch.from_numpy(chunk_logW_fast(pre, b["t_idx"], b["fut_idx"])).to(dev) + W = W.clamp(-4, 4).exp() + ess = float((w.sum() ** 2) / (w.pow(2).sum() * len(w))) + report["calibration"] = { + "calib_scale": float(getattr(wend, "calib", 1.0)), + "E_mu[W_chunk]": float(W.mean()), "E_mu[w_endpoint]": float(w.mean()), + "w_p05": float(w.quantile(0.05)), "w_p50": float(w.quantile(0.5)), + "w_p95": float(w.quantile(0.95)), "ess_frac": ess, + "corr_w_vs_W": float(np.corrcoef(w.cpu().numpy(), W.cpu().numpy())[0, 1]), + } + print(f"[gate] E_mu[w]={w.mean():.3f} (target 1.0) ESS={ess:.3f} " + f"corr(what,W)={report['calibration']['corr_w_vs_W']:.3f}", flush=True) + + # ---------------- the falsifiable gate ---------------- + # pi_synth := mu restricted to successful episodes. Its occupancy is directly + # estimable, so the IS-corrected value can be checked against a reference + # rather than merely asserted. + fb = d.sample_frames(2048, rng, "val", dev) + with torch.no_grad(): + zq = enc(fb["x"]) + q_is, ess_q = q_recursive(zq, fb["a"], fb["task"], rew=rew, flow=flow, rms=rms, + pol=pol, wend=wend, beta=args.beta_q, gamma=args.gamma, + depth=args.depth, n_particles=args.particles, + use_is=True) + q_no, _ = q_recursive(zq, fb["a"], fb["task"], rew=rew, flow=flow, rms=rms, + pol=pol, wend=wend, beta=args.beta_q, gamma=args.gamma, + depth=args.depth, n_particles=args.particles, + use_is=False) + succ = fb["succ"].cpu().numpy() + dq = float((q_is - q_no).abs().mean() / q_no.abs().mean().clamp_min(1e-6)) + report["horizon"] = effective_horizon(args.beta_q, args.gamma, args.depth) + print(f"[horizon] depth={args.depth} -> {report['horizon']['mean_hops']:.2f} hops, " + f"~{report['horizon']['effective_frames']:.0f} frames, " + f"gamma_eff={report['horizon']['gamma_effective']:.4f} " + f"(nominal {args.gamma}); truncated mass " + f"{report['horizon']['truncation_mass']:.3f}", flush=True) + report["value"] = { + "pi_mode": args.pi_mode, + "rel_shift_IS_vs_noIS": dq, + "gate_expectation": ("null: weights ~1 and rel_shift should be SMALL" + if args.pi_mode == "all" else + "signal: pi is better than mu, Q should move UP"), + "auc_success_IS": auc(q_is.cpu().numpy(), succ), + "auc_success_noIS": auc(q_no.cpu().numpy(), succ), + "q_mean_IS": float(q_is.mean()), "q_mean_noIS": float(q_no.mean()), + "ess_particles": float(ess_q.mean()), + "depth": args.depth, "beta": args.beta_q, "gamma": args.gamma, + } + print(f"[gate] pi_mode={args.pi_mode} success-AUC IS={report['value']['auc_success_IS']:.4f} " + f"noIS={report['value']['auc_success_noIS']:.4f} " + f"rel|dQ|={dq:.4f} particle ESS={float(ess_q.mean()):.3f}", flush=True) + + torch.save({"pol": pol.state_dict(), "ratio": ratio.state_dict(), + "wend": wend.state_dict(), "config": vars(args)}, out / "is_stack.pt") + (out / "report.json").write_text(json.dumps(report, indent=2)) + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/frozen/rsm_libero_rsmpi/run_slurm.sh b/frozen/rsm_libero_rsmpi/run_slurm.sh new file mode 100644 index 0000000000000000000000000000000000000000..c88879dad292987e4d35040ea227def9abb64f2d --- /dev/null +++ b/frozen/rsm_libero_rsmpi/run_slurm.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# Launch an RSM/OPE arm on MIT slurm. +# ARM=critic bash rsm_libero/run_slurm.sh +# ARM=ope bash rsm_libero/run_slurm.sh +# ARM=awr bash rsm_libero/run_slurm.sh +# QoS note: vision-pulkitag-main is off limits per standing instruction; lab-free +# has no GPU cap and reaches csail-shared-h200 (24h wall clock max there). +set -euo pipefail +ROOT=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q +PY=$ROOT/.venv/bin/python +CACHE=${CACHE:-/data/pulkitag/users/rli14/rsm_libero_cache/full} +OUTROOT=${OUTROOT:-/data/pulkitag/users/rli14/rsm_libero_runs} +ARM=${ARM:-critic} +TAG=${TAG:-$(date +%m%d)_${ARM}} +QOS=${QOS:-lab-free} +PART=${PART:-csail-shared-h200} +TIME=${TIME:-23:00:00} +MEM=${MEM:-400G} +OUT=$OUTROOT/$TAG +mkdir -p "$OUT" "$OUT/slurm" + +case "$ARM" in + critic) CMD="$PY $ROOT/rsm_libero/train_rsm.py --cache $CACHE --out $OUT \ + --steps ${STEPS:-60000} --batch ${BATCH:-512} --beta-lo 0.90 --beta-hi 0.995 \ + --beta-q ${BETAQ:-0.98} --w-actcon ${ACTCON:-0} --seed ${SEED:-0}" ;; + ope) CMD="$PY $ROOT/rsm_libero/run_ope.py --cache $CACHE --critic ${CRITIC:?set CRITIC} \ + --out $OUT --beta-q ${BETAQ:-0.98} --gamma ${GAMMA:-0.99} \ + --depth ${DEPTH:-2} --seed ${SEED:-0}" ;; + awr) CMD="$PY $ROOT/rsm_libero/awr.py --cache $CACHE --critic ${CRITIC:?set CRITIC} \ + --out $OUT --rounds ${ROUNDS:-2} --depth ${DEPTH:-2} \ + --use-is ${USE_IS:-1} --seed ${SEED:-0}" ;; + *) echo "unknown ARM=$ARM" >&2; exit 2 ;; +esac + +sbatch --job-name="rsm_$TAG" --account=vision-pulkitag --qos="$QOS" \ + --partition="$PART" --gres=gpu:1 --cpus-per-task=8 --mem="$MEM" --time="$TIME" \ + --output="$OUT/slurm/%j.out" --error="$OUT/slurm/%j.err" \ + --wrap="cd $ROOT/rsm_libero && $CMD" +echo "submitted $ARM -> $OUT"