rsm_rise code snapshot (HF_PUSH_ALL) (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+24
- frozen/rsm_libero_rsmpi/stats_full.sbatchAdded+18
- frozen/rsm_libero_rsmpi/stats_r256.sbatchAdded+18
- frozen/rsm_libero_rsmpi/subgoals_from_npz.pyAdded+24
- frozen/rsm_libero_rsmpi/sweep_horizon.pyAdded+140
- frozen/rsm_libero_rsmpi/sync_to_ibm.shAdded+75
- frozen/rsm_libero_rsmpi/test_dwm.pyAdded+262
- frozen/rsm_libero_rsmpi/test_lewm_port.pyAdded+143
- frozen/rsm_libero_rsmpi/their_ctl.sbatchAdded+16
- frozen/rsm_libero_rsmpi/their_trainer_control.pyAdded+46
- frozen/rsm_libero_rsmpi/thr_test.pyAdded+32
- frozen/rsm_libero_rsmpi/train_goal_clf.pyAdded+122
- frozen/rsm_libero_rsmpi/train_lewm.pyAdded+244
- frozen/rsm_libero_rsmpi/train_rsm.pyAdded+1312
- frozen/rsm_libero_rsmpi/train_rsm_dwm.pyAdded+765
- frozen/rsm_libero_rsmpi/train_slurm.sbatchAdded+22
- frozen/rsm_libero_rsmpi/verify_cpu.sbatchAdded+19
- frozen/rsm_libero_rsmpi/verify_full.sbatchAdded+20
- frozen/rsm_libero_rsmpi/verify_fullg.sbatchAdded+22
- frozen/rsm_libero_rsmpi/verify_successes.pyAdded+97
- frozen/rsm_libero_rsmpi/verify_successes.sbatchAdded+20
- frozen/rsm_libero_snap_20261030/.pytest_cache/README.mdAdded+8
- frozen/rsm_libero_snap_20261030/CLAUDE.mdAdded+291
- frozen/rsm_libero_snap_20261030/FINDINGS.mdAdded+344
- frozen/rsm_libero_snap_20261030/README.mdAdded+737
- frozen/rsm_libero_snap_20261030/audit_logged_goal.pyAdded+93
- frozen/rsm_libero_snap_20261030/autoresearch_driver.pyAdded+78
- frozen/rsm_libero_snap_20261030/awr.pyAdded+275
- frozen/rsm_libero_snap_20261030/bc_arm.pyAdded+168
- frozen/rsm_libero_snap_20261030/calib_dwm.pyAdded+106
- frozen/rsm_libero_snap_20261030/capture_init_feats.pyAdded+88
- frozen/rsm_libero_snap_20261030/crn_diag.pyAdded+58
- frozen/rsm_libero_snap_20261030/data.pyAdded+644
- frozen/rsm_libero_snap_20261030/df_readout.pyAdded+228
- frozen/rsm_libero_snap_20261030/dinowm_readout.pyAdded+168
- frozen/rsm_libero_snap_20261030/dwm_model.pyAdded+580
- frozen/rsm_libero_snap_20261030/dwm_readout.pyAdded+314
- frozen/rsm_libero_snap_20261030/dwm_readout_timing.pyAdded+78
- frozen/rsm_libero_snap_20261030/encode_parquet.pyAdded+83
- frozen/rsm_libero_snap_20261030/encode_t5.pyAdded+52
- frozen/rsm_libero_snap_20261030/eval_closed_loop.pyAdded+1025
- frozen/rsm_libero_snap_20261030/extract_clips.pyAdded+98
- frozen/rsm_libero_snap_20261030/extract_viz.pyAdded+90
- frozen/rsm_libero_snap_20261030/ibm_autoresearch.shAdded+53
- frozen/rsm_libero_snap_20261030/ibm_bias_diag.shAdded+16
- frozen/rsm_libero_snap_20261030/ibm_cell.shAdded+21
- frozen/rsm_libero_snap_20261030/ibm_crn_diag.shAdded+13
- frozen/rsm_libero_snap_20261030/ibm_eval.shAdded+51
- frozen/rsm_libero_snap_20261030/ibm_eval_depth.shAdded+7
- frozen/rsm_libero_snap_20261030/ibm_eval_matrix.shAdded+25
36 unmodified lines37383936 unmodified linesfrozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -textfrozen/rsm_libero_rsmpi/notes/action_contrast.pdf filter=lfs diff=lfs merge=lfs -textfrozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -text36 unmodified lines37383940414243444546474849505152535455565758596061626336 unmodified linesfrozen/rsm_libero_freeze_20261002/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -textfrozen/rsm_libero_rsmpi/notes/action_contrast.pdf filter=lfs diff=lfs merge=lfs -textfrozen/rsm_libero_rsmpi/notes/rsm_formula_comparison.pdf filter=lfs diff=lfs merge=lfs -textgen_q_rsm/docs/richard/fig/d256_lib.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/docs/richard/fig/r128_demo.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/docs/richard/fig/r256_demo.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/docs/richard/fig/r256_lib.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/docs/richard/libero10_rsm_result.pdf filter=lfs diff=lfs merge=lfs -textgen_q_rsm/docs/richard/ocbench_fair_wave_audit.pdf filter=lfs diff=lfs merge=lfs -textgen_q_rsm/docs/richard/plan_unified_rsm_rerun.pdf filter=lfs diff=lfs merge=lfs -textgen_q_rsm/docs/richard/recipe_ocbench_vs_libero10.pdf filter=lfs diff=lfs merge=lfs -textgen_q_rsm/docs/richard/rsm_recipe_comparison.pdf filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_fair_antmaze_dense_hindsight.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_fair_antmaze_sparse_hindsight.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_fair_pointmaze_dense_hindsight.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_fair_pointmaze_sparse_hindsight.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_gpu_antmaze_dense_hindsight.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_gpu_antmaze_sparse_hindsight.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_gpu_pointmaze_dense_hindsight.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_gpu_pointmaze_sparse_hindsight.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_joint.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_joint_all.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/figures/tdflow_comparison_joint_sparse.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/lewm/fig_compute_vs_perf.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/lewm/fig_cost_heatmap.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/lewm/fig_horizon.png filter=lfs diff=lfs merge=lfs -textgen_q_rsm/misc/lewm/fig_mechanism.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718#!/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 pipefailcd /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 LiberoRSMDatafor 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)PYecho "[stats] rc=$? $(date -u +%T)"123456789101112131415161718#!/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 pipefailcd /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 LiberoRSMDatafor 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)PYecho "[stats] rc=$? $(date -u +%T)"123456789101112131415161718192021222324"""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<subgoal_dir>/task{t}.npz (ep, vals, K) layout that data.py reward_mode=subgoal reads.
usage: subgoals_from_npz.py --cache <pack> --out <subgoal_dir>"""import argparse, numpy as npfrom pathlib import Pathap = 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")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""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 querybeta. 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 numberaverages the signal away: at beta=0.98 depth=1 the gap is +0.063 within 50frames of the end and ~0 beyond it, while the pooled value is +0.008."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, jsonfrom pathlib import Pathimport numpy as npimport torch
from data import LiberoRSMDatafrom is_ope import load_critic, q_recursive, effective_horizon, train_bcfrom model import BCHeadfrom 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475#!/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 notesSRC=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_liberoDST=/proj/dmfexp/zwhong/rsm_liberoCACHE_STATS=/data/pulkitag/users/rli14/rsm_libero_cache/full_demo/feat_stats.npzSSHQ=(-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 3fi
# 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 4fiecho "[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=<venv>/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 andlet LiberoRSMData refit it there -- stats must match the cache they index.NOTE123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""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 annotationsimport json, os, subprocess, sysfrom pathlib import Pathimport numpy as npimport pytestimport torch
HERE = Path(__file__).resolve().parentsys.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"] > 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""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 beASSERTED rather than assumed. These are the four things that, if wrong, would silently turn LeWMinto 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 npimport 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")12345678910111213141516#!/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.errset -uo pipefailexport PYTHONUNBUFFERED=1B=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationexport 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.pyRC=$?; echo "[ctl] rc=$RC"; exit $RC12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""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 step110000. Our pipeline plateaus near 0.042 at 120000. A 20k-step bisect showed bothpaths equal (0.0495 theirs vs 0.0471 ours), so the question is whether theirnumber is reachable at all at the full budget, or whether it came from somewhereelse. 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()1234567891011121314151617181920212223242526272829303132"""Throughput comparison. thr_all = SR*max/mean_steps_all conflates success rate withspeed; the paired steps-to-success on episodes BOTH arms solved isolates speed alone."""import json, sys, statistics as stfrom math import sqrt, erfcE="/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, dpairs=[]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=0print(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>0print(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'}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""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 itsbaselines 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/<task>/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 andfalse-positive rate (p > 0.5 on goal = 0 frames) on the val episodes. Saves <out>/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 annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, json, timefrom pathlib import Pathimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
from data import LiberoRSMDatafrom 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 <cache>/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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244#!/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 declareddeviations): JEPA next-embedding prediction with an AdaLN-zero causal predictor, collapse preventedby SIGReg alone -- no stop-gradient, no EMA target -- AdamW 5e-5 / wd 1e-3 with a global-norm clipof 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 aclass-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-phasefit (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 thereference's phase 1 produces. The probe is fitted on BOTH the encoder embedding of a real frame andthe PREDICTED embedding of the next one, because scoring applies it to predicted embeddings and aprobe fitted only on encoder outputs would be evaluated off its own training distribution -- thatmismatch 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 bestRANKS ACTIONS on held-out episodes (the true chunk against a shuffled one), not the last one.
usage: train_lewm.py --cache cache/<task> --out runs/<task>/wm/lewm [--size m] [--steps 100000]"""from __future__ import annotations
import argparseimport jsonimport os as _osimport timefrom pathlib import Path
import numpy as npimport torchimport torch.nn.functional as F
from lewm_data import StreamingFrameDatafrom 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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312"""Joint reward-latent + action-conditioned occupancy training (RSM) on LIBERO-10.
No TD target, no return regression: the occupancy target is a REAL logged futureframe drawn at k ~ Geom(1-beta), and reward enters only at read-out.
Diagnostics follow COLLAPSE_ANALYSIS: batch losses can look healthy while thecritic 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 thestate-ranking AUC."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import os as _osimport argparse, json, timefrom pathlib import Pathimport numpy as npimport torchimport torch.nn.functional as F
from model import (Encoder, RewardHead, OccFlow, ema_update)from model import mlp, IdentityEncoder, PCAEncoderfrom 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<step>.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: <cache>/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 <out>/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.") # ---- RSM-pi (rsm_rise RSMPI_RISE, 2026-11-12). OPT-IN: "" (default) = the freeze's code path, bit for bit. # Per-frame log rho_R (scripts/rsmpi/label.py). Each MC target s_{t+k} is weighted by # W = exp(clip(sum_{m>=1, m*H<=k-1} logrho[t+m*H], +-pi_logw_clip)), batch-mean 1 (rsmpi_weights.py), applied # per ROW to l_cfm and l_ac. The reward BCE is NOT weighted: the reward head is r(s), policy-free. ap.add_argument("--pi-logrho-npy", default="", help="RSM-pi: float [n_frames] log rho_R per cache row") ap.add_argument("--pi-logw-clip", type=float, default=6.0, help="RSM-pi: |log W| cap per hop") ap.add_argument("--pi-H", type=int, default=8, help="RSM-pi: decision period (env steps) of the data policy") ap.add_argument("--pi-print-every", type=int, default=500, help="RSM-pi: print the weight diagnostics every N steps") ap.add_argument("--pi-warmup", type=int, default=0, help="RSM-pi: linear LR warm-up over the first N steps AFTER the resume step (0 = off = the " "freeze). A fine-tune from a scoring blob restarts AdamW's moments cold.") 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)
# ---- RSM-pi (opt-in): per-frame log rho_R -> per-row hop weights on l_cfm / l_ac ---- pi_logrho = None if args.pi_logrho_npy: from rsmpi_weights import pi_hop_weights, load_logrho _why = [] if args.cache2: _why.append("--cache2 (mixed rows have no logrho row)") if args.action_augment > 0: _why.append("--action-augment (counterfactual rows)") if args.occupancy_target != "mc": _why.append("--occupancy-target td") if args.flow_expectile != 0.5: _why.append("--flow-expectile != 0.5") if _why: raise SystemExit(f"--pi-logrho-npy is implemented for the plain MC successor only; refusing: {_why}") pi_logrho = load_logrho(args.pi_logrho_npy, int(d.ep_to[-1])) print(f"[rsmpi] logrho {args.pi_logrho_npy}: n={len(pi_logrho)} mean={pi_logrho.mean():+.4f} " f"sd={pi_logrho.std():.4f} min={pi_logrho.min():+.3f} max={pi_logrho.max():+.3f} " f"E[rho]={np.exp(pi_logrho).mean():.4f}; H={args.pi_H} logw_clip={args.pi_logw_clip}", flush=True) _pi_acc = {}
@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") pi_w = None if pi_logrho is not None: _w, _pi_info = pi_hop_weights(pi_logrho, b["t_idx"], b["fut_idx"], b["ep"], d.ep_to, H=args.pi_H, clip=args.pi_logw_clip) pi_w = torch.from_numpy(_w).to(dev) 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 and pi_w is not None: # RSM-pi: per-row mean, then the W-weighted mean (W has batch mean 1, so W == 1 is the line below) _row = (v - (y - noise)).pow(2).mean(-1) l_cfm = (_row * pi_w).mean() _pi_info["l_cfm_unweighted"] = float(_row.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) if pi_w is not None: # RSM-pi: row i's positive and its permuted negative share row i's (x_k, k, target), so the # row weight is W_i (the target's IS weight); the negative's own chunk is not reweighted. _sp = F.softplus(e_pos - e_neg) l_ac = (_sp * pi_w).mean() _pi_info["l_ac_unweighted"] = float(_sp.mean()) else: 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)) if args.pi_warmup > 0: # RSM-pi opt-in (0 = off): ramp the LR after a cold-moment resume for _pg in opt.param_groups: _pg["lr"] = args.lr * min(1.0, (step - start_step) / args.pi_warmup) 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 pi_w is not None: for _k, _v in _pi_info.items(): _pi_acc[_k] = _pi_acc.get(_k, 0.0) + _v _pi_acc["_n"] = _pi_acc.get("_n", 0) + 1 if step % max(args.pi_print_every, 1) == 0 or step == args.steps or step == start_step + 1: _n = _pi_acc.pop("_n") print(f"[rsmpi] {step} cfm_w={float(l_cfm):.6f} cfm_unw={_pi_info.get('l_cfm_unweighted', float('nan')):.6f} " f"ac_w={float(l_ac):.6f} ac_unw={_pi_info.get('l_ac_unweighted', float('nan')):.6f} " f"wmean={float(pi_w.mean()):.6f} loss={float(loss):.6f} finite={bool(torch.isfinite(loss))} | avg over {_n}: " + " ".join(f"{_k}={_v / _n:.4f}" for _k, _v in _pi_acc.items()), flush=True) if wb is not None: _wb_log({f"rsmpi/{_k}": _v / _n for _k, _v in _pi_acc.items()}, step) _pi_acc = {} 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765"""DWM successor-model trainer: DINO-WM's ViT predictor, trained by conditional flow matchingto 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, sameckpt.pt / ckpt_best.pt / ckpt_s<step>.pt files. Multi-GPU by torchrun (DDP, one node):
torchrun --standalone --nproc_per_node 8 train_rsm_dwm.py --cache cache/<task> \ --out runs/<task>/rsm/DWM --batch 4096 --steps 100000 ...
Run without torchrun for a single process. The token cache is memory-mapped, so the 8ranks share one page-cache copy of tok.f16.npy."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, copy, datetime, json, queue, threading, timefrom pathlib import Pathimport numpy as npimport torchimport torch.distributed as distimport torch.nn.functional as F
from model import ema_updatefrom train_rsm import aucfrom 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/<task>; 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/<task>/goal.npz): a goal-STATE classifier") ap.add_argument("--goal-file", default="", help="goal.npz for --reward-mode goal (default <cache>/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 <x> 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()12345678910111213141516171819202122#!/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.errset -uo pipefailexport PYTHONUNBUFFERED=1cd /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_liberoPY=/data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/.venv/bin/pythonecho "[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 checkpointexit $RC12345678910111213141516171819#!/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.errset -uo pipefailB=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationS=/data/pulkitag/users/rli14/rlinf_recap_task_expansionexport LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard# no renderer at all -- osmesa keeps mujoco happy without a GPU or EGLexport MUJOCO_GL=osmesa PYTHONUNBUFFERED=1OUT=/data/pulkitag/users/rli14/rsm_libero_runs/verifymkdir -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.npz1234567891011121314151617181920#!/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.errset -uo pipefailB=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationS=/data/pulkitag/users/rli14/rlinf_recap_task_expansionexport LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standardexport MUJOCO_GL=osmesa PYTHONUNBUFFERED=1T=$((SLURM_ARRAY_TASK_ID / 4)); K=$((SLURM_ARRAY_TASK_ID % 4))OUT=/data/pulkitag/users/rli14/rsm_libero_runs/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}.npz12345678910111213141516171819202122#!/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.errset -uo pipefailB=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationS=/data/pulkitag/users/rli14/rlinf_recap_task_expansionexport LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standardexport MUJOCO_GL=osmesa PYTHONUNBUFFERED=1T=$((SLURM_ARRAY_TASK_ID / 4)); K=$((SLURM_ARRAY_TASK_ID % 4))OUT=/data/pulkitag/users/rli14/rsm_libero_runs/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}.npz12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""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-episodeaudit: 5/32 logged successes did not reproduce, 0/28 logged failures did). BC-on-successesclones that pool, and the critic's gamma^steps-to-success reward gives a false success afull progress curve toward an event that never happened.
This re-executes each logged action sequence from the logged initial sim_state and recordswhether the episode actually succeeds. Emits a boolean mask aligned to the cache's episodeindex, consumed via --success-mask.
Error is one-sided (no logged failure ever reproduced as a success), so verification onlyever REMOVES episodes from the success pool."""import argparse, os, re, sysimport numpy as npsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
def src_parquet(ep_src: 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()1234567891011121314151617181920#!/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.errset -uo pipefailB=/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulationS=/data/pulkitag/users/rli14/rlinf_recap_task_expansionexport LIBERO_CONFIG_PATH=$S/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standardexport MUJOCO_GL=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/verifymkdir -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.npz12345678# pytest cache directory #
This directory contains data from the pytest's cache plugin,which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
**Do not** commit this to version control.
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291# rsm_libero — LIBERO-10 RSM critic evaluation
## INVALIDATION (2026-09-13): every result before this date is void
Every run directory under `rsm_libero_runs/mit/` suffixed `_wrong_eval_env` (105 of them) andevery eval JSON under `rsm_libero_runs/eval/wrong_eval_env/` (143) was produced with the rolloutlatents and the evaluator in DIFFERENT feature spaces. Do not cite, compare against, or resumefrom them. The results tables further down in this file are retained only as a record of whatwas believed; they are superseded. Valid runs are `*_r` and later, trained on`rsm_libero_cache/full_demo_r256` (or its full-corpus successor) and evaluated at `--cam-res 256`.
## PINNED INPUT FORMAT (offline data == online environment, or the run is inadmissible)
| item | value | why ||---|---|---|| camera render | **256x256**, both cameras (`--cam-res 256`, the default) | RLinf `config/env/libero_10.yaml`; the collector rendered at 256 || orientation | raw render `[::-1, ::-1]` -> serving orientation | parquet images are stored already upright; demo hdf5 stores raw || resize | 256 -> 224 bilinear, **round and clamp to uint8** | `to224`: float input alone moves the latent 3 sigma || encoder | the latent-cache BUILDER's PaliGemma, base||wrist 2048+2048 | same module the evaluator imports || proprio | eef_pos(3) ++ ee_ori **axis-angle**(3) ++ gripper_qpos(2) | Euler was the #243 bug || demos | `libero10_demo_ogpo_cache_r256` (re-rendered from hdf5 `states` at 256) | the 128 demo cache is off-manifold under this evaluator || normalisation | `feat_stats*.npz` of the cache being trained on | eval reads `norm_pool` from the checkpoint |
**Naming and marker convention (2026-09-13).** Every dataset, cache and checkpoint carries the renderresolution it was produced at, twice: in the NAME (`_cam128`, `_cam256`; a mix is `_MIXED_..._INVALID`)and in a machine-readable marker (`RENDER.json` / `PACK.json` `cam_res`; checkpoints store `cam_res`).`eval_closed_loop.py` REFUSES a policy, critic or Q whose declared resolution differs from`--cam-res`, and refuses an undeclared one (`--allow-cam-mismatch 1` overrides; never for a reportednumber). `pack.py --cam-res` is how a cache gets its declaration.
| asset | name | cam_res ||---|---|---|| rollout latents | `pi05_lib10_ogpo_fl15_v1` (+RENDER.json) | 256 || demos, LIBERO hdf5 render | `libero10_demo_ogpo_cache_cam128` | 128 -- invalid under the 256 evaluator || demos, re-rendered | `libero10_demo_ogpo_cache_cam256` | 256 || subset cache | `rsm_libero_cache/full_demo_cam256` (`full_demo_r256` is a symlink for running jobs) | 256 || full cache | `rsm_libero_cache/full_r256` | 256 || old subset cache | `full_demo_MIXED_128demos_256rollouts_INVALID` | mixed |
Rule, extended from reward labels to features: **a latent the eval environment cannot produce isinadmissible for offline training.** Verify with `rerender_rollouts.py --validate-rollouts` /`--validate-demos` (re-render from logged state in the evaluator's env; L2 to the cached latentmust sit at the within-cloud scale, ~4-12, not 60+).
## RULE: offline data must reproduce its reward labels in the EVAL environment
**A trajectory is admissible for offline training only if replaying its logged actionsin the environment we evaluate in reproduces its reward labels. If it does notreproduce, drop the trajectory.**
This is not a data-cleaning nicety, it is a correctness condition. An offline learnerfits $(s,a,r,s')$ tuples and is then scored in the simulator. If those tuples cannot bereproduced there, they describe different dynamics than the ones the policy is gradedagainst, and the learner is being fit to an environment that does not exist. That is thestandard way offline RL silently fails.
Three consequences that are easy to get wrong:
1. **"The label was honest" is NOT the admissibility test.** Evaluating the goal predicate at an episode's own logged final state answers whether the recorder told the truth about the state it reached. Useful diagnostics, wrong question. A truthful label on a trajectory that will not reproduce here is still inadmissible.2. **The replay must run in the SAME configuration as eval** — same venv, same package versions, same renderer and device. A trajectory that reproduces on CPU/osmesa but not on the GPU/EGL path we actually evaluate on is not admissible, because the eval path is the one that defines the environment.3. **If the eval environment changes, admissibility must be recomputed.** Moving eval to a different cluster, venv or `bddl` version invalidates the existing mask. See the pinned versions below: IBM's `bddl` is 1.0.1 against MIT's 3.6.0, and `bddl` defines the goal predicates, so a mask built for MIT does not transfer.
Measured on R1 (`pi05_lib10_sde_v1`): replaying logged successes reproduces **~81%**(per task 0.620--0.938). The remaining ~19% are inadmissible and are dropped by`merge_verify.py --shards`, leaving ~1800 usable rollout successes. For contrast, thediagnostic goal-predicate check passes ~87% — the gap between the two is exactly theset of trajectories that were honestly recorded but do not reproduce, and **those areinadmissible too**.
## THE TWO EVALUATION PROTOCOLS — always report both
There are two initial-state distributions, they give materially different numbers,and **which one you use decides who wins**. Never report one without saying which.
| protocol | flag | what it does | who is at home in it ||---|---|---|---|| **A. stock LIBERO test set** | `FRESH=0` (default) | replays `bench.get_task_init_states(tid)` — the benchmark's own fixed init states | **the demos** (they were collected from these) || **B. 5 cm continuous region** | `FRESH=1` | `env.reset()` only, so the task's placement initialiser samples object poses continuously | **the rollouts** (`fresh_reset=true`, "fresh 5 cm inits") |
```bash# A: stock init statessbatch --export=ALL,POLICY=$P,NINIT=50,OUT=$E/x.json eval_slurm.sbatch# B: continuous regionsbatch --export=ALL,POLICY=$P,NINIT=50,FRESH=1,OUT=$E/x_fresh.json eval_slurm.sbatch```
### How an initial condition is actually defined
Per episode, indexed by task `tid` and episode `k` (both protocols):
```pythonpseed = 7_919_003 + policy_seed*500_009 + tid*1_013 + k # policy sampling RNGtorch.manual_seed(pseed); torch.cuda.manual_seed_all(pseed)np.random.seed(seed*100_003 + tid*1_009 + k)env.seed(seed*100_003 + tid*1_009 + k) # env RNGenv.reset() # B stops hereif not fresh: env.set_init_state(inits[k % 50]) # A overrides the reset```
**Protocol A** — `env.set_init_state()` writes one of LIBERO's 50 stored full sim-statevectors (`bench.get_task_init_states(tid)`), overwriting whatever `reset()` sampled.Object poses are therefore a deterministic replay of a fixed, finite, curated set.`NINIT=10` replays inits 0-9, which is why it is biased (see above); `NINIT=50` useseach stored state exactly once.
**Protocol B** — no override, so object poses come from the task's BDDL placementregions (`bddl_base_domain.py`: `regions[name]["ranges"]` → `UniformRandomSampler`,uniform in x/y over the task's rectangle plus a z-rotation). Under B, `NINIT=10` is asmall unbiased sample rather than a curated subset — noisy, but not systematically easy.
**MEASURED (`probe_inits.py`, 2026-09-12): protocol B is NARROWER than protocol A.**Mean std of the randomised sim-state DoF, over 50 states per task:
| protocol | mean std | note ||---|---|---|| A, stock init states | **0.0236** | wider on all 10 tasks || B, `env.reset()` | **0.0138** | 0.58x of A |
So `--fresh 1` is **not** an "expanded region" — it is a tighter one, and A is the moredemanding of the two. (`stock_inside_fresh_support = 0.00` is a consequence of A beingwider, not of a distribution shift.)
**Neither protocol reproduces the rollout corpus's init distribution.** The corpus wascollected with RLinf's `fresh_reset=true`, documented as "fresh 5 cm inits" — 0.05would be wider than both A and B. Our evaluator has no equivalent. Evaluating on thegenuine 5 cm region would require explicit jitter of object free-joint xy after reset;until that exists, the critic and the success-pool policies are under a mild initshift under BOTH protocols.
**Protocol A CANNOT be replicated by varying `SEED`.** `set_init_state` overwriteswhatever `env.reset()` sampled, so `env.seed` has no effect; `np.random.seed` is set butnever used in the rollout loop; and the policy stream is keyed on `--policy-seed`, not`--seed`. Re-running protocol A at a different `SEED` reproduces the identical 500episodes. **A is hard-capped at 500 distinct episodes** (50 stored inits x 10 tasks).Its only legitimate replication is `PSEED=1,2,...`, which resamples the policy on thosesame inits. Protocol B draws fresh placements per episode, so `SEED` gives genuine newepisodes and n scales without limit — it is the only protocol that supports replication.
**Both protocols are PAIRED across arms.** The env seed depends only on`(seed, tid, k)` and the policy seed only on `(policy_seed, tid, k)` — neither dependson which policy or critic is being evaluated. So with `SEED=0` every arm sees theidentical sequence of initial conditions and the identical policy-sampling RNG stream.Differences between arms are attributable to the arm, and variance on a *difference*is lower than the independent-sample formula implies. Never vary `SEED` between armsyou intend to compare.
### Why this is not a detail
Provenance of every component, verified 2026-09-12 from the corpus `DATASET.md` files:
| component | source | init distribution ||---|---|---|| 500 demos → BC-on-demos | `libero10_demo_ogpo_cache_srv` (official LIBERO-10 human demos) | **stock init states** || 4500 rollouts → BC-on-successes, **93% of critic training** | `pi05_lib10_ogpo_fl15_v1` ← `pi05_lib10_sde_v1` | **fresh 5 cm**, `fresh_reset=true` |
Under protocol A we evaluate on exactly the configurations the demos were collectedfrom, while the rollout corpus — which trains the critic and the success-pool policies— comes from a different, wider region. That is a structural advantage forBC-on-demos and a distribution shift against everything else. Protocol B is the onewhere the critic's training distribution matches the test distribution.
## PINNED: simulator versions, and where eval may run
**All LIBERO evaluation and the R1 rollout collection run in the SAME MIT venv**, sothey are comparable by construction. Do not change this venv without re-deriving everynumber in this file.
```venv continual_learning_for_manipulation/venvs/rlinf-libero-eval-venv (python 3.11.15)mujoco 3.8.1 robosuite 1.4.1 bddl 3.6.0 libero vendoredinstalled 2026-08-31 (corpus R1 collected 2026-09-05 with this same venv, unchanged since)collection driver: logs/09052026_pi05_lib10_collect.sh -> PYE=.../rlinf-libero-eval-venv/bin/python```
**IBM cannot run LIBERO eval, and its stack is not equivalent:**
| | MIT (eval + collection) | IBM `/proj/dmfexp/zwhong/venvs/lerobot_env` ||---|---|---|| mujoco | 3.8.1 | 3.8.1 || robosuite | **1.4.1** | **1.4.0** || bddl | **3.6.0** | **1.0.1** || libero | vendored | **absent** |
`bddl` differs by a major version and **bddl defines the goal predicates**, so a"success" computed on IBM would not be the same event. IBM is **training-only**; everyclosed-loop number must come from MIT.
**The replay divergence is NOT a version mismatch.** Collection and replay share thevenv and the versions, installed before collection and untouched since. Re-executinglogged actions reproduces only ~81% of successes because contact-rich manipulation ischaotic and the two runs differ in floating-point detail (collection on GPU nodes underEGL, replay on CPU under osmesa). This is why label correctness must be measured byevaluating the goal predicate at the LOGGED FINAL state (~87% correct) rather than byreplay (~81%) -- replay conflates label error with non-reproducibility and overstatesit by roughly 3x on the worst task.
## Other measurement traps in this directory
**`NINIT=10` is a fixed easier subset, not a sample.** Init states are selected as`inits[k % 50]`, so `n_init=10` always replays inits 0–9. Measured on one policy:**0.630 at n=100 vs 0.532 at n=500**, a +0.098 mean per-task gap on 8 of 10 tasks.It is deterministic and does not shrink with repetition. Control: a Q-filter gatefiring on 0.5% of decisions (≈ BC) returned exactly 0.630 at n=100.**Use `NINIT=50` for any number you intend to quote.** At n=100 the standard error ona *difference* is ±0.069, so sub-14-point effects are unresolvable.
**Success labels are ~16% optimistic.** A replay audit of the source corpus found 5 of32 logged successes did not actually succeed. BC-on-successes clones a pool where~1 in 6 "successes" is a failure, and the critic's `γ^steps-to-success` reward givesthose episodes a full progress curve toward a success that never happened.
**Held-out action win rate does not predict closed-loop.** `ckpt_best.pt` selects onit, but it went 0.478 → 0.784 → 0.896 across critics while closed-loop went0.496 → 0.490. A collapse to 0.363 cost only 0.046. Treat it as a broken-critic alarm,not a selection criterion.
**A silent 0% means a config mismatch**, not a bad policy — a chunk-25 flow policy runthrough the chunk-10 concat harness scores exactly 0/350. Same signature as theoriginal Euler-vs-axis-angle proprio bug.
## Results, n=500, both protocols
Protocol B column is filled as arms land; `--` = not yet run.
| arm | uses demo labels? | A: stock | B: 5 cm continuous ||---|---|---|---|| BC-on-demos | yes (pool) | **0.532** | **0.520** || BC-on-successes | no | 0.438 | -- || RSM ranking, successes proposal, N=32 | **no** | 0.416 | -- || IQL extraction (200k steps) | yes (pool) | 0.416 | -- || RSM ranking, demos proposal (best: `c1Mb`, β 0.98/0.99) | yes | **0.540** | -- || RSM ranking, successes proposal | **no** | -- | -- || AWR extraction on success pool | **no** | -- | -- |
**Measured 2026-09-12: BC-on-demos scores 0.532 (A) vs 0.520 (B) — it does NOTmemorise the stock init states.** Protocol A is not inflating the baseline; the bar isreal. The remaining reason to run B is the reverse concern: the critic and thesuccess-pool policies were trained on the continuous-region corpus, so protocol A puts*them* under mild shift.
Scoring rule (PI): using the demo *label* is a privilege that only counts if it beatsBC-on-demos. Using demo *data* without the label is unprivileged; beatingBC-on-successes there is already signal, and beating BC-on-demos is the strong claim.
### Critic ablations (protocol A, n=500, demos proposal)
| knob | result ||---|---|| **trained β band** 0.85–0.97 / **0.93–0.995** / 0.96–0.999 | 0.490 / **0.540** / 0.502 — inverted-U, optimum found || read-out β 0.95 / 0.98 / 0.99 / 0.995 | 0.524 / 0.540 / 0.540 / 0.500 — plateau 0.98–0.99 || critic steps 12k → 110k (same band) | 0.496 → 0.490 — **no effect** || best-of-N 8 → 32 | flat to harmful || confidence gate (6 thresholds, 0.5%–60% fire) | 0.488–0.532 — no regime beats BC || candidate noise (SDE 0.3) | 0.510 → 0.290 — strongly harmful || demo-chunk retrieval (+4 / +8 / retrieval-only) | 0.516 / 0.392 / 0.352 — **strongly harmful** || action chunk 10 → 16 / 24 / 32 | 0.630 → 0.49 / 0.29 / 0.25 (n=100) — strongly harmful || AWR advantage into the actor (demos pool) | 0.520 → 0.350 vs its own `w≡1` control — strongly harmful |
**The critic cannot rank off-proposal candidates.** Noise, N=32 and retrieval all fail,and retrieval fails *in proportion to how often the retrieved chunk is used*. Itsordering is calibrated only on the proposal's own distribution; outside it the rankingis actively misleading, not merely uninformative. Corollary: AWR on a pool of uniformlyexpert demos can only damage it — run advantage weighting on the **success** pool,where quality actually varies.
## Paths
```code /data/pulkitag/hamer_diffusion_policy_project/projects/gen_q/rsm_liberocache /data/pulkitag/users/rli14/rsm_libero_cache/full_demo # 5000 eps = 500 demo + 4500 rolloutruns /data/pulkitag/users/rli14/rsm_libero_runs/mitevals /data/pulkitag/users/rli14/rsm_libero_runs/evalbest critic runs/mit/critic_1M_b995/ckpt_best.pt # band 0.93-0.995, step 110kBC-demos runs/mit/A_nd/policy_r1.pt # 0.532 (A, n=500)BC-successes runs/mit/B_nd/policy_r1.pt # 0.438 (A, n=500)```
Compute: MIT slurm, `--qos=vision-pulkitag-free-cycles`. Never `vision-pulkitag-main`.`lab-free`/`csail-shared-h200` gets root-cancelled within seconds — use`vision-pulkitag-l40s,vision-pulkitag-a6000`. Training is resumable (`--resume 1`,saves optimiser state); chain with `--dependency=afterany`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344# RSM on the LIBERO-10 pi0.5 rollout corpus: findings
Branch `rsm-libero10-ope`. All closed-loop numbers: 10 tasks x 10 initial states(n=100), 520-step cap, action chunk 10 with 10 executed, seed 0, measured by`eval_closed_loop.py` after the fix described in section 2.
---
## 1. Headline
Behaviour cloning on the 500 demonstrations is the best policy in this lane, andno value-guided extraction beats it.
| arm | succ/n | SR | thr succ | thr all ||---|---|---|---|---|| **BC on demonstrations** | **63/100** | **0.630** | 1.132 | 0.874 || lane reference `bcdemos_h1024d4`, our harness | 53/100 | 0.530 | 0.946 | 0.691 || RSM Q-filter, 16 candidates | 51/100 | 0.510 | 0.951 | 0.668 || IQL + AWR (demo pool) | 50/100 | 0.500 | 0.963 | 0.658 || IQL + AWR (success pool) | 49/100 | 0.490 | 0.839 | 0.615 || BC on successful rollouts | 48/100 | 0.480 | 0.807 | 0.596 || PARL + RSM value (collapsed proposal) | 44/100 | 0.440 | - | - || RSM + AWR (demo pool) | 43/100 | 0.430 | 0.758 | 0.528 || RSM + AWR (success pool) | 41/100 | 0.410 | 0.802 | 0.513 |
Our BC also clears the published 0.584 reference: that checkpoint scores 0.530through this harness, and ours scores 0.630 under the same protocol.
Both critic arms start from the *same* 0.630 clone and move it **down**. Theadvantage signal is harmful, not merely uninformative.
---
## 2. The bug that invalidated everything before it
For most of this work every arm scored **0%**. The cause was in our evaluator, notin any policy: it converted the end-effector quaternion to **Euler angles**, whilethe latent cache stores robosuite **axis-angle**. Three of the eightproprioception dimensions were a different physical quantity at every timestep ofevery episode.
Proof, same machine and same weights, on the lane's own 0.584 policy:
| evaluator | task 5 ||---|---|| lane's `09032026_latent_head_eval.py` (axis-angle) | 5/5 || ours before the fix (Euler) | 0/5 || ours after the fix | 5/5 |
Why every existing check missed it:
* The visual latent is 4096 of 4104 input dimensions, so the three corrupted ones never moved a **cosine similarity**. Our encoder reproduces the cache at cos 0.9999 offline and 0.9903 from live frames; both stayed green throughout.* The **offline fit** is computed on cached proprio, which is correct, so held-out sampled action MSE looked healthy at 0.049.* A **bit-exact comparison of the first action chunk** passed, because it called the same helper on both sides.
Only an end-to-end control with a known-good policy exposes it. That control didnot exist in this lane before now; `eval_closed_loop.py --lane-norm` runs it.
A second, smaller deviation in the same file: `to224` returned the raw float32interpolation where the cache builder rounds to uint8, shifting the latent by upto 0.31 against a per-dim std of 0.107. Fixed, though not the cause of the 0%.
**Anything measured through this evaluator before commit `b64ebddf` says nothingabout the policy it was measuring.**
---
## 3. What the main-branch recipe gave us, and what it did not
Adopted from `ogbench_unified_rsm/RECIPE.md` and the lane's BC:
| item | effect here ||---|---|| flow-matching occupancy on residuals, per-dim RMS normalised | works; CFM val loss 0.17-0.30 || EMA target encoder, variance floor | no collapse observed (latent std min 0.10-0.41) || Fourier beta conditioning, FiLM in the successor | retained || beta band + query beta | see section 5: the band is not the lever || action-contrastive term | does not fix the action gap at any weight || concatenation flow head for the policy (their BC head) | matches their fit exactly || select on ODE-sampled MSE, not the CFM loss | correct, but see section 6 || SWA at deploy, two-tower `q_readout=lik` | **not implemented** |
Two things we added that mattered more than any recipe item:
1. **The policy must not read the critic's latent.** That encoder is trained to predict reward and discards what an action head needs. On the 264-d latent a flow policy beat a predict-the-mean baseline by 14% in action MSE with a biased gripper channel. Reading the full observation is what took arms off the floor.2. **Policy input scaling**, section 4.
---
## 4. Normalisation is worth more than any algorithm here
| policy input | SR ||---|---|| centred with DEMONSTRATION statistics | **0.630** || centred with rollout-dominated statistics | 0.430 || per-dim z-scored | 0.010 |
Centring matters because the mean feature vector has norm 51.1 against aper-frame deviation of 9.0, so 85% of the raw magnitude is a constant. *Which*frames the statistics come from matters because the rollout corpus is a differentdistribution (pi0.5 with SDE noise 0.5, about half failures). Whitening iscatastrophic because per-dim std spans 0.048 to 3.675, so it shrinks the fewinformative directions up to 34x relative to the median.
Note the sign flip against intuition: whitening *improved* the critic's action gap(-0.086 to a +0.103 peak) while destroying the policy. The critic and the policywant different input geometry, which is why they are scaled separately.
---
## 5. The critic ranks states well and actions barely at all
Held-out within-task action win rate versus reward AUC, across every intervention:
| critic | action win | reward AUC ||---|---|---|| chunk 10, w_actcon 0.5 (deployed) | 0.568 | 0.96 || w_actcon 1.0, d_z 512 | 0.532 | 0.96 || w_actcon 2.0 | 0.533 | 0.96 || inverse dynamics 1.0 | 0.445 | 0.96 || inverse dynamics 5.0 | 0.534 | 0.96 || chunk 10, hop 0.97 | 0.558 | 0.96 || chunk 10, hop 0.99 | 0.551 | 0.96 || chunk 30, hop 0.967 | 0.597 | 0.96 || chunk 100, hop 0.99 | **0.613** | 0.95 |
All peak between step 1000 and 2000 and then decay below chance. The state valueis excellent throughout; only the action channel is missing.
**The lever is the action window, not the hop.** Holding chunk at 10 and sweepingthe hop is flat (0.568 / 0.558 / 0.551). Widening the window to 100 frames is theonly thing that moves it. A 10-frame chunk does not determine enough about theoutcome on these tasks.
This is consistent with the lane's own earlier measurement: over 5 frames theexecuted action correlates with the **proprio** delta at |r| up to 0.98 but withthe **visual-latent** delta at only 0.49 (mean 0.10). A mean-pooled PaliGemmaembedding barely resolves what a short chunk does.
And the trade is strictly unfavourable, because the policy moves the other way:
| chunk | BC on demos | RSM extraction | critic win ||---|---|---|---|| 10 | **0.630** | 0.430 | 0.568 || 30 | 0.440 | 0.160 | 0.597 || 100 | 0.080 | 0.020 | 0.613 |
---
## 6. The experiment that settles it: PARL with proposal diversity
PARL ranks N=32 proposal samples by Q, keeps the argmax, and distills. Its ownprecondition is that the proposal must be diverse, because ranking N copies of oneaction cannot improve anything. Measured action std against the data's 0.421:
| proposal | action std | ratio ||---|---|---|| BC on demos, 120k steps, best-MSE checkpoint | 0.029 | 0.070 || BC on demos, 20k steps | 0.053 | 0.126 || the same, sampling temperature 1.5 | 0.103 | 0.244 || the same, sampling temperature 2.5 | 0.222 | 0.527 |
**Selecting a checkpoint by best held-out sampled MSE picks the mostmean-collapsed policy.** Our earlier Q-filter was therefore ranking 32 near-copiesof one action, which is why it returned 0.510 instead of anything informative.This is a trap for anyone reusing `train_bc`'s selection for a proposal.
Result:
| proposal diversity | PARL SR ||---|---|| 0.070 | 0.350 || 0.126 | 0.440 || 0.244 | 0.230 || 0.527 | **0.000** |
and dropping the variance penalty, so selection follows the raw value instead ofhugging the mode, makes it worse again:
| selection rule | T=1.5 | T=2.5 ||---|---|---|| Q minus 2 particle std | 0.230 | 0.000 || pure expected success | 0.130 | 0.010 |
Critic, N, distillation and evaluator are fixed across every row; the onlyvariable is how much freedom the value has to choose. A value carrying signal gets*better* with a wider candidate set. This one destroys the policy.
**Conclusion: Q responds to the action, but the direction of its response isuncorrelated with action quality.** Measured directly with`probe_perturb.py` on demonstration frames, where the logged chunk is byconstruction the good action:
| perturbation noise | mean Q | expert wins ||---|---|---|| 0 (expert chunk) | 48.749 | - || 0.05 | 48.800 | 0.489 || 0.10 | 48.674 | 0.508 || 0.20 | 48.769 | 0.508 || 0.40 | 48.962 | 0.490 || 0.80 | 49.243 | 0.483 |
The data's own action std is 0.421, so noise 0.80 destroys the action completely,and mean Q moves by 1%, with the expert winning half the comparisons at everylevel.
That alone is ambiguous: it is equally consistent with "Q ignores the action" andwith "the Monte-Carlo estimator cannot resolve the action", because q_recursivedraws fresh flow noise per call. `probe_crn.py` separates them by scoringcandidates under COMMON random numbers, which cancels the shared noise from thepaired difference:
| perturbation | paired abs dQ (CRN) | expert wins | ratio to repeat noise ||---|---|---|---|| 0.10 | 0.399 | 0.481 | 0.18 || 0.20 | 0.719 | 0.503 | 0.32 || 0.40 | 1.588 | 0.482 | 0.71 || 0.80 | 3.793 | 0.502 | 1.69 |
(repeat noise, same action under independent draws: 2.246)
So Q is **not** blind. It moves substantially when the action changes, roughlylinearly in the perturbation size, and at noise 0.8 the paired response exceedsthe estimator noise. What is missing is the SIGN: perturbing an expert action isexactly as likely to raise Q as to lower it, even at the smallest perturbation andeven with the shared noise cancelled.
The occupancy model has therefore learned an action-conditioned map whosecounterfactual gradient is meaningless. It is trained only on (state, actionactually taken, observed future); it never sees a counterfactual action with areal outcome, so off the logged action it extrapolates confidently andarbitrarily. Magnitude without direction.
This explains every downstream result coherently, and explains the PARL sweepbetter than "weak critic" does. Selection follows an arbitrary direction, so PARLeffectively picks a random member of its candidate set; the wider the set, thefurther off-support the winner, and the worse the policy -- exactly the monotonecollapse 0.440 -> 0.230 -> 0.000. AWR weights become noise that dilutes the clone.A collapsed proposal looks harmless because a random choice among 32 copies of oneaction is still that action, and it is also the only configuration that staysinside the region where the model was ever trained.
It also explains why the 0.568 offline win rate looked survivable: comparing thelogged chunk against a DIFFERENT episode's chunk is dominated by on-support versusoff-support, which the occupancy model does capture. Ranking a policy's owncandidates at the same state is a different question, and there the model hasnothing to say.
The 0.568 offline win rate did not reveal this, because ranking *dataset*alternatives is dominated by on-support versus off-support. That is a differentquestion from ranking a policy's *own* candidates, which is what every extractionmethod actually does. `probe_perturb.py` asks the right question directly: does Qprefer the expert chunk over noisy perturbations of it.
### The filtering test the corpus was collected for
One configuration tests the critic's whole reason to exist. Fit the proposal tothe WHOLE corpus, failures included, so its candidate set genuinely contains bothgood and bad behaviour, then let the value filter it. A critic that can separatesuccess-like from failure-like actions should recover demonstration-levelperformance from a proposal that on its own is poor.
| proposal | PARL SR ||---|---|| demonstrations only (diversity 0.126) | 0.440 || whole corpus incl. failures (diversity 0.132) | **0.170** |
It does not filter. Given a candidate set that by construction contains thefailure modes the critic was trained on, selection makes things worse, not better.
That run also shows candidate diversity cannot be bought with data: fitting theproposal to the whole corpus gives action std 0.056, against 0.053 fordemonstrations only. Flow matching learns the conditional mean regardless of howvaried the data behind it is. The only lever that moved diversity was samplingtemperature, and that pushes candidates off the manifold -- exactly where thevalue's response was measured to be arbitrary. On-manifold and diverse are notjointly available from a flow behaviour clone here.
---
## 7. Bugs fixed along the way
Each of these alone produced a zero or a badly wrong number.
1. Evaluator sent Euler angles where the cache holds axis-angle (section 2).2. Evaluator fed float32 pixels where the builder quantises to uint8.3. `import_file` given an absolute path: ValueError before any env was built.4. The featuriser imported from the rollout producer, which does not define it.5. `RawFeat` left on CPU once it carried a buffer.6. `offline_score` indexed an empty failure pool on a demos-only cache.7. `bc_arm` scored before saving, discarding a finished 120k-step run.8. Launchers ended with `echo`, so crashed jobs exited 0 and every `--dependency=afterok` eval ran against a checkpoint never written.9. AWR weight degeneracy: advantage std ~8 at beta 3 saturates the exponent, so the "soft" weight was a hard sign filter on a 0.568-accurate critic. Worth 0.11 (IQL 0.380 to 0.490 once the advantage is standardised).10. `q_recursive` called the extracted policy to re-draw continuation actions in latent space, which a raw-feature policy cannot answer; it now uses a separate latent-space continuation policy.
---
## 8. Where to iterate next
The blocker is specific: the latent does not carry the action, so no read-outbuilt on it can rank actions, and the horizon over which a short chunk matters istoo short to recover the signal. In rough order of expected value:
1. ~~Ask whether the ranking is inverted or absent.~~ **Answered: neither.** Q responds to the action with the right magnitude and an arbitrary sign (section 6). There is no sign to flip and no variance to average away -- common random numbers make the paired response exceed the estimator noise and the expert still wins only half the time. The defect is that the model's COUNTERFACTUAL response is untrained: it only ever sees the action that was actually taken. Everything below attacks that.2. **A latent that is action-predictive by construction.** The inverse-dynamics auxiliary tried here (`--w-invdyn`) is the weak version: it shares the encoder with a reward objective that dominates. Stronger: train the occupancy in a latent whose *only* objectives are reward AND inverse dynamics, or concatenate a proprio-history channel that already correlates with the action at 0.98.3. **The recipe's `q_readout=lik`.** The two-tower InfoNCE goal likelihood is the one main-branch item not implemented here. `GoalLikelihood` already exists in `model.py`, unused. A contrastive read-out is better calibrated than a saturating reward head and may rank where the sigmoid cannot.4. **Decouple the critic's action window from the policy's.** The measured trade-off is that the critic wants 100 frames and the policy wants 10. A model-based lookahead that scores the policy's 10-frame chunk followed by occupancy-rolled continuation would give the critic its long window without forcing the policy to emit one. This is the most promising direction and the most work; the pieces (`q_recursive`, a latent continuation policy) exist.5. **Richer features.** Mean-pooled PaliGemma is the root constraint. Patch tokens or an explicitly action-conditioned encoder would change the ceiling rather than work around it.
What is NOT worth repeating: action-contrastive weight sweeps, latent width,recursion depth, hop length, and AWR pool choice. All were measured and none movesthe action win rate off ~0.57.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737# RSM + importance-sampled OPE on the LIBERO-10 rollout corpus
Goal: learn an occupancy critic on the pi0.5 LIBERO-10 rollout corpus (43,135episodes, ~49.5% success), evaluate a target policy off-policy with theimportance-sampling correction, and distil a policy that beats behaviour cloning.
## Why this corpus and not the demos
The smolvla RSM critic was fit on demonstrations only. Its AWR extraction was anull result for a mechanical reason recorded in `rsm_vla/smolvla_rsm/README.md`:the mean absolute advantage was **0.019**, because a BC actor that imitates thedemos scores its own action the same as the demo action. Half of this corpus isfailure, so the advantage has real spread.
## Pipeline
| stage | file | what it produces ||---|---|---|| pack | `pack.py` | flat memmap cache from the per-episode npz corpus || critic | `train_rsm.py` | reward-predictive latent + action-conditioned occupancy || OPE | `is_ope.py`, `run_ope.py` | ratio nets, endpoint weight, recursive Q, gate || improvement | `awr.py` | advantage-weighted regression, looped with re-fitted ratios |
## Tricks carried over from `main` (ogbench_unified_rsm)
Taken from `RECIPE.md` and `notes/COLLAPSE_ANALYSIS.md`:
* train over a **beta band**, not one discount, with Fourier features on the log-horizon* **residual** successor, normalised per dimension by the dataset RMS of the residual* **EMA target encoder** supplies the future target, with a variance floor against latent collapse* condition on the action chunk and the task **equally**, concat plus FiLM* keep recursion **shallow** (2 hops here), and never prune mid checkpoints
Deliberately not carried over: the goal-ball arrival likelihood. LIBERO has noprivileged success ball in this latent, so the read-out is a learned rewarddecoder, which is what the image branch of `CLAUDE.md` requires anyway.
The collapse analysis' central lesson drives the diagnostics: a value that ranksSTATES but cannot rank ACTIONS shows flat batch losses and then falls off acliff in closed loop. So the headline validation metric here is the **action gap**,Q on the logged chunk minus Q on a foreign chunk at the same state, not thestate-level success AUC.
## The importance-sampling correction
The behaviour policy is a flow model sampled as an SDE at noise 0.5 and has **notractable density**, which is open question 2 in the notes. We never ask for one:
1. a classifier separates a logged chunk from a chunk sampled from the target policy at the same state, and its logit is `log pi/mu` on balanced classes;2. the chunk product runs over the interior decisions of a beta-hop only, which with a 10-action chunk is ~5 factors per hop rather than ~50;3. that product is regressed onto the endpoint under squared loss, whose minimizer is `E[W | endpoint] = d^pi_beta / d^mu_beta`, the only form usable at inference because the occupancy model emits endpoints and not actions;4. the recursive read multiplies endpoint weights along hops and self-normalises.
Decision-point ratios are prefix-summed once per ratio fit, so the chunk productis an O(1) lookup rather than one forward pass per interior decision.
## Data notes
* `task_index` is 0 in every episode of this corpus. The producer that caused it is already fixed upstream; the packer takes ids from the canonical benchmark order in `09052026_lib10_tasks.txt` and refuses to run on a task directory that is not in that list.* Failed episodes are all exactly 520 frames while successes end early, so episode length nearly determines the outcome. Any label built from "frames remaining" leaks it. The reward label is therefore defined on terminal states of successful episodes, and action ranking is the headline metric.
## Findings so far (dev cache: 2,350 episodes, 954k frames, 50% success)
### The critic learns states well and actions weakly
Reward AUC 0.99, occupancy loss 0.27 -> 0.13, state AUC 0.50 -> 0.66 over 16k steps.The pooled action win rate never left chance in eight checkpoints.
### The action-ranking metric has to use an ON-SUPPORT alternative
Comparing Q on the logged chunk against a chunk permuted across the whole batchcompares against an action from a *different task*. Once the successor isaction-conditioned that lands off-manifold, and the frozen reward decoder scoresoff-manifold latents arbitrarily -- the win rate fell to 0.361, i.e. the critic"preferred" the off-support action 2 times in 3. The same bug was latent in thesweep, whose recursion originally used an untrained continuation head.
With a within-task alternative and 8,192 pairs, the base critic ranks actionsabove chance near the goal: 0.61 mean near-terminal win, vs a cross-task controlpinned at 0.47-0.52 in all twelve cells.
### Recursion depth costs action signal; longer single hops do not
Base arm, near-terminal win pooled over four discounts:
| depth | mean win | n | 95% CI ||---|---|---|---|| 1 | 0.630 | ~4000 | [0.615, 0.645] || 2 | 0.608 | ~4000 | [0.592, 0.623] || 3 | 0.580 | ~3000 | [0.562, 0.598] |
The query action conditions only the first hop, so each extra hop hands more ofthe trajectory to the continuation policy. Meanwhile reach at depth 1 grows from25 to 200 frames as beta goes 0.96 -> 0.995 with the win rate flat at 0.61-0.64.**A single long hop dominates stacked short hops here** -- but only because theoccupancy was trained on a beta BAND covering the query horizon. Recursion earnsits place when composing *beyond* the trained band, which is not what this tested.
### The action-contrastive term: better actions, worse states, and an artifact
At weight 1.0 it reaches its own objective (contrastive loss 0.68 -> 0.39) andranks near-terminal actions better (0.667 vs 0.609 over 12,000 pairs), but stateAUC drops 0.66 -> 0.59 and the occupancy loss stalls.
It also shows a **perfect depth-parity artifact**: pooled win 0.460 / 0.617 /0.542 at depths 1 / 2 / 3, with the value gap negative at odd depth and positiveat even depth in 12 of 12 cells. The base arm is flat at 0.505 for every depth.Unexplained; not built on.
### Contrastive weight: 0.1 is free, 1.0 is destructive
| arm | w_actcon | state AUC | occupancy loss ||---|---|---|---|| base | 0 | 0.660 | 0.132 || actcon01 | 0.1 | **0.676** | 0.133 || actcon | 1.0 | 0.587 | 0.175 |
The damage at 1.0 is an over-weighting artifact, not something inherent to thecontrastive idea. The 1.0 arm is also the one carrying the unexplaineddepth-parity behaviour, so treat it as suspect.
### The importance-sampling correction FAILED its null control
Both gates use the same critic and differ only in whether the target policy isgenuinely different from the behaviour policy.
| metric | signal (pi = BC on successes) | null (pi = BC on all ~ mu) ||---|---|---|| ratio classifier accuracy | 1.000 | 0.999 || raw `E_mu[W]` (must be 1.0) | 0.181 | 0.181 || calibration factor | x5.229 | x5.238 || weight ESS | 0.563 | 0.559 || corr(endpoint w, chunk W) | 0.432 | 0.434 || relative value shift from IS | 0.1925 | 0.1842 || success AUC change | +0.0019 | -0.0054 |
Identical to within noise. The correction shifts values ~19% whether or notthere is a policy difference to correct, and never improves discrimination.
**Cause, and it is an implementation error not a property of the method:** thetarget policy was a diagonal Gaussian while the behaviour policy is a flowsampled as an SDE. The classifier reached 100% accuracy by recognising theSAMPLER, not the policy, so `log pi/mu` was a parametric-family artifact. This isopen question 2 of the notes -- a likelihood-free ratio only works if bothpolicies come from the same family, else the classifier solves the easier problem.
Note how well the signal gate looked in isolation: weights calibrated to 1.016,ESS 0.56, and the best success AUC in the run (0.6645). Without the null controlthat would have been reported as a working correction.
**Fix:** `FlowPolicy` in `model.py` -- a flow-matching target policy that matchesthe behaviour family. AWR weights the per-sample flow-matching loss in place of alog-density. The fix is confirmed only if classifier accuracy drops below 1.0 ANDthe null gate moves to `E_mu[W]` near 1 while the signal gate does not.
### The residual cause is the collection noise, not just the family
Same critic, same null gate, only the ratio estimator changes:
| configuration | classifier acc | `E_mu[W]` (must be 1.0) ||---|---|---|| Gaussian policy, no smoothing | 0.999 | 0.181 || flow policy, no smoothing | 0.98 | 0.184 || flow policy + per-dim smoothing (0.5) | 0.934 | 0.219 |
Matching the family cut classifier confidence 20x (bce 0.0035 -> 0.076) and moved`E_mu[W]` **not at all**. The corpus was collected with pi0.5 flow **SDE noise0.5** deliberately injected for exploration; any policy fit to that data withoutthe same dispersion stays distinguishable from it. Exploration noise atcollection time is exactly what makes the behaviour distribution broad, andbreadth is what makes a target policy trivially separable from it.
Across 3 critics and 2 policy families the correction consistently shifts values18-26% and consistently fails to improve what the values are for:
| critic / policy | rel value shift | success AUC with IS | without IS ||---|---|---|---|| base / gaussian, signal | 0.192 | 0.6645 | 0.6626 || base / gaussian, null | 0.184 | 0.6577 | 0.6631 || actcon / flow, signal | 0.256 | 0.5741 | 0.5768 |
### Smoothing helps the diagnostics and not the estimator
Null gate, where a correct weight must do NOTHING:
| configuration | acc | `E_mu[W]` | weight ESS | rel value shift | AUC change ||---|---|---|---|---|---|| gaussian, no smoothing | 0.999 | 0.181 | 0.559 | 0.184 | -0.005 || flow, no smoothing | 0.98 | 0.184 | - | - | - || flow + smoothing 0.5 | 0.934 | 0.219 | 0.625 | 0.219 | **+0.018** |
Smoothing did what it was meant to (acc 0.999 -> 0.934, ESS 0.559 -> 0.625) anddid not fix the estimator. The clearest tell is the **+0.018 AUC gain in the NULLgate**: a correction that improves discrimination when there is nothing tocorrect is fitting something other than the policy difference. The endpointregression also went unstable under smoothing (loss 0.11 -> 5.73 at step 3000).
**Verdict: across 3 critics x 2 policy families x 2 smoothing levels, theper-decision importance weight fails its null control every time.**
### AWR made the policy WORSE, and the mechanism is dilution
| metric | pi_0 (cloned on successes) | after 1 AWR round ||---|---|---|| flow loss on SUCCESS chunks | 0.1706 | 0.1708 || flow loss on FAILURE chunks | 0.1876 | **0.1713** || separation gap | **0.0170** | **0.00046** |
Round 2 is worse still: success loss 0.1770 (up from 0.1706), failure loss 0.1672(down from 0.1876), gap **-0.0098**. The gap declines monotonically and CROSSESZERO -- after two rounds the policy fits FAILED chunks better than successfulones. Iterating the loop does not merely fail to improve the policy, itprogressively inverts it.
The policy did not improve on successes; it got much better at fitting FAILURES.`awr_step` samples from ALL training episodes and relies on the advantage todownweight the bad ones. With an advantage this weak (the critic ranks actions at0.608 near the goal and at chance beyond one hop) that reduces to behaviourcloning on the full half-failure corpus, undoing the success filtering that madepi_0 good. It is the offline echo of this lane's own `bcall` 0.108 vs `bcdemos`0.584.
Normalised, the advantage is **not** larger than the demonstration-only baselineit was supposed to beat: 0.0160-0.0221 in probability units vs the smolvla nullresult's 0.0190. The raw printout reads 1.60-2.21 only because Q is divided by(1-gamma). **The premise that failure data would give AWR a bigger signal is notsupported by this measurement.**
**The correction is NOT what breaks the loop.** Turning it off changes nothingqualitative:
| arm | pi_0 gap | after round 1 | change ||---|---|---|---|| IS on | 0.0170 | 0.00046 | -97% || IS off | 0.0089 | 0.00111 | -87% |
Both collapse. So the loop failure and the IS failure are INDEPENDENT negatives:the weights never tracked the policy difference (they fail their null control),and separately the advantage is too weak to stop AWR diluting a success-clonedpolicy with the failure half of the corpus.
**Caveat on the AWR arms:** `awr.py` seeded numpy but not torch, so the IS-on andIS-off arms started from different policies (pi_0 gaps 0.0170 vs 0.0089). Eacharm's trajectory relative to its OWN baseline is valid; the absolute numbers arenot matched across arms. Fixed for future runs.
### FINAL: no policy-extraction win. All three AWR arms lose ground.
Separation gap between success and failure chunks (higher is better):
| arm | pi_0 | round 1 | round 2 ||---|---|---|---|| IS on, pool=all | +0.0170 | +0.00046 | **-0.0098** || IS off, pool=all | +0.0089 | +0.00111 | **-0.0082** || IS off, pool=succ (dilution control) | +0.0211 | +0.0166 | **+0.0054** |
Two of three INVERT: the policy ends up fitting FAILED chunks better thansuccessful ones. Restricting the pool slows the collapse a lot but still loses3/4 of the starting gap. **None improves on its own starting point.** Theadvantage from this critic is too weak to drive improvement even when it cannotdilute.
### FINAL: the smoothed IS pair is backwards
| gate | rel value shift | AUC with IS | AUC without ||---|---|---|---|| NULL (pi ~ mu, should do nothing) | 0.219 | 0.6675 | 0.6499 || SIGNAL (pi better, should help) | 0.247 | 0.6510 | **0.6557** |
It helps +0.018 where it should do nothing and hurts -0.005 where it shouldhelp. Inverted. That closes the question.
## Status
COMPLETE. Critic works; every off-policy result is negative. See the two FINALsections above. Raw artifacts in `results/`; runs under`/data/pulkitag/users/rli14/rsm_libero_runs/`.
## FINAL RESULTS
### The AWR loop WORKS once the action chunk spans the hop it conditions
Every failing arm conditioned the occupancy on 10 frames of action while asking itto predict a 50-frame hop, so 4/5 of the transition came from actions the criticnever saw. A model-free probe shows the action's contribution to predicting successrises monotonically with sequence length: +0.0237 (10 frames) -> +0.0627 (100).
With `--chunk 100` spanning a 100-frame hop:
| critic | pooled action win | near-terminal | state AUC ||---|---|---|---|| chunk=100, depth 2 | **0.580** [0.569,0.591] | **0.73** | 0.698 || chunk=10, depth 2 | 0.519 | 0.60 | 0.664 |
**Depth 2 beats depth 1** (0.580 vs 0.547), reversing the earlier "depth hurts"result and supporting the 2-3 hop intuition once the chunk spans the hop.
| AWR arm | pi_0 | round 1 | round 2 ||---|---|---|---|| **chunk=100, pool=succ** | **+0.0671** | **+0.0791** | **+0.0825** || chunk=10, IS on | +0.0170 | +0.00046 | -0.0098 || chunk=10, IS off | +0.0089 | +0.00111 | -0.0082 || chunk=10, pool=succ | +0.0211 | +0.0166 | +0.0054 |
Advantage is 0.068-0.080 in probability units vs the demo-only smolvla nullresult's 0.019 -- ~4x more. The original premise holds at the RIGHT granularity.
### ROOT CAUSE of every IS failure: the classifier measures NETWORK IDENTITY
Six confounds were found and removed (gaussian-vs-flow family mismatch, missingsmoothing, ratio scored over the conditioning window instead of decisions, targetpolicy at the wrong granularity, and two shape/order bugs). Overlap improved everytime -- classifier bce 0.0035 -> 0.286 -- and the weights still collapsed.
The identity control explains why. Train two BC policies on **identical data** withdifferent seeds; they are the SAME policy, so a ratio classifier must be at chance:
| comparison | classifier acc ||---|---|| two policies, same data, different seed | **0.945-0.977** || target policy vs behaviour policy | 0.941 |
Identical. The classifier detects **which network generated a sample** -- samplerartifacts and generator fingerprints -- not a density difference. Every ratio itproduced was meaningless. `E_mu[W]` sat at 0.13-0.22 in all six configurationsregardless of critic, family, smoothing or granularity, and the final clean nullgate applied a **0.537 relative value shift where zero is correct**.
**This RETRACTS the intermediate conclusion** that flow SDE noise 0.5 at collectionmade the policies too separable and that the fix was data collection. Theseparability was never between policies; less injected noise would not have helped.
**Actual cause:** discriminative density-ratio estimation does not work oncontinuous high-dimensional action chunks in this setup. It is an ESTIMATORproperty, not a data property. The notes' likelihood-free route -- classify insteadof requiring normalised densities -- is not viable here. A working correction needsa genuine likelihood ratio (tractable densities on both sides) or a correction thatdoes not route through sample classification.
### The likelihood ratio FIXES the estimator; the product length still kills it
Replacing the classifier with a genuine `pi/mu_hat` (two tractable Gaussians, onefit to the logged actions by maximum likelihood, densities evaluated AT the loggedaction so nothing has to tell samples apart):
| route | E_mu[w] | median w | ESS | null-gate value shift ||---|---|---|---|---|| classifier | 0.156 | - | 0.52 | 0.537 || **likelihood** | **1.756** | **0.974** | 0.526 | 0.607 |
The per-decision weight is now RIGHT IN THE BULK (median 0.974 vs a required 1.0);the classifier's was wrong everywhere. But the null gate still fails, and theendpoint regression needed a x10 calibration.
**Cause is arithmetic.** At `beta_q=0.99` a hop spans 100 frames = **10 policydecisions**, so W is a product of 10 factors each with p95 = 4.48. That product iscatastrophically heavy-tailed however well-calibrated each factor is.
This is precisely the variance argument in the notes, and the real case for myopicbeta: keep each hop SHORT so the product has few factors, then recurse. The tensionis now measured on both sides:
* action signal needs LONG action windows (+0.0237 at 10 frames -> +0.0627 at 100)* estimable weights need SHORT hops (1 decision per hop, not 10)
**Untested middle ground:** chunk = hop = ~25 frames, i.e. ~2.5 decisions perproduct, where the probe still shows +0.0334 action contribution (40% above the10-frame case). That is the configuration most likely to satisfy both, and it isthe obvious next experiment.
## What would come next
1. Run the loop **without** the correction: `--chunk 100 --awr-pool succ --use-is 0`. This is the only configuration that improves the policy monotonically.1b. To make IS viable, test chunk = hop = ~25 frames (~2.5 decisions per product) with `--ratio-mode likelihood`. Both requirements are measured; this is where they might overlap.2. Condition the occupancy on an action window that **spans its hop** -- the single highest-impact setting found.3. For IS, replace the classifier with a genuine likelihood ratio, or drop it.4. Closed-loop LIBERO eval is NOT run here. Nothing in this file supports a claim of beating BC on demos (0.584 +- 0.025 step-matched in the lane).
## Closed-loop results, 2026-09-10 (MIT)
### The control that was missing
The lane's own bcdemos policy, run through the lane's own evaluator on thismachine, scores **0.20 / 0.20 / 0.70 on tasks 0-2 (11/30 = 0.367)** before slurmpreempted it. The environment, EGL rendering, pi0.5 encoder, initial states andsuccess detection here are therefore sound, and any 0% is ours to fix. Two thingswere needed to get it to run: `FL15_TASKS` must name the 10 libero_10 tasks (itdefaults to a 15-task list and the head's task embedding then refuses thecheckpoint), and the evaluation-protocol freeze needs a fresh output directory.
### What actually caused the 0% across every arm
The policy was conditioned on the critic's 264-d encoder output. That encoder istrained to predict REWARD, so it keeps what separates success from failure anddiscards what an action head needs. On a trained arm the policy beat apredict-the-mean action baseline by only 14% in MSE (0.1456 vs 0.1701) with abiased gripper channel. The policy now reads the full 4104-d observation; onlythe advantage comes from the critic.
### Whitening the policy input breaks the closed loop
Four runs, one consistent pattern:
| policy input | head | steps | pooled SR ||---|---|---|---|| raw, chunk 25 | FiLM | 60k | 0.040 || **center**, chunk 10 | FiLM | 60k | **0.110** || z-score, chunk 10 | FiLM | 60k | 0.000 || z-score, chunk 10 | concat | 120k | 0.000 |
The z-scored arm had the BEST offline fit of any arm (sampled action MSE 0.0374against 0.042 for the others) and still scored 0/100. Per-dim std on this corpusspans 0.048 to 3.675, so whitening shrinks the few high-variance directions by upto 34x relative to the median and flattens the spectrum. Offline the networksimply relearns its weights; at deployment the small online-vs-cache featurisationdifference is then comparable to the signal that survives. Centering removes theuninformative common mode (mean vector norm 51.1 against a per-frame deviation of9.0) without flattening the spectrum, and is what the arms now use.
### Not the cause, established by measurement
* **Featurisation.** Our encoder reproduces the demo latent cache at cos 0.9999 offline and 0.9903 from live env frames; demo and rollout latents agree at 0.991; env obs shares the h5 orientation (pixel MAE 13.9 as-is vs 101 flipped), so the evaluator's ROT180 is right. The previously reported 0.6015 mismatch does not reproduce.* **Policy architecture.** Their concatenation head, their loader and their loss, trained here for 20k steps, reach val_mse 0.0495 -- the same as our pipeline at the same budget (0.0471). Their published 0.0032 is reachable only with their `--train-all` flag, which puts the validation demos into training.
### Bugs fixed (each alone produced a zero)
1. `import_file` given an absolute path -- ValueError before any env was built.2. The featuriser imported from the producer, which does not define it.3. `RawFeat` left on CPU once it carried a buffer.4. `offline_score` indexed an empty failure pool on a demos-only cache.5. `bc_arm` scored before saving, discarding a finished 120k-step run.6. Launchers ended with `echo`, so crashed jobs exited 0 and every `--dependency=afterok` eval ran against a checkpoint that was never written.
## Results with the FIXED evaluator (2026-09-11)
All runs: 10 tasks x 10 initial states, max 520 steps, chunk 10, executed 10.Throughput = pooled SR * max_steps / mean_steps.
| arm | succ/n | pooled SR | thr (succ) | thr (all) ||---|---|---|---|---|| reference bcdemos, **our** harness | 53/100 | 0.530 | 0.946 | 0.691 || reference bcdemos, **its own** harness | 46/100 | 0.460 | 0.888 | 0.591 || **A: BC on demos (ours)** | **58/100** | **0.580** | **1.082** | **0.794** || B: BC on successful rollouts | 47/100 | 0.470 | 0.831 | 0.591 || C: IQL critic + AWR | 38/100 | 0.380 | 0.607 | 0.443 || ablation: A with z-scored input | 1/100 | 0.010 | 0.014 | 0.010 |
The harness control (0.530 ours vs 0.460 theirs, same weights) confirms thisevaluator is equivalent to the lane's; the 0.07 spread is seed variation atn=100.
### The whitening ablation is now clean
A trained on demonstrations, center-scaled, scores 0.580. The identical run withper-dim z-scored input scores 0.010. Same data, same head, same budget, sameseed -- only the input scaling differs. Whitening flattens a spectrum whoseper-dim std spans 0.048 to 3.675, shrinking the informative high-variancedirections by up to 34x relative to the median.
### AWR currently HURTS
C starts from a BC-on-successes clone (0.470) and IQL-weighted AWR takes it to0.380. Both critic arms initialised on successes alone, which starts them 0.11below the BC-on-demos bar they must clear. `--init-pool demos_succ` now lets botharms start from demonstrations plus successful rollouts, so the comparisonmeasures the critic rather than the initialisation.
## Matched four-arm comparison (2026-09-11, demonstration statistics)
Every arm: full_demo cache, demo-pool feature statistics, center scaling, theconcatenation flow head, chunk 10, batch 1024, 120k steps, seed 0. The criticarms start from the SAME behaviour clone as arm A, so the comparison isolates theimprovement signal.
| arm | succ/n | SR | thr succ / all ||---|---|---|---|| **A: BC on demonstrations** | **63/100** | **0.630** | 1.183 / 0.788 || B: BC on successful rollouts | 48/100 | 0.480 | 0.807 / 0.596 || C: IQL critic + AWR (soft) | 49/100 | 0.490 | 0.839 / 0.615 || D: RSM critic + AWR (soft, pessimism 2.0) | running | | |
Reference: the lane's own bcdemos policy scores 0.530 through this harness and0.460 through its own.
### Two normalisation findings worth keeping
| policy input | SR ||---|---|| centred with DEMONSTRATION statistics | 0.630 || centred with rollout-dominated statistics | 0.430 || per-dim z-scored | 0.010 |
Centring matters (the mean feature vector has norm 51.1 against a per-framedeviation of 9.0), WHICH frames the statistics come from matters (the rolloutcorpus is a noisier, half-failing distribution), and whitening is catastrophic(per-dim std spans 0.048 to 3.675, so it shrinks the informative directions up to34x relative to the median).
## The critic is the blocker, and it is upstream of the flow
Held-out within-task action win rate -- how often Q ranks the action actuallytaken above another action from the same task -- across every intervention tried:
| critic | best win rate ||---|---|| chunk 10, w_actcon 0.5 (the one deployed) | 0.568 || w_actcon 1.0, d_z 512 | 0.532 || w_actcon 2.0 | 0.533 || inverse dynamics 1.0 | 0.445 || inverse dynamics 5.0 | 0.534 || deployed critic + pessimism 2.0 (probe) | 0.570 |
All peak between step 1000 and 2000 and then decay below chance while reward AUCstays above 0.95. The state value is excellent and the action ranking is nearcoin-flip.
The cause is upstream of the occupancy model. This lane measured that over 5frames the executed action correlates with the proprio delta at |r| up to 0.98but with the visual-latent delta at only 0.49 (mean 0.10): a mean-pooledPaliGemma embedding barely resolves the motion a 10-frame chunk produces. Raisingthe action-contrastive weight asks the flow to use information the latent doesnot carry, which is why 2.0 was worse than 0.5.
### Every downstream use of that critic fails
| use | from | to ||---|---|---|| AWR, hard weight (IQL) | 0.470 | 0.380 || AWR, hard weight (RSM) round 1 | 0.470 | 0.400 || AWR, hard weight (RSM) round 2 | 0.470 | 0.290 || AWR, soft weight (IQL) | 0.630 | 0.490 || Q-filter, 16 candidates (RSM) | 0.630 | 0.510 |
The hard-weight collapse was a real bug and is fixed: with advantage std ~8 andbeta 3 the exponent saturates, so the "soft" weight became a hard filter on thesign of a 0.568-accurate critic. Standardising the advantage recovers most of theloss (IQL 0.380 -> 0.490) but does not turn a coin-flip critic into animprovement.
## Where RSM stands (2026-09-11)
Matched: full_demo cache, demo statistics, center scaling, concatenation flowhead, chunk 10, batch 1024, 120k steps, seed 0. C and D start from the SAMEdemonstration clone as A.
| arm | succ/n | SR | thr succ / all ||---|---|---|---|| **A: BC on demonstrations** | **63/100** | **0.630** | 1.183 / 0.788 || C: IQL + AWR (soft, pool = successes) | 49/100 | 0.490 | 0.839 / 0.615 || B: BC on successful rollouts | 48/100 | 0.480 | 0.807 / 0.596 || RSM Q-filter, 16 candidates, on A | 51/100 | 0.510 | - || D: RSM + AWR (soft, pessimism 2.0, pool = successes) | 41/100 | 0.410 | 0.802 / 0.513 |
**RSM does not yet beat the baselines.** Both critic arms move the policy DOWNfrom the 0.630 clone they start at, and RSM moves it further down than IQL.
Chunk 100 was tried because it is the only setting where the critic ranks actionswell (win 0.613 against 0.568 at chunk 10, confirming that over a 10-frame hop theaction barely moves the success probability). It does not rescue the result: BC atchunk 100 fits far worse (sampled action MSE 0.114 against 0.049) and scores0.00-0.20 per task over the first six, so the better critic sits on top of a muchweaker policy.
### What would have to change
The critic ranks actions at 0.57 and that ceiling survived every intervention:action-contrastive weight 0.5/1.0/2.0, latent width 512, inverse dynamics 1.0/5.0,particle pessimism, and chunk/hop length. Reward AUC stays above 0.95 throughout,so the state value is strong and only the ACTION channel is missing. The measuredcause is upstream: over 5 frames the executed action correlates with the propriodelta at |r| up to 0.98 but with the visual latent delta at only 0.49 (mean 0.10).Until the latent carries the action, no read-out on top of it can rank actions,and every consumer of that ranking -- AWR in two flavours, Q-filtering -- lowers agood policy instead of raising it.
## FINAL: all arms, fixed evaluator (2026-09-11)
10 tasks x 10 initial states, 520-step cap, chunk 10 executed 10. Every arm usesthe same cache, demonstration statistics, center scaling, concatenation flow head,batch 1024, 120k steps, seed 0. Both critic arms start from the SAME demonstrationclone as arm A, so the only difference is the improvement signal.
| arm | succ/n | SR | thr succ | thr all ||---|---|---|---|---|| **A: BC on demonstrations** | **63/100** | **0.630** | 1.132 | 0.874 || reference bcdemos, our harness | 53/100 | 0.530 | 0.946 | 0.691 || RSM Q-filter, 16 candidates | 51/100 | 0.510 | 0.951 | 0.668 || C: IQL + AWR (demo pool) | 50/100 | 0.500 | 0.963 | 0.658 || C: IQL + AWR (success pool) | 49/100 | 0.490 | 0.839 | 0.615 || B: BC on successful rollouts | 48/100 | 0.480 | 0.807 | 0.596 || D: RSM + AWR (demo pool) | 43/100 | 0.430 | 0.758 | 0.528 || D: RSM + AWR (success pool) | 41/100 | 0.410 | 0.802 | 0.513 |
**The RSM recipe does not beat BC-on-demonstrations, BC-on-successes, or IQLextraction on this dataset.** Behaviour cloning on the 500 demonstrations winsoutright, and it also beats the published reference through the same harness.
### The search that was run
Critic: action-contrastive weight 0.5 / 1.0 / 2.0; latent width 256 / 512;inverse dynamics 1.0 / 5.0; chunk and hop 10 / 100; particle pessimism 0 to 4.Extraction: AWR with hard and standardised weights, over the all / success /demonstration pools, with and without the importance-sampling correction, one andtwo rounds, plus deployment-time Q-filtering over 4 and 16 candidates.
### The single blocker
Held-out within-task action win rate never exceeds 0.57 at chunk 10 (0.613 atchunk 100), while reward AUC stays above 0.95. The state value is strong; theaction channel is missing, and it is missing upstream of the occupancy model: over5 frames the executed action correlates with the proprio delta at |r| up to 0.98but with the visual-latent delta at only 0.49 (mean 0.10). A mean-pooled PaliGemmaembedding does not resolve what a 10-frame chunk does. Every consumer of thatranking therefore lowers a good policy rather than raising it.
The chunk-100 result is the constructive part: lengthening the action window andthe hop is the one intervention that moved the win rate (0.568 -> 0.613), whichsays the horizon, not the read-out, is what starves the signal. Making thatusable needs a policy that is still accurate at a 100-frame chunk; ours loses moreto the longer chunk (sampled action MSE 0.114 vs 0.049) than the critic gains.
### The ceiling is the ACTION WINDOW, not the hop
Held-out within-task action win rate, chunk 10 held fixed while the hop varies:
| chunk | hop (beta_q) | best win ||---|---|---|| 10 | 0.90 (~10 frames) | 0.568 || 10 | 0.97 (~33 frames) | 0.558 || 10 | 0.99 (~100 frames) | 0.551 || 100 | 0.99 (~100 frames) | **0.613** |
Lengthening the hop does nothing; lengthening the ACTION WINDOW is what moves it.A 10-frame chunk simply does not determine much about the future on this task, sothe ranking ceiling at chunk 10 is a property of the data rather than a modellingfailure. And the policy trades the other way: a chunk-100 policy loses more to thelonger chunk (sampled action MSE 0.114 against 0.049) than the critic gains.
With this featurisation you can have an accurate policy or a discriminativecritic, not both. That is the finding, and it is what any future attempt on thiscorpus has to break.
## PARL with the RSM value, and the experiment that settles it
PARL: sample N=32 action chunks from a proposal policy, rank by the RSM Q, keepthe argmax, distill into a fresh head. The recipe's own precondition is that theproposal's samples must be DIVERSE, because ranking N copies of one action cannotimprove anything. Measured proposal action std against the data's 0.421:
| proposal | action std | ratio ||---|---|---|| BC on demos, 120k steps, best-MSE checkpoint | 0.029 | 0.070 || BC on demos, 20k steps | 0.053 | 0.126 || the same, sampling temperature 1.5 | 0.103 | 0.244 || the same, sampling temperature 2.5 | 0.222 | 0.527 |
Selecting a checkpoint by best held-out sampled reconstruction MSE picks the mostmean-collapsed one, so the earlier Q-filter run was ranking near-identicalcandidates. That is fixed above.
### The result
| proposal diversity | PARL SR ||---|---|| 0.070 (120k clone) | 0.350 || 0.126 | 0.440 || 0.244 | 0.230 || 0.527 | **0.000** |
Success falls monotonically as the critic is given more freedom to choose. Everyother factor is fixed: same critic, same N, same distillation, same evaluator.The only variable is how different the candidates are. If the value functioncarried signal, widening the candidate set would help; it destroys the policyinstead, so the ranking is not weak, it is pointed the wrong way. A collapsedproposal scores near BC simply because selection can do little harm when all 32candidates are the same action.
This is the cleanest isolation of the critic in this lane, and it agrees with theoffline probe: held-out within-task action win rate 0.568, barely above chance,while reward AUC stays above 0.95.
Chunk 30 closes the last alternative: BC 0.440, RSM + AWR 0.160, with a criticthat ranks at 0.597. Across all three action windows the same pattern holds.
| chunk | BC on demos | RSM extraction | critic win rate ||---|---|---|---|| 10 | 0.630 | 0.430 | 0.568 || 30 | 0.440 | 0.160 | 0.597 || 100 | 0.080 | 0.020 | 0.613 |
A better-ranking critic goes with a worse policy at every size, and the product isworse than plain behaviour cloning in all three.
### PARL grid: both knobs point the same way
| selection rule | T=1.5 (diversity 0.244) | T=2.5 (diversity 0.527) ||---|---|---|| Q minus 2 particle std | 0.230 | 0.000 || pure expected success | 0.130 | 0.010 |
Two independent controls, same conclusion. Giving the value more candidates tochoose among makes it worse, and removing the variance penalty -- so thatselection follows the raw value rather than staying near the mode -- makes itworse again. The penalty was masking the problem by keeping choices close to theproposal's mode, not by adding information.
The RSM value's preference over actions is anti-correlated with action quality onthis corpus. That is a stronger and more useful statement than "the critic isweak", and it is what the offline probe was too blunt to show: a 0.568 win rateagainst dataset alternatives is dominated by on-support versus off-support, whichsays nothing about ranking a policy's own candidates.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Is the label wrong, or did the replay diverge? These are different claims.
Replaying logged actions tests reproducibility; the corpus is documented as NOTbit-reproducible, so a replay failure does not by itself prove the label is wrong.
This does the direct test instead and needs no replay: load the episode's LOGGED FINALsim_state, restore the simulator to it, and evaluate LIBERO's own goal predicate.If the predicate is false in the very state the episode ended in, while is_success=1,the label is wrong -- no nondeterminism can explain it.
Per-conjunct results are also recorded, which measures how much of a compound task a"successful" episode actually completed."""import argparse, io, os, re, sys, base64import numpy as npsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
def src_parquet(ep_src): m = PAT.search(str(ep_src)) if not m: return None t, b, i, idx = m.groups() p = (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") return p if os.path.exists(p) else None
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True); ap.add_argument("--task", type=int, required=True) ap.add_argument("--out", required=True); ap.add_argument("--limit", type=int, default=0) ap.add_argument("--save-img", type=int, default=12, help="keep this many final frames of label errors") args = ap.parse_args()
import pyarrow.parquet as pq from libero.libero import benchmark, get_libero_path from libero.libero.envs.env_wrapper import ControlEnv from pathlib import Path
m = np.load(f"{args.cache}/meta.npz", allow_pickle=True) d, s, task = m["ep_demo"].astype(bool), m["ep_success"].astype(bool), m["ep_task"] todo = np.where((task == args.task) & s & ~d)[0] if args.limit: todo = todo[:args.limit]
bench = benchmark.get_benchmark_dict()["libero_10"]() t = bench.get_task(args.task) env = ControlEnv(bddl_file_name=str(Path(get_libero_path("bddl_files")) / t.problem_folder / t.bddl_file), has_renderer=False, has_offscreen_renderer=False, use_camera_obs=False) env.reset() goal = env.env.parsed_problem["goal_state"] print(f"[audit] task {args.task}: {len(todo)} logged successes, goal={goal}", flush=True)
rows, imgs = [], [] for n, e in enumerate(todo): p = src_parquet(m["ep_src"][e]) if p is None: rows.append((int(e), -1, -1, 0)); continue tb = pq.read_table(p, columns=["sim_state", "is_success", "image"]) last = tb.num_rows - 1 st = np.asarray(tb["sim_state"][last].as_py(), np.float64) env.env.sim.set_state_from_flattened(st) env.env.sim.forward() conj = [bool(env.env._eval_predicate(g)) for g in goal] ok = all(conj) rows.append((int(e), int(ok), int(sum(conj)), len(conj))) if not ok and len(imgs) < args.save_img: imgs.append((int(e), int(sum(conj)), len(conj), base64.b64encode(tb["image"][last].as_py()["bytes"]).decode())) if (n + 1) % 50 == 0: g = [r for r in rows if r[1] >= 0] print(f"[audit] {n+1}/{len(todo)} goal-holds-at-logged-end " f"{sum(r[1] for r in g)}/{len(g)}", flush=True) env.close() a = np.array([r for r in rows if r[1] >= 0]) np.savez_compressed(args.out, rows=np.array(rows), task=args.task, imgs=np.array([i[3] for i in imgs], dtype=object), img_ep=np.array([i[0] for i in imgs]), img_sat=np.array([[i[1], i[2]] for i in imgs])) if len(a): holds = int(a[:, 1].sum()); tot = len(a) print(f"[audit] task {args.task}: goal predicate TRUE at the logged final state " f"for {holds}/{tot} ({holds/tot:.3f}) of logged successes", flush=True) bad = a[a[:, 1] == 0] if len(bad): print(f"[audit] of the {len(bad)} label errors, conjuncts satisfied: " f"{np.bincount(bad[:, 2], minlength=int(a[0,3])+1).tolist()} " f"(index = #subgoals met of {int(a[0,3])})", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Autoresearch driver: reads the local JSON mirror, advances stages, launches the nextcells via ibm_autoresearch.sh. Idempotent (state in a JSON file); run it repeatedly."""import json, os, subprocess, sys, globsys.argv = ["x"]; sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import ibm_table as TD = "/data/pulkitag/scratch/rli14/ibm_eval_json"; ST = "/data/pulkitag/scratch/rli14/autoresearch_state.json"IB = "/proj/dmfexp/zwhong/rsm_libero"; R = f"{IB}/runs/full_r256"st = json.load(open(ST)) if os.path.exists(ST) else {}def save(): json.dump(st, open(ST, "w"), indent=1)def run(*a): return subprocess.run(["./ibm_autoresearch.sh", *a], capture_output=True, text=True, timeout=1800).stdoutcells = T.load(D)V = {k[0]: v for k, v in cells.items() if k[1] == "DL" and k[4] == "V"}plain = V.get("plain")def vs_plain(arm): if arm not in V or plain is None: return None r = T.pair(V[arm], plain); return rprint(f"V cells: {len(V)} plain={plain['sr'] if plain else None}")for arm in sorted(V): r = vs_plain(arm); print(f" {arm:22} SR {V[arm]['sr']:.3f} thr {V[arm]['thr']:.3f}" + (f" dSR {r['dsr']:+.3f} p={r['p']:.2f}" if r else ""))# ---- stage 1 -> stage 2s1 = [f"RSMb{b}d{d}{pp}" for b in (90, 95, 98) for d in (1, 2, 3) for pp in ("", "p256")]if "stage2" not in st and all(a in V for a in s1) and plain: best = max(s1, key=lambda a: (V[a]["sr"], V[a]["thr"])) b, d = best[4:6], best[7]; pp = "256" if best.endswith("p256") else "16" # RSMb<bb>d<d>[p256] print(f"stage1 complete -> best {best}; launching stage2 at {pp} particles"); os.environ["QFPART"] = pp; print(run("stage2", b, d)) st["stage2"] = {"beta": b, "depth": d, "part": pp}; save()# ---- BC checkpoint selectionif "bcsel" not in st: out = subprocess.run(["ssh", "-o", "BatchMode=yes", "bluevela", f"ls {R}/BCdemo_c/policy_s120000.pt 2>/dev/null"], capture_output=True, text=True, timeout=120).stdout if "policy_s120000" in out: print("BCdemo_c finished -> launching bcsel"); print(run("bcsel")); st["bcsel"] = 1; save()# ---- critic checkpoint selection on V for each finished critic run, then confirm the arg-max on A/BCB = f"{R}/qsg_f/ckpt_best.pt"; HOP = f"{R}/HOPdemo_f/policy_r1.pt"b2, d2 = (st["stage2"]["beta"], st["stage2"]["depth"]) if "stage2" in st else ("95", "3")for crun in ("qsg_bce", "qind_bce", "qsoft_f", "qsg_b90", "qsg_wide"): key = f"critsel_{crun}" if key not in st: done = subprocess.run(["ssh", "-o", "BatchMode=yes", "bluevela", f"grep -q '^\\[rsm\\] DONE' {R}/logs/{crun}.out && ls {R}/{crun}/ckpt_s*.pt 2>/dev/null | wc -l"], capture_output=True, text=True, timeout=120).stdout.strip() if done and done != "0": print(f"{crun} finished ({done} periodic ckpts) -> critsel on V"); print(run("critsel", crun, b2, d2)) st[key] = {"n": int(done)}; save() elif "confirmed" not in st[key]: arms = sorted([a for a in V if a.startswith(f"RSMc{crun}S")], key=lambda a: -V[a]["sr"]) if len(arms) >= st[key]["n"] and arms: step = arms[0][len(f"RSMc{crun}S"):] print(f"{crun}: V arg-max checkpoint = step {step} (SR {V[arms[0]]['sr']:.3f}); confirming on A/B x 3 seeds") env = f"CRITIC={R}/{crun}/ckpt_s{step}.pt, SELECT=argmaxq, HOPPOL={HOP}, QFDEPTH={d2}, QFBETA=0.{b2}, QFILTER=8, QFPES=0, QFGATE=0, QFCRN=1, QFPART=16" print(run("stage3", f"RSMc{crun}", env, "DL", f"{R}/BCdemo_f/policy_last.pt")) st[key]["confirmed"] = step; save()# ---- stage 2 -> stage 3if "stage2" in st and "stage3" not in st: b, d = st["stage2"]["beta"], st["stage2"]["depth"] s2 = [f"RSMb{b}d{d}{x}" for x in ("n32", "n16", "q90", "q90n32", "near4", "fold", "pes1", "nocrn", "cL")] + [f"RSMb{b}d{d}" + ("p256" if st["stage2"].get("part") == "256" else "")] pc = sorted([a for a in V if a.startswith("plainC")], key=lambda a: -V[a]["sr"]) if all(a in V for a in s2) and (("bcsel" in st and pc and len(pc) >= 12) or plain): top = sorted(s2, key=lambda a: -(V[a]["sr"] + 0.1 * V[a]["thr"]))[:2] bc_ckpt = f"{R}/BCdemo_c/policy_s{pc[0][6:]}.pt" if pc else f"{R}/BCdemo_f/policy_last.pt" prop = "DC" if pc else "DL" print(f"stage2 complete -> confirming {top} on A/B x3 seeds against BC ckpt {bc_ckpt}") CB = f"{R}/qsg_f/ckpt_best.pt"; HOP = f"{R}/HOPdemo_f/policy_r1.pt" pp = st["stage2"].get("part", "256") def env_for(a): x = a[len(f"RSMb{b}d{d}"):].replace("p256", "") e = f"CRITIC={CB}, HOPPOL={HOP}, QFDEPTH={d}, QFBETA=0.{b}, QFGATE=0, QFCRN=1, QFPART={pp}, QFPES=0, QFILTER=8, SELECT=argmaxq" if x == "n32": e = e.replace("QFILTER=8", "QFILTER=32") if x == "n16": e = e.replace("QFILTER=8", "QFILTER=16") if x == "q90": e = e.replace("SELECT=argmaxq", "SELECT=quantile, SELQ=0.9") if x == "q90n32": e = e.replace("SELECT=argmaxq", "SELECT=quantile, SELQ=0.9").replace("QFILTER=8", "QFILTER=32") if x == "near4": e = e.replace("SELECT=argmaxq", "SELECT=qnear, QNEARK=4") if x == "fold": e += ", QFMODE=fold" if x == "pes1": e = e.replace("QFPES=0", "QFPES=1") if x == "nocrn": e = e.replace("QFCRN=1", "QFCRN=0") if x == "cL": e = e.replace(CB, f"{R}/qsg_f/ckpt.pt") return e for a in top: print(run("stage3", a, env_for(a), prop, bc_ckpt)) print(run("stage3", "plain", "QFILTER=0", prop, bc_ckpt)) print(run("stage3", "medoid8", "SELECT=medoid, QFILTER=8, QFDEPTH=1, QFBETA=0.98, QFPES=0, QFGATE=0", prop, bc_ckpt)) st["stage3"] = {"arms": top, "bc_ckpt": bc_ckpt}; save()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""Policy improvement by advantage-weighted regression on the IS-corrected Q,and the evaluation <-> improvement loop.
A(z,A) = Q^pi(z,A) - V(z), V(z) = mean over M chunks drawn from pi itself loss = -E[ w * log pi(A_data | z) ], w = clip(exp(beta*A), 0, w_max)
Why this can carry signal where the smolvla run's could not: that critic was fiton demonstrations only, so Q(demo action) ~= Q(actor's own action) and the meanabsolute advantage was 0.019 -- no gradient. Here half the corpus is failure, sothe advantage has real spread, and the weights are additionally corrected towardpi by the endpoint ratio rather than left at the behaviour policy's value.
The loop is deliberately short (2-3 rounds). Each round re-fits the ratio nets,because the target policy has moved and a stale ratio silently evaluates thewrong policy -- the notes flag exactly this."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, jsonfrom pathlib import Pathimport numpy as npimport torch
from model import BCHead, FlowPolicyfrom data import LiberoRSMDatafrom is_ope import ( policy_features, load_critic, train_bc, train_ratio, train_endpoint_ratio, q_recursive, make_policy, policy_nll)from train_rsm import auc
def awr_step(d, enc, pol, *, rew, flow, rms, wend, args, device, steps, M=4, pfeat=None, d_policy=None, cont_pol=None): """One improvement round. Returns a NEW policy; `pol` is left untouched.
`awr_pool` controls which episodes the regression draws from. Standard AWR uses ALL data and relies on the advantage to downweight bad actions. Measured consequence when the advantage is weak: pi_0 was cloned on SUCCESSES, one AWR round over all data collapsed its success-vs-failure separation from 0.0170 to 0.00046, and the loss on FAILED chunks improved from 0.1876 to 0.1713 -- i.e. it walked the policy back toward cloning the full half-failure corpus. That is the offline echo of this lane's own bcall=0.108 vs bcdemos=0.584. `awr_pool=succ` restricts the pool so AWR can only sharpen within the slice pi_0 was fit on, which isolates dilution from genuine improvement.""" pf = enc if pfeat is None else pfeat # q_recursive rolls hops through the occupancy model and must re-draw a # continuation action at each hop CONDITIONED ON THE PREDICTED LATENT z'. # Once the extracted policy reads raw 4104-d observations it cannot be # queried there -- there is no observation for a latent the flow imagined. # `cont_pol` is a small BC policy living in the critic's latent space used # only inside the recursion; the policy AWR actually improves is `new`. roll = cont_pol if cont_pol is not None else pol new = make_policy(args, d, device, d_z=d_policy) new.load_state_dict(pol.state_dict()) opt = torch.optim.AdamW(new.parameters(), lr=1e-4, weight_decay=0.01) rng = np.random.default_rng(args.seed + 11) stats = [] _ap = getattr(args, "awr_pool", "all") for step in range(1, steps + 1): b = d.sample_frames(args.batch, rng, "train", device) if _ap != "all": keep = (b["succ"] > 0.5) if _ap == "succ" else (b["demo"] > 0.5) if keep.sum() < 8: continue b = {k: (v[keep.cpu().numpy()] if isinstance(v, np.ndarray) else (v[keep] if torch.is_tensor(v) else v)) for k, v in b.items()} with torch.no_grad(): z = enc(b["x"]) # critic latent -> advantage zp = pf(b["x"]) # policy features -> action head q_data, _ = q_recursive(z, b["a"], b["task"], rew=rew, flow=flow, rms=rms, pol=roll, wend=wend, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=args.use_is, pessimism=args.q_pessimism) # V(z) = Monte-Carlo baseline over the policy's own chunks v = torch.zeros_like(q_data) for _ in range(M): a_pi = new.sample(zp, b["task"]) qi, _ = q_recursive(z, a_pi, b["task"], rew=rew, flow=flow, rms=rms, pol=roll, wend=wend, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=args.use_is, pessimism=args.q_pessimism) v += qi v /= M adv = q_data - v # Standardise the advantage before exponentiating. Measured on this # corpus the raw advantage has std ~8, so at beta=3 the exponent is # ~24 per standard deviation: every positive sample saturates the # clip and every negative one underflows to zero. The "soft" weight # degenerates into a hard sign filter that throws away half the data # and hands the decision entirely to the critic's sign -- whose # held-out action win rate is only 0.568. That is why AWR moved the # IQL arm from 0.470 down to 0.380. Standardising makes beta mean # what it is supposed to mean: weights span exp(+-beta) per sigma. if args.adv_norm == "std": adv = (adv - adv.mean()) / adv.std().clamp_min(1e-6) w = (args.awr_beta * adv).exp().clamp(0, args.w_max) w = w / w.mean().clamp_min(1e-6) # AWR on a flow policy weights the PER-SAMPLE flow-matching loss, since # a flow head has no tractable log-density. loss = (w * policy_nll(new, zp, b["task"], b["a"], reduce=False)).mean() opt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_(new.parameters(), 1.0); opt.step() if step % 500 == 0: rec = {"step": step, "loss": float(loss), "mean_abs_adv": float(adv.abs().mean()), "adv_std": float(adv.std()), "w_max_batch": float(w.max())} stats.append(rec) print(f"[awr] {step} loss={rec['loss']:.3f} |adv|={rec['mean_abs_adv']:.4f} " f"adv_std={rec['adv_std']:.4f} w_max={rec['w_max_batch']:.2f}", flush=True) new.eval() return new, stats
@torch.no_grad()def offline_score(d, enc, pol, rng, device, n=4096, pfeat=None): """Offline proxies, reported together and never individually as a win: bc_nll_succ : negative log-likelihood of SUCCESSFUL logged chunks act_gap : how much more likely a success chunk is than a failure chunk Neither is closed-loop success; they are screens, not the result.""" ok = np.array([e for e in d.val_eps if d.ep_success[e]], dtype=np.int64) bad = np.array([e for e in d.val_eps if not d.ep_success[e]], dtype=np.int64) def nll(pool): # A demonstrations-only cache has no failures at all, so this pool is # empty; report nan rather than indexing with an empty float array. if len(pool) == 0: return float("nan") w = d.ep_len[pool].astype(np.float64); w /= w.sum() e = rng.choice(pool, size=n, p=w) lo, hi = d.ep_from[e], d.ep_to[e] t = lo + (rng.random(n) * (hi - lo)).astype(np.int64) x = torch.from_numpy(d._feat(t)).to(device) a = torch.from_numpy(d._chunk_at(t, e)).to(device) tk = torch.from_numpy(d.ep_task[e]).long().to(device) return float(policy_nll(pol, (enc if pfeat is None else pfeat)(x), tk, a)) s, f = nll(ok), nll(bad) return {"bc_nll_success": s, "bc_nll_failure": f, "act_gap": f - s}
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--norm-pool", default="all", choices=["all", "demos"], help="frames the feature statistics come from. demos is worth +0.15 closed-loop over rollout-dominated statistics.")
ap.add_argument("--q-pessimism", type=float, default=2.0, help="subtract this many particle standard deviations from Q. " "Probed on the deployed critic, the held-out within-task " "action win rate goes 0.549 (0.0) -> 0.570 (2.0).")
ap.add_argument("--adv-norm", default="std", choices=["std", "none"], help="standardise the advantage inside the AWR weight. " "Without it beta is uninterpretable and the weight " "collapses to a hard sign filter.")
ap.add_argument("--init-pool", default="succ", choices=["succ", "demos", "demos_succ", "all"], help="episodes the pi_0 clone is fit on. Both critic arms must " "use the SAME value or the comparison measures the initialisation rather than the critic.")
ap.add_argument("--lr", type=float, default=3e-4)
ap.add_argument("--feat-scale", default="zscore", choices=["zscore", "center"], help="how the POLICY sees the observation. zscore matches the " "lane BC recipe that reaches 0.584; center keeps relative " "dim importance. Ranked on held-out sampled action MSE, " "never on the CFM loss.")
ap.add_argument("--critic", required=True) ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"], help="what the POLICY reads. raw = the full 4104-d observation " "(what a BC baseline sees); latent = the critic's " "reward-predictive bottleneck, which discards action " "detail and produced the 0%% closed-loop cliff. The " "ADVANTAGE always comes from the critic latent either way.")
ap.add_argument("--out", required=True) ap.add_argument("--rounds", type=int, default=2) ap.add_argument("--batch", type=int, default=256) ap.add_argument("--beta-q", type=float, default=0.98) ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--depth", type=int, default=2) ap.add_argument("--particles", type=int, default=8) ap.add_argument("--awr-beta", type=float, default=1.0) ap.add_argument("--w-max", type=float, default=20.0) ap.add_argument("--awr-steps", type=int, default=4000) ap.add_argument("--bc-steps", type=int, default=8000) ap.add_argument("--ratio-steps", type=int, default=4000) ap.add_argument("--wend-steps", type=int, default=4000) ap.add_argument("--use-is", type=int, default=1) ap.add_argument("--chunk", type=int, default=10, help="MUST match the critic's training chunk; the action\n dim is chunk*7 and a mismatch silently breaks loading") ap.add_argument("--ratio-chunk", type=int, default=0, help="action length the IS ratio scores; 0 = same as --chunk. " "Set to the BEHAVIOUR POLICY decision period (10 for pi0.5). " "The occupancy may condition on a much longer window; the " "ratio is a product over DECISIONS and must not.") ap.add_argument("--success-gamma", type=float, default=0.98, help="discount for reward-mode=soft: the label is " "success_gamma ** (frames until success)") ap.add_argument("--reward-mode", default="dense", choices=["dense","terminal","soft"], help="dense = P(task succeeds|z), every frame of a success is a " "positive (~50%%). terminal = last k frames only (~0.5%%), which " "leaves Q near-constant in the action.") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--policy-family", default="concat", choices=["concat", "flow", "gauss"]) ap.add_argument("--awr-pool", default="all", choices=["all", "succ", "demos"], help="which episodes AWR regresses on; 'succ' isolates dilution") ap.add_argument("--ratio-smooth", type=float, default=0.0, help="Gaussian kernel width applied to BOTH action classes before " "the ratio classifier; buys overlap at the cost of a blurred ratio") args = ap.parse_args() args.use_is = bool(args.use_is)
# Seed torch too, not just numpy: the policy head init and the # flow-matching noise are torch RNG. Without this two arms meant to # differ in ONE flag start from different policies -- observed as # pi_0 separation gaps of 0.0170 (IS on) vs 0.0089 (IS off). torch.manual_seed(args.seed) dev = "cuda" if torch.cuda.is_available() else "cpu" out = Path(args.out); out.mkdir(parents=True, exist_ok=True) d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode=args.reward_mode, success_gamma=getattr(args, 'success_gamma', 0.98), norm_pool=args.norm_pool) enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) args.d_z = cfg["d_z"] pfeat, d_pol = policy_features(args, enc, d, cfg, dev) print(f"[loop] policy reads {args.policy_features} ({d_pol}-d); " f"advantage reads critic latent ({cfg['d_z']}-d)", flush=True) rng = np.random.default_rng(args.seed + 23)
pol = train_bc(d, enc, args, dev, only_success=args.init_pool, steps=args.bc_steps, pfeat=pfeat, d_policy=d_pol, resume_path=str(Path(args.out) / 'bc_resume.pt')) # Continuation policy for the recursion only (critic-latent space). Cheap: # it never has to be a good controller, only a plausible next-action model # so the imagined hops stay on the behaviour manifold. cont_pol = (pol if args.policy_features != "raw" else train_bc(d, enc, args, dev, only_success=True, steps=max(args.bc_steps // 6, 2000), pfeat=enc, d_policy=cfg["d_z"])) log = {"config": vars(args), "rounds": []} log["pi_0"] = offline_score(d, enc, pol, rng, dev, pfeat=pfeat) print(f"[loop] pi_0 {log['pi_0']}", flush=True)
for r in range(1, args.rounds + 1): if args.use_is: # Re-fit every round: the target policy has moved, and a stale ratio # silently evaluates the wrong policy. print(f"=== round {r}: re-fit ratio for the CURRENT policy ===", flush=True) ratio = train_ratio(d, enc, cont_pol, args, dev, steps=args.ratio_steps) wend = train_endpoint_ratio(d, enc, ratio, args, dev, steps=args.wend_steps) else: # q_recursive ignores wend when use_is is False, so fitting it is # pure waste in the ablation arm. print(f"=== round {r}: IS off, skipping ratio fit ===", flush=True) wend = None pol, stats = awr_step(d, enc, pol, rew=rew, flow=flow, rms=rms, wend=wend, args=args, device=dev, steps=args.awr_steps, pfeat=pfeat, d_policy=d_pol, cont_pol=cont_pol) sc = offline_score(d, enc, pol, rng, dev, pfeat=pfeat) log["rounds"].append({"round": r, "awr": stats, "score": sc}) print(f"[loop] round {r} {sc}", flush=True) torch.save({"pol": pol.state_dict(), "round": r, "config": vars(args)}, out / f"policy_r{r}.pt") (out / "loop.json").write_text(json.dumps(log, indent=2)) print(json.dumps(log["rounds"][-1]["score"], indent=2), flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Behaviour-cloning arms: the bars an RSM recipe has to clear.
Two pools, one script: --pool demos -> A_bc_demos, cloning the 500 human demonstrations. This is the headline baseline: the lane's own bcdemos bar is 0.584. --pool succ -> B_bc_succ, cloning the SUCCESSFUL rollouts of the behaviour policy. This is behaviour-policy extraction with no critic at all, which is what "RSM adds value" has to beat.
No critic is loaded when the policy reads raw features, so these arms areindependent of the RSM run and can train in parallel with it. The policy class,chunk, optimiser and seed are identical to the AWR arms so the only thing thatdiffers across the four arms is where the improvement signal comes from."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, jsonfrom pathlib import Pathimport numpy as npimport torch
from data import LiberoRSMDatafrom is_ope import train_bc, policy_featuresfrom awr import offline_score
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--norm-pool", default="all", choices=["all", "demos"], help="frames the feature statistics come from. demos is worth +0.15 closed-loop over rollout-dominated statistics.")
ap.add_argument("--lr", type=float, default=3e-4)
ap.add_argument("--feat-scale", default="zscore", choices=["zscore", "center"], help="how the POLICY sees the observation. zscore matches the " "lane BC recipe that reaches 0.584; center keeps relative " "dim importance. Ranked on held-out sampled action MSE, " "never on the CFM loss.")
ap.add_argument("--out", required=True) ap.add_argument("--pool", required=True, choices=["demos", "succ", "rollsucc", "rollsucc_mix", "demos_succ", "all"], help="rollsucc = successful ROLLOUTS with demos excluded; " "succ silently includes all 500 demos.") ap.add_argument("--critic", default="", help="only needed when --policy-features latent") ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"]) ap.add_argument("--policy-family", default="concat", choices=["concat", "flow", "gauss"]) ap.add_argument("--chunk", type=int, default=10) ap.add_argument("--pol-width", type=int, default=1024, help="policy MLP width (1024 -> 7.7M params; 3072x8 -> ~90M)") ap.add_argument("--pol-depth", type=int, default=4) ap.add_argument("--demo-weight", type=float, default=1.0, help="sampling weight multiplier for demonstration episodes in a mixed pool") ap.add_argument("--save-every", type=int, default=0, help="save policy_s<step>.pt every N steps (checkpoint selection on validation inits)") ap.add_argument("--bc-steps", type=int, default=30000) ap.add_argument("--batch", type=int, default=1024) ap.add_argument("--in-ram", type=int, default=0) ap.add_argument("--success-gamma", type=float, default=0.98, help="discount for reward-mode=soft: the label is " "success_gamma ** (frames until success)") ap.add_argument("--reward-mode", default="dense", choices=["dense", "terminal", "soft"]) ap.add_argument("--demos-per-task", type=int, default=5, help="pool=rollsucc_mix only: demonstrations added per task on top " "of the rollout successes. 0 reduces to pool=rollsucc.") ap.add_argument("--success-mask", default="", help="npz with keep[] from merge_verify.py. Drops logged successes whose replay did not reproduce.") ap.add_argument("--eps-per-task", type=int, default=0, help="cap distinct initial conditions per task (0 = all). Each " "episode is an independent BDDL draw, so this is a direct " "coverage-density knob at FIXED data quality.") ap.add_argument("--qfilter-frac", type=float, default=0.0, help="clone only the top fraction of each oversampled batch " "by critic advantage (the port's qfilter_frac=0.25). " "Requires --critic. A third way to use the critic: data " "selection, not action selection or gradient weighting.") ap.add_argument("--beta-q", type=float, default=0.98) # rsm_rise V6 plan Q5 (2026-10-15): the RISE-actor recipe for the continuation policy. BOTH DEFAULT OFF -- # with them unset train_bc takes exactly the code path (and RNG draws) it always did. ap.add_argument("--sn-beta", type=float, default=0.0, help="spectral-norm penalty: loss += sn_beta * (sigma_max(W_first) + sigma_max(W_last)), " "first/last = the action in/out projections (flow: in_proj/out; gauss: first trunk " "Linear / mu), as openpi pi0.py spectral_norm_policy. 0 = OFF.") ap.add_argument("--knn-pairs", default="", help="RISE kNN action augmentation: npz from scripts/real/build_knn_pairs_ee.py (global frame " "index == cache row). Each (play i, neighbour j) pair with dist <= --knn-radius becomes an " "extra sample with observation i and action chunk j (openpi KNNAugmentedDataset). '' = OFF.") ap.add_argument("--knn-radius", type=float, default=0.01, help="kNN pair distance threshold (table units; ee = m)") ap.add_argument("--knn-augment-play", type=int, default=1, help="also use play->play pairs (different episode)") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--val-eps-json", default="", help="split json (episodes[i]['split']=='valid' -> val); default off = seeded split") 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 '', val_eps_json=args.val_eps_json)
enc, cfg = None, {"d_z": 0} if args.policy_features == "latent": if not args.critic: raise SystemExit("--policy-features latent needs --critic") from is_ope import load_critic enc, _r, _f, _rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) args.d_z = cfg["d_z"] pfeat, d_pol = policy_features(args, enc, d, cfg, dev) print(f"[bc_arm] pool={args.pool} eps={d.n_ep} chunk={d.chunk} " f"policy reads {args.policy_features} ({d_pol}-d)", flush=True)
Path(args.out).mkdir(parents=True, exist_ok=True) pool = {"demos": "demos", "succ": True, "rollsucc": "rollsucc", "rollsucc_mix": "rollsucc_mix", "demos_succ": "demos_succ", "all": False}[args.pool] pol = train_bc(d, enc, args, dev, only_success=pool, steps=args.bc_steps, pfeat=pfeat, d_policy=d_pol, resume_path=str(Path(args.out) / 'bc_resume.pt'))
# Save FIRST: a defect in the offline proxies must never discard an hour of # training that already produced a usable policy. out = Path(args.out); out.mkdir(parents=True, exist_ok=True) torch.save({"pol": pol.state_dict(), "round": 1, "config": vars(args), "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")}, out / "policy_r1.pt") rng = np.random.default_rng(args.seed + 23) sc = offline_score(d, enc, pol, rng, dev, pfeat=pfeat) sc["sampled_action_mse"] = getattr(pol, "best_sampled_mse", float("nan")) print(f"[bc_arm] {args.pool} {sc}", flush=True) (out / "loop.json").write_text(json.dumps( {"config": vars(args), "pi_0": sc, "rounds": []}, indent=2)) import is_ope as _isope if _isope.WANDB_RUN is not None: try: _isope.WANDB_RUN.log({f"final/{k}": v for k, v in sc.items() if isinstance(v, (int, float))}) _isope.WANDB_RUN.finish() except Exception as e: print(f"[bc_arm] wandb finish failed: {e}", flush=True) print("[bc_arm] DONE", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Temperature calibration of a DWM checkpoint's dense reward head on HELD-OUT frames (orchestrator, 13:20 UTC).
Fits a scalar T minimising BCE(sigmoid(logit / T), dense label) over the val episodes' frames (EMA head on realframes, z-scored tokens/proprio exactly as in training) and writes <ckpt dir>/calib.json: {T, ckpt, step, n_val, bce_before, bce_after, ece_before, ece_after, frac_p_gt_0.99_before/after, label_rate, train: {same numbers on a train-frame sample}}.DWMCritic then uses q = mean_i sigmoid(logit_i / T) (load_critic_dwm reads calib.json). T >> 1 = overconfident head.
python calib_dwm.py --cache cache/<task> --ckpt runs/<task>/rsm/DWM/ckpt_best.pt [--max-frames 20000]"""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, json, timefrom pathlib import Pathimport numpy as npimport torchimport torch.nn.functional as F
from dwm_model import TokenRSMDatafrom dwm_readout import load_critic_dwmfrom train_rsm import auc
def ece(p, y, n_bins=15): p = np.asarray(p, np.float64); y = np.asarray(y, np.float64) bins = np.linspace(0, 1, n_bins + 1); e = 0.0 for lo, hi in zip(bins[:-1], bins[1:]): m = (p > lo) & (p <= hi) if lo > 0 else (p >= lo) & (p <= hi) if m.any(): e += m.mean() * abs(p[m].mean() - y[m].mean()) return float(e)
def fit_T(logit, y, iters=200): """1-D BCE minimisation over log T (Newton-free: golden-section on [1/16, 64]).""" lo, hi = np.log(1 / 16), np.log(64.0) f = lambda t: float(F.binary_cross_entropy_with_logits(logit / np.exp(t), y)) r = (np.sqrt(5) - 1) / 2 a, b = lo, hi; c = b - r * (b - a); d = a + r * (b - a); fc, fd = f(c), f(d) for _ in range(iters): if fc < fd: b, d, fd = d, c, fc; c = b - r * (b - a); fc = f(c) else: a, c, fc = c, d, fd; d = a + r * (b - a); fd = f(d) if b - a < 1e-5: break return float(np.exp((a + b) / 2))
def stats(logit, y, T): p = torch.sigmoid(logit / T).cpu().numpy(); yn = y.cpu().numpy() return {"bce": float(F.binary_cross_entropy_with_logits(logit / T, y)), "ece": ece(p, yn), "frac_p_gt_0.99": float((p > 0.99).mean()), "frac_p_gt_0.9": float((p > 0.9).mean()), "mean_p": float(p.mean()), "auc": auc(p, yn), "mean_p_on_label0": float(p[yn < 0.5].mean()) if (yn < 0.5).any() else float("nan"), "mean_p_on_label1": float(p[yn > 0.5].mean()) if (yn > 0.5).any() else float("nan")}
@torch.no_grad()def logits_on(crit, d, idx, dev, bs=1024): out = [] for i in range(0, len(idx), bs): sl = idx[i:i + bs] tok = torch.from_numpy(d._tok(sl)).to(dev); pr = torch.from_numpy(d._pr(sl)).to(dev) tz, pz = crit.norm.tok(tok), crit.norm.pr(pr) with crit.autocast(): out.append(crit.rew(tz, pz).float()) return torch.cat(out)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True); ap.add_argument("--ckpt", required=True) ap.add_argument("--reward-mode", default="dense"); ap.add_argument("--seed", type=int, default=0) ap.add_argument("--max-frames", type=int, default=20000); ap.add_argument("--out", default="") a = ap.parse_args() dev = "cuda" if torch.cuda.is_available() else "cpu" d = TokenRSMData(a.cache, chunk=8, seed=a.seed, reward_mode=a.reward_mode) crit = load_critic_dwm(a.ckpt, dev, calib=None) rng = np.random.default_rng(a.seed) val_idx = np.concatenate([np.arange(d.ep_from[e], d.ep_to[e]) for e in d.val_eps]) tr_idx = np.concatenate([np.arange(d.ep_from[e], d.ep_to[e]) for e in d.train_eps]) if len(val_idx) > a.max_frames: val_idx = np.sort(rng.choice(val_idx, a.max_frames, replace=False)) tr_idx = np.sort(rng.choice(tr_idx, min(a.max_frames, len(tr_idx)), replace=False)) t0 = time.time() lv = logits_on(crit, d, val_idx, dev); yv = torch.from_numpy(d.r[val_idx]).to(dev) lt = logits_on(crit, d, tr_idx, dev); yt = torch.from_numpy(d.r[tr_idx]).to(dev) T = fit_T(lv, yv) rec = {"T": T, "ckpt": str(a.ckpt), "step": crit.step, "label": a.reward_mode, "n_val": int(len(val_idx)), "n_train": int(len(tr_idx)), "label_rate_val": float(yv.mean()), "label_rate_train": float(yt.mean()), "val_before": stats(lv, yv, 1.0), "val_after": stats(lv, yv, T), "train_before": stats(lt, yt, 1.0), "train_after": stats(lt, yt, T), "T_fit_on_train_for_reference": fit_T(lt, yt), "seconds": time.time() - t0} for k in ("bce", "ece", "frac_p_gt_0.99"): rec[f"{k}_before"] = rec["val_before"][k]; rec[f"{k}_after"] = rec["val_after"][k] out = Path(a.out) if a.out else Path(a.ckpt).parent / "calib.json" out.write_text(json.dumps(rec, indent=1)) print(f"[calib] T={T:.3f} val bce {rec['bce_before']:.4f}->{rec['bce_after']:.4f} ece {rec['ece_before']:.4f}->" f"{rec['ece_after']:.4f} frac p>0.99 {rec['frac_p_gt_0.99_before']:.4f}->{rec['frac_p_gt_0.99_after']:.4f} " f"(val auc {rec['val_before']['auc']:.4f}; train T_ref {rec['T_fit_on_train_for_reference']:.3f}) -> {out}", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""Capture the evaluator's t=0 feature vector without rolling out.
The question this answers: are the features the closed-loop evaluator actuallyfeeds the policy in the DEMO region of the cache or the ROLLOUT region? It decideswhether a critic trained on a 90%-rollout corpus is read on-support at eval time.
Only the first observation of each episode is needed, so no policy and no GPU arerequired -- reset, one zero step, encode, done. Uses the SAME featurization path aseval_closed_loop.py (to224 quantisation, axis-angle proprio, cache normalisation);any deviation would make the comparison meaningless."""from __future__ import annotationsimport argparse, importlib.util, sys, osfrom pathlib import Pathimport numpy as npimport torch
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from eval_closed_loop import to224, _eef_ori, BUILDER # identical transforms
_spec = importlib.util.spec_from_file_location("ogpo_cap", BUILDER)ogpo = importlib.util.module_from_spec(_spec)sys.modules["ogpo_cap"] = ogpo_spec.loader.exec_module(ogpo)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True, help="cache whose feat stats the policy used") ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) ap.add_argument("--tasks", default="0,1,2,3,4,6,7,8,9") ap.add_argument("--n-init", type=int, default=5) ap.add_argument("--fresh", type=int, default=0) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", required=True) args = ap.parse_args()
dev = "cuda" if torch.cuda.is_available() else "cpu" print(f"[cap] device {dev}", flush=True) tower = ogpo.build_paligemma(dev) from libero.libero import benchmark, get_libero_path from libero.libero.envs import OffScreenRenderEnv bench = benchmark.get_benchmark_dict()["libero_10"]()
sname = "feat_stats.npz" if args.norm_pool == "all" else f"feat_stats_{args.norm_pool}.npz" st = np.load(str(Path(args.cache) / sname)) nmu = torch.tensor(st["mu"], dtype=torch.float32, device=dev) nsd = torch.tensor(st["sd"], dtype=torch.float32, device=dev) print(f"[cap] normalisation {sname} dim={int(st['dim'])}", flush=True)
tasks, feats = [], [] for tid in [int(t) for t in args.tasks.split(",")]: task = bench.get_task(tid) ids = ogpo.tokenize_prompt(task.language) inits = bench.get_task_init_states(tid) env = OffScreenRenderEnv( bddl_file_name=str(Path(get_libero_path("bddl_files")) / task.problem_folder / task.bddl_file), camera_heights=128, camera_widths=128) for k in range(args.n_init): np.random.seed(args.seed * 100003 + tid * 1009 + k) if hasattr(env, "seed"): env.seed(args.seed * 100003 + tid * 1009 + k) env.reset() if not args.fresh: env.set_init_state(inits[k % len(inits)]) obs, _, _, _ = env.step(np.zeros(7)) cams = [] for key in ("agentview_image", "robot0_eye_in_hand_image"): cams.append(to224(obs[key][::-1, ::-1])[None]) z = np.concatenate( [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0] prop = np.concatenate([ obs["robot0_eef_pos"], _eef_ori(obs), obs["robot0_gripper_qpos"], ]).astype(np.float32) x = torch.tensor(np.concatenate([z, prop])[None], dtype=torch.float32, device=dev) x = (x - nmu) / nsd tasks.append(tid); feats.append(np.asarray(x[0].cpu(), np.float32)) print(f"[cap] task {tid} init {k}: |x|={float(x.norm()):.2f}", flush=True) env.close() np.savez_compressed(args.out, task=np.array(tasks), x=np.stack(feats), norm_pool=args.norm_pool, fresh=args.fresh) print(f"[cap] wrote {len(tasks)} features -> {args.out}", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Does the Q arg-max over N near-copy candidates track the critic or the Monte-Carlonoise? Score the same N candidates twice with fresh seeds, with independent draws andwith common random numbers (crn), and report arg-max agreement and the ratio ofbetween-candidate Q spread to between-seed Q noise. CPU/GPU, no env.usage: crn_diag.py --critic ckpt --policy proposer.pt --hop hop.pt [--depth 3] [--n 8] [--states 200]"""import argparse, numpy as np, torchfrom data import LiberoRSMDatafrom is_ope import load_critic, q_recursive, make_policyfrom eval_closed_loop import load_policy, _resolve_cache
ap = argparse.ArgumentParser()ap.add_argument("--critic", required=True); ap.add_argument("--policy", required=True)ap.add_argument("--hop", default=""); ap.add_argument("--depth", type=int, default=3)ap.add_argument("--n", type=int, default=8); ap.add_argument("--states", type=int, default=200)ap.add_argument("--particles", type=int, default=16); ap.add_argument("--beta", type=float, default=0.98)a = ap.parse_args()dev = "cuda" if torch.cuda.is_available() else "cpu"pcfg = torch.load(a.policy, map_location="cpu", weights_only=False)["config"]d = LiberoRSMData(_resolve_cache(pcfg["cache"]), chunk=pcfg.get("chunk", 10), seed=0, in_ram=False, reward_mode="dense", norm_pool=pcfg.get("norm_pool", "all"))pfeat, pol, chunk, ccfg, pmode, d_lat, _ = load_policy(a.critic, a.policy, d.n_task, dev)q_enc, q_rew, q_flow, q_rms, q_cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d)hop = Noneif a.depth >= 2: hk = torch.load(a.hop, map_location=dev, weights_only=False) hop = make_policy(hk["config"], d, dev, d_z=q_cfg["d_z"]); hop.load_state_dict(hk["pol"]); hop.eval()rng = np.random.default_rng(0)# demo frames from the pool the proposer was trained oneps = np.where(d.ep_demo)[0]; rows = []tasks = []for e in rng.choice(eps, size=a.states, replace=True): s, l = int(d.ep_from[e]), int(d.ep_len[e]); rows.append(s + int(rng.integers(0, max(1, l - chunk)))); tasks.append(int(d.ep_task[e]))agree = {0: [], 1: []}; ratio = {0: [], 1: []}; agree_x = []with torch.no_grad(): for i, ti in zip(rows, tasks): x = torch.as_tensor(d._feat(i)[None], device=dev).float(); tt = torch.tensor([ti], device=dev) torch.manual_seed(1234 + i) cand = pol.sample(pfeat(x).expand(a.n, -1), tt.expand(a.n)) z = q_enc(x).expand(a.n, -1) qs = {} for crn in (0, 1): out = [] for seed in (1, 2): torch.manual_seed(seed) q, _ = q_recursive(z, cand, tt.expand(a.n), rew=q_rew, flow=q_flow, rms=q_rms, pol=hop, wend=None, beta=a.beta, gamma=0.99, depth=a.depth, n_particles=a.particles, use_is=False, crn=bool(crn)) out.append(q.cpu().numpy()) q1, q2 = out; qs[crn] = (q1, q2) agree[crn].append(float(q1.argmax() == q2.argmax())) spread = 0.5 * (q1.std() + q2.std()); noise = np.abs(q1 - q2).mean() / np.sqrt(2) ratio[crn].append(spread / max(noise, 1e-9)) agree_x.append(float(qs[0][0].argmax() == qs[1][0].argmax()))for crn in (0, 1): print(f"crn={crn}: argmax agreement across seeds {np.mean(agree[crn]):.3f} " f"median (between-candidate spread / between-seed noise) {np.median(ratio[crn]):.2f}")print(f"chance agreement = {1/a.n:.3f}; independent-vs-crn argmax agreement {np.mean(agree_x):.3f}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644"""Batch sampling over the packed LIBERO-10 rollout cache."""from __future__ import annotationsfrom pathlib import Pathimport json as _json # was only imported inside the cam_res loop below, so the encoder # tag lookup (which runs first) always hit NameError and kept the # legacy default; importing it here makes PACK.json's encoder tag loadimport numpy as npimport torch
def truncated_geometric_future(rows, ep_ends, discounts, uniforms): """Ported verbatim from gen_q ogbench_genq/rsm.py (via the CLM fast-critic port).
Draws k ~ Geom(1-discount) truncated to the episode end, so the sampled future is always a REAL logged frame -- the Monte-Carlo occupancy target with no bootstrap anywhere. """ length = (ep_ends - rows) log_d = np.log(discounts) finite_mass = np.maximum(1.0 - np.exp(length * log_d), 1e-12) offset = np.ceil(np.log1p(-uniforms * finite_mass) / log_d).astype(np.int64) - 1 offset = np.clip(offset, 0, length - 1) return rows + offset
class LiberoRSMData: def __init__(self, root, chunk: int = 10, k_success: int = 10, val_frac: float = 0.1, seed: int = 0, in_ram: bool = True, success_mask: str = "", subgoal_dir: str = "", reward_mode: str = "dense", success_gamma: float = 0.98, reward_npy: str = "", weight_npy: str = "", normalize: bool = True, norm_pool: str = "all", stratify_success: bool = False, action_augment: float = 0.0, augment_mode: str = "contrastive", augment_table: str = "", augment_neighbors: int = 15, augment_frac_cap: float = 0.0, val_eps_json: str = "", start_weight_npy: str = "", aug_group_npy: str = ""): 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:]) if val_eps_json: # EXPLICIT SPLIT FILE (rsm_rise V6_JUNCTION, 2026-10-15). The seeded split above ignores the # plan split (data/derived/cooking_v6_split.json), so every v6 model trained on 16-18/18 TUNE # and 11-12/13 TEST episodes. Episodes with split=='valid' become val, the rest train. Applied # after the seeded permutation so the rng state is unchanged; unset = bit-identical. _sp = _json.load(open(val_eps_json))["episodes"] assert len(_sp) == self.n_ep, f"{val_eps_json}: {len(_sp)} episodes vs cache {self.n_ep}" _lens = np.array([int(_sp[str(i)]["length"]) for i in range(self.n_ep)]) assert (_lens == np.asarray(self.ep_len)).all(), f"{val_eps_json}: episode lengths differ from cache" self.val_eps = np.array(sorted(i for i in range(self.n_ep) if _sp[str(i)]["split"] == "valid"), np.int64) self.train_eps = np.sort(np.setdiff1d(np.arange(self.n_ep), self.val_eps)) print(f"[data] split from {val_eps_json}: {len(self.val_eps)} val / {len(self.train_eps)} train", flush=True)
# 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)
# JUNCTION-WEIGHTED START SAMPLING (V6_SCORER tier c, 2026-10-15). Default off: with # start_weight_npy unset nothing below runs and the sampler is bit-identical. When set, # TRAINING draws of sample(augment=True) pick the start row t with P(t) ~ w[t] over the # train frames (diagnostic samplers, augment=False, keep the episode-uniform draw); the # augmented-pair draw is weighted by w[anchor] too. aug_group_npy (int per frame): for # anchors with w > 1, pairs whose neighbour has the SAME group are dropped, so the # counterfactual target at an up-weighted start comes from another edge. self.start_w = None if start_weight_npy: _sw = np.load(start_weight_npy).astype(np.float64).ravel() assert len(_sw) == int(self.ep_to[-1]) and (_sw >= 0).all(), "bad start weights" self.start_rows = np.concatenate([np.arange(int(self.ep_from[e]), int(self.ep_to[e])) for e in self.train_eps]).astype(np.int64) _p = _sw[self.start_rows]; self.start_p = _p / _p.sum() self.start_w = _sw self.row_ep_all = np.zeros(int(self.ep_to[-1]), np.int64) for _e in range(self.n_ep): self.row_ep_all[int(self.ep_from[_e]):int(self.ep_to[_e])] = _e print(f"[data] start weights {start_weight_npy}: {int((_sw[self.start_rows] > 1).sum())} up-weighted " f"train rows, their batch share {float(self.start_p[_sw[self.start_rows] > 1].sum()):.3f}", flush=True) if self.aug: _wa = _sw[self.aug_anchor] if aug_group_npy: _g = np.load(aug_group_npy).astype(np.int64).ravel() assert len(_g) == len(_sw) _keep = ~((_wa > 1) & (_g[self.aug_anchor] == _g[self.aug_nbr])) print(f"[data] aug group filter: dropped {int((~_keep).sum())} same-group pairs at " f"up-weighted anchors, {int(_keep.sum())} pairs left", flush=True) self.aug_anchor = self.aug_anchor[_keep]; self.aug_nbr = self.aug_nbr[_keep] self.aug_dist = self.aug_dist[_keep]; _wa = _wa[_keep] self.aug_pair_p = _wa / _wa.sum() elif aug_group_npy: raise ValueError("aug_group_npy needs start_weight_npy")
# 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 if self.start_w is not None and augment and split == "train": t = rng.choice(self.start_rows, size=batch, p=self.start_p) e = self.row_ep_all[t] lo = self.ep_from[e]; hi = self.ep_to[e] else: w = self.ep_len[eps_pool].astype(np.float64); w /= w.sum() e = rng.choice(eps_pool, size=batch, p=w) lo = self.ep_from[e]; hi = self.ep_to[e] t = lo + (rng.random(batch) * (hi - lo)).astype(np.int64) # BETA MEANS ONE THING (gen_q#262). k ~ Geom(1-beta) is truncated at the episode end, and # E[k | k<L] depends on L -- at beta=0.995 with 150 frames remaining, 47% of the geometric # falls past the end and the realised mean offset is 65 instead of 199. Drawing beta before # looking at L therefore trains the model on "beta=0.995" paired with horizons anywhere from # ~23 to ~180 frames, blurring the conditioning exactly where the horizon is longest. # # Cap beta per anchor so the truncated tail is a CONSTANT eps for every sample: # beta_cap**L == eps => beta_cap = eps**(1/L) # Anchors with a long remaining horizon (a full episode from its initial condition) get the # whole band; short-remaining anchors get a correspondingly narrower one, because a # long-horizon target genuinely does not exist there. L = np.maximum(hi - t, 1).astype(np.float64) beta_cap = np.power(beta_trunc_eps, 1.0 / L) beta_hi_eff = np.clip(beta_cap, beta_lo, beta_hi) beta = beta_lo + rng.random(batch) * (beta_hi_eff - beta_lo) fut = truncated_geometric_future(t, hi, beta, rng.random(batch))
# ---- counterfactual action augmentation (see the block in __init__) ------------------- # Nothing here touches `rng`: with augmentation off the draws above ARE the whole sampler and # every existing run reproduces bit-for-bit. `t_act` is the row the ACTION chunk comes from # and is identical to `t` on every non-augmented row. t_act, e_act = t, e aug_mask = np.zeros(batch, bool) if self.aug and augment and split == "train": if with_next: raise NotImplementedError( "--action-augment with --occupancy-target td is not implemented: the TD " "right-hand side needs s_{t+1} and a_{t+1} for the COUNTERFACTUAL action, which " "the logged corpus does not contain. Use the MC occupancy target.") ar = self._aug_rng n_aug = int(ar.binomial(batch, self.aug_p)) if n_aug > 0: t_act = t.copy(); e_act = e.copy() pos = ar.choice(batch, size=min(n_aug, batch), replace=False) if self.start_w is not None: pi = ar.choice(len(self.aug_anchor), size=len(pos), p=self.aug_pair_p) else: pi = ar.integers(len(self.aug_anchor), size=len(pos)) i_row = self.aug_anchor[pi] # the ANCHOR state (x_now) j_row = self.aug_nbr[pi] # the NEIGHBOUR: its action is the counterfactual # "invariant" asserts the anchor's OWN occupancy for the counterfactual action; # "contrastive" gives the counterfactual action the NEIGHBOUR's own future. src = i_row if self.aug_mode == "invariant" else j_row e_src = self.row_ep[src].astype(np.int64) hi_s = self.ep_to[e_src] L_s = np.maximum(hi_s - src, 1).astype(np.float64) b_cap = np.power(beta_trunc_eps, 1.0 / L_s) # the SAME beta band and the SAME b_hi = np.clip(b_cap, beta_lo, beta_hi) # truncation cap as the logged rows b_new = beta_lo + ar.random(len(pos)) * (b_hi - beta_lo) fut_new = truncated_geometric_future(src, hi_s, b_new, ar.random(len(pos))) # x_now, r_now, task, succ, demo all stay the ANCHOR's (the reward head is # state-only, so relabelling r at an unchanged x_now would be label noise) e[pos] = self.row_ep[i_row] t[pos] = i_row beta[pos] = b_new fut[pos] = fut_new t_act[pos] = j_row e_act[pos] = self.row_ep[j_row] aug_mask[pos] = True
x_now = torch.from_numpy(self._feat(t)).to(device) x_fut = torch.from_numpy(self._feat(fut)).to(device) a_now = torch.from_numpy(self._chunk_at(t_act, e_act)).to(device) out = { "x_now": x_now, "x_fut": x_fut, "a_now": a_now, "task": torch.from_numpy(self.ep_task[e]).long().to(device), "beta": torch.from_numpy(beta).float().to(device), "r_now": torch.from_numpy(self.r[t]).to(device), "r_fut": torch.from_numpy(self.r[fut]).to(device), "succ": torch.from_numpy(self.ep_success[e].astype(np.float32)).to(device), "demo": torch.from_numpy(self.ep_demo[e].astype(np.float32)).to(device), "t_idx": t, "ep": e, "fut_idx": fut, } # BUGFIX 2026-09-23 (pack 1881632 crashed here): `aug_frac` is a SCALAR, and nnl1_eval slices # every value of the batch dict by a row index. Emit the two bookkeeping keys ONLY on a batch # that actually went through the augmented path, so the diagnostic samplers (augment=False) and # every run with the flag off see EXACTLY the pre-change key set. Both readers in train_rsm.py # already use b.get(..., 0.0). if self.aug and augment and split == "train": out["aug_mask"] = aug_mask out["aug_frac"] = float(aug_mask.mean()) if self.w is not None: out["w_now"] = torch.from_numpy(self.w[t]).to(device) if with_next: # TD-FLOW (gen_q#268). The Bellman right-hand side of the occupancy identity # m_beta(. | s,a) = (1-beta) P(. | s,a) + beta E_{s'}[ m_beta(. | s', pi(s')) ] # needs the ONE-STEP successor s' and the action the behaviour policy takes there. # This lane fits the occupancy of the DATASET policy (train_rsm.py has no actor), so # a' is the logged chunk at t+1 -- exactly the analogue of a' = pi(s') for the policy # the Monte-Carlo path already integrates along. # Clamped to hi-1, i.e. the terminal frame is its own successor; the mixture coin is # drawn per row in train_rsm.py, so a terminal anchor that takes the bootstrap branch # bootstraps from itself rather than from a frame of the next episode. # NOTHING here draws from `rng`: with with_next=False (the default) this block does not # run at all, and with it True the MC draws above are bit-for-bit unchanged. nxt = np.minimum(t + 1, hi - 1) out["x_next"] = torch.from_numpy(self._feat(nxt)).to(device) out["a_next"] = torch.from_numpy(self._chunk_at(nxt, e)).to(device) out["r_next"] = torch.from_numpy(self.r[nxt]).to(device) out["next_idx"] = nxt return out
def goal_pool(self): """Terminal latents of SUCCESSFUL episodes, per task -- the goal set the two-tower likelihood scores against. Built once; index by task id.""" if getattr(self, "_gpool", None) is None: pool = {} for i in range(self.n_ep): if not self.ep_success[i]: continue hi = int(self.ep_to[i]) pool.setdefault(int(self.ep_task[i]), []).extend( range(max(int(self.ep_from[i]), hi - self.k_success), hi)) self._gpool = {k: np.array(v, np.int64) for k, v in pool.items()} return self._gpool
def sample_goals(self, task_ids, rng, device="cuda"): """One goal latent per row, drawn from that row's task's terminal states.""" gp = self.goal_pool() idx = np.empty(len(task_ids), np.int64) for j, ti in enumerate(np.asarray(task_ids)): c = gp.get(int(ti)) idx[j] = rng.choice(c) if c is not None and len(c) else 0 return torch.from_numpy(self._feat(idx)).to(device)
def sample_frames(self, batch: int, rng, split="train", device="cuda"): """(x, action chunk, task, reward, success) with no future -- for the reward head, the ratio classifier and behavior cloning.""" eps_pool = self.train_eps if split == "train" else self.val_eps w = self.ep_len[eps_pool].astype(np.float64); w /= w.sum() e = rng.choice(eps_pool, size=batch, p=w) lo = self.ep_from[e]; hi = self.ep_to[e] t = lo + (rng.random(batch) * (hi - lo)).astype(np.int64) return { "to_end": torch.from_numpy((hi - t).astype(np.float32)).to(device), "x": torch.from_numpy(self._feat(t)).to(device), "a": torch.from_numpy(self._chunk_at(t, e)).to(device), "task": torch.from_numpy(self.ep_task[e]).long().to(device), "r": torch.from_numpy(self.r[t]).to(device), "succ": torch.from_numpy(self.ep_success[e].astype(np.float32)).to(device), "demo": torch.from_numpy(self.ep_demo[e].astype(np.float32)).to(device), "t_idx": t, "ep": e, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228"""Diffusion Forcing as a VALUE ESTIMATOR -- the eval-harness read-out (gen_q#274 / #282, DF_VALUE).
WHAT THIS IS------------The third column of the world-model family. All three are the same experiment with ONE thingchanged -- how the horizon is produced:
DINO-WM autoregressive latent rollout, chunk after chunk (dinowm_readout.py) LeWM autoregressive latent rollout (lewm_readout.py) DF ONE joint multi-step generation of the whole horizon, per-token noise levels (here)
so this module is deliberately the same shape as the other two: a `*Critic` class with the `q(...)`signature `rsm_scorer` calls, plus a `load_critic_df` loader. The scoring MATH is not reimplementedhere -- it is `df_value.value_of_candidates`, the same function the offline spread gate runs, so aneval cell and the gate cannot disagree about what "DF's value of a candidate" means.
THE READ-OUT (D1-D4, status/real/DF_VALUE.md; the docstring of df_value.py is the full statement) D1 the candidate action chunk is INPAINTED into the action channel of plan token 1 and re-imposed after every scheduling step; guidance_fn is None, ALWAYS. There is no guidance objective in this route -- that is the planner route, and it is a different stream's. D2 past the 8-frame chunk the action channel is LEFT FREE (model-sampled): the value means "this chunk, then the behaviour distribution the model was trained on", which is the same semantics as RSM's successor measure under the behaviour policy. free_tail=False (zero action, i.e. "this chunk then nothing") is the named ablation, exposed as `free_tail`. D3 M Monte-Carlo draws, the analogue of RSM's particle count P. See CRN below. D4 two aggregations of the predicted reward channel: terminal r_hat at H (mode="mpc") and the normalised discounted sum (mode="mpc_disc"). They map onto the two MPC modes the DINO-WM and LeWM columns already publish, so the arm grammar is byte-identical across the three.
INPUT SPACE. The pooled 1545-d DINOv2 state, z-scored with the task's feat_stats -- literally thesame vector `rsm_scorer.PooledDinoState.forward` returns and the same map `df_data.obs_rows` applies(`x = clip((feat - mu)/sd)`). So DF reads the scorer's DEFAULT state field `x`; unlike DINO-WM itneeds no patch tokens and unlike LeWM it needs no pixels, and `state_from_obs` needs no new branch.The model's SECOND normalisation (the bundle-level z-score over [obs | act | reward]) is appliedinside df_value via `model.norm`, from the checkpoint's own mean/std.
COMMON RANDOM NUMBERS. `rsm_scorer` flattens (B envs x N candidates) into rows and a backend isnever told N, so drawing noise per row would give every candidate its own noise and make the argmaxpartly a noise draw. This module therefore calls df_value with `crn_rows=True`: ONE noise draw perMonte-Carlo index, shared by every row of the call. `crn_seed` from the planner selects it, so acell is reproducible and two candidates differ only by their actions.
WHAT IS NOT MATCHED, STATED PLAINLY-----------------------------------1. DF's value is NOT a probability. DINO-WM and LeWM push their reward logit through a sigmoid and return c_k in [0,1]; DF's reward channel is a REGRESSION onto the provenance label, unnormalised and unbounded. It is clamped to [0,1] here ONLY because the planner's argmax and the table's health numbers assume that range; `q_raw` carries the unclamped value. No temperature calibration exists for it, so `temperature` is accepted and ignored, and `return_logit` returns the raw value, NOT a logit. Any read-out that needs a real logit (prob_log, conformal_lcb) is refused rather than faked.2. The two aggregations are one rollout used twice, but the scorer asks for one mode per cell, so a (mpc, mpc_disc) pair of cells rolls the model twice. That is 2x the compute for a pair of numbers that could share it; it is accepted here because sharing would mean caching across calls inside a backend the harness may re-instantiate, and a wrong cache is worse than a slow cell.3. The continuation past chunk 1 is the model's own sampled action channel (D2), which is NEITHER DINO-WM's hop head NOR LeWM's zero-order hold. The three columns therefore differ in the continuation as well as the rollout mechanism; the caption must say so."""from __future__ import annotations
import jsonimport osimport sysfrom pathlib import Path
import numpy as npimport torch
_DF_DIR = "/proj/dmfexp/zwhong/rsm_rise/code/df_rise"if _DF_DIR not in sys.path: sys.path.insert(0, _DF_DIR)
# The RISE eval env ($ROOT/env, py3.10) does not ship rotary_embedding_torch, and upstream's# models/diffusion.py -> models/unet3d.py:6 imports it unconditionally (unet3d is NOT used by our# 1-D transformer bundle; the import is merely on the module path). code/df_rise/_deps holds the# real 0.9.1 package, vendored by the planner stream (see _deps/PROVENANCE.txt) and put on sys.path# there only inside eval.py's `if RR_DF_CKPT:` block -- a branch this value-estimator route never# takes. Do the same here, guarded, so no shared environment is mutated and a process that already# has the package (venv_df, where the trainer and the offline gate run) is untouched.# Measured: without this, LSF 1893591 died at df_readout.py:87 with ModuleNotFoundError.try: # pragma: no cover - env-dependent import rotary_embedding_torch as _ret # noqa: F401except ModuleNotFoundError: _DF_DEPS = os.path.join(_DF_DIR, "_deps") if os.path.isdir(_DF_DEPS) and _DF_DEPS not in sys.path: sys.path.append(_DF_DEPS)
from df_data import OBS_DIM, ACT_DIM # noqa: E402from df_core import DFRise # noqa: E402from df_value import value_of_candidates, default_gamma # noqa: E402
class DFCritic: """The interface robomimic's RSMScorer expects of a backend core (see rsm_scorer.DWMBackend)."""
def __init__(self, ck, device, free_tail=True): meta = ck["meta"] self.device = torch.device(device) # TF32 ON by default, and it is a MEASUREMENT, not a guess. LSF 1894069 ran threading df_A # H=50 M=8 over 128 shared anchors at S=50 in both precisions and dumped the raw 128x128 # value matrices (status/real/dfval/vals_*_cost_s50_{fp32,tf32}.npz). Against the fp32 # reference TF32 agrees on top-1 -- which is all the planner's argmax consumes -- for # 99.2 % of anchors on the discounted read-out and 96.9 % on terminal, with per-anchor rank # correlation 1.000 / 0.995, while cutting the cell 1.45x (119.4s -> 81.3s / 128 anchors). # Contrast the DDIM knob, measured in the SAME job and REJECTED: S=25 already drops terminal # top-1 to 0.594 and S=10 to 0.367, so sampling_timesteps stays at its trained-config 50. # RR_DF_TF32=0 restores full fp32 for a bit-comparable re-read. self._tf32 = os.environ.get("RR_DF_TF32", "1") not in ("0", "false", "False") torch.backends.cuda.matmul.allow_tf32 = self._tf32 torch.backends.cudnn.allow_tf32 = self._tf32 self.frame_stack = int(meta["frame_stack"]) self.n_tokens = int(meta["n_tokens"]) self.model = DFRise(frame_stack=self.frame_stack, n_tokens=self.n_tokens, mean=ck["mean"], std=ck["std"], cfg=ck["cfg"]).to(self.device) self.model.load_state_dict(ck["model"]) self.model.eval() for p in self.model.parameters(): p.requires_grad_(False) # The candidate chunk IS one plan token: frame_stack == the project's 8-frame action chunk. self.chunk = self.frame_stack self.adim = ACT_DIM self.d_act = self.chunk * ACT_DIM self.d_z = OBS_DIM # One DF hop = one plan token = frame_stack frames, so K = ceil(H / hop_frames) plan tokens. # Read by rsm_scorer to turn the cell's H (in frames) into a depth; constant in beta, as on # DINO-WM and LeWM, because a latent world model has no beta. self.hop_frames = float(self.frame_stack) self.step = int(ck.get("step", -1)) self.free_tail = bool(free_tail) self.temperature = 1.0 self.calib = None self.q_action_winrate = None # The training window, kept so a cell can declare when H extrapolates past it. self.train_frames = self.frame_stack * self.n_tokens self.last_diag = None
# ------------------------------------------------------------------------------------------ def _prep(self, inp, a_chunk): x = inp[0] if isinstance(inp, (tuple, list)) else inp x = torch.as_tensor(x).to(self.device).float() assert x.ndim == 2 and x.shape[1] == self.d_z, \ f"DF scores from the pooled {self.d_z}-d state, got {tuple(x.shape)}" a = torch.as_tensor(a_chunk).to(self.device).float().view(x.shape[0], -1) assert a.shape[1] == self.d_act, f"a_chunk must be [B,{self.d_act}], got {tuple(a.shape)}" return x, a.view(x.shape[0], 1, self.chunk, self.adim)
@torch.no_grad() def q(self, inp, a_chunk, beta=None, n_particles=1, crn_seed=None, depth=1, mode="mpc", proprio=None, hop_policy=None, gamma=0.99, flow_steps=8, micro=256, return_hops=False, return_logit=False, temperature=None, return_lcb=None, rescore_top=0, n_particles_rescore=0): """Q per row. `depth` = plan tokens (K), so the horizon rolled is K * frame_stack frames.
`n_particles` is DF's M (D3) -- unlike DINO-WM this model IS stochastic, so the particle axis is real here and is not forced to 1. `beta`, `flow_steps`, `hop_policy` and `proprio` are accepted because the shared planner passes them to every backend, and are inert: DF has no hazard, no ODE, no hop head and reads no proprio channel of its own (proprio is already inside the pooled state).""" if mode not in ("mpc", "mpc_disc"): raise ValueError( f"mode {mode!r}: the DF value route publishes the two MPC read-outs only -- 'mpc' " f"(terminal r_hat at H) and 'mpc_disc' (normalised discounted sum along the " f"rollout). 'd1' and 'fold' are hazard read-outs of a SUCCESSOR model; DF has no " f"per-hop hazard to fold, and faking one would not be the same estimator.") if return_lcb is not None: raise ValueError("plan_score=conformal_lcb needs a calibrated particle quantile; DF's " "reward channel is an uncalibrated regression, so a quantile of it is " "not a lower confidence bound on anything") x, a = self._prep(inp, a_chunk) K = max(int(depth), 1) H = int(K * self.frame_stack) M = max(int(n_particles), 1) seed = 0 if crn_seed is None else int(crn_seed) out = value_of_candidates( self.model, x, a, H=H, M=M, # D4: the cell's own gamma, so the discounted sum uses the SAME discount the cell's H # was derived from (H = 1/(1-gamma)) instead of df_value's default 1 - 1/H. gamma=float(gamma) if mode == "mpc_disc" else None, free_tail=self.free_tail, device=self.device, seed=seed, crn_rows=True, assert_clamp=True) v = (out["terminal"] if mode == "mpc" else out["disc"])[:, 0] sd = (out["terminal_std"] if mode == "mpc" else out["disc_std"])[:, 0] self.last_diag = dict(out["diag"], mode=mode, H=H, K=K, M=M, mean_std_across_M=float(sd.mean().item()), std_across_rows=float(v.std().item())) q_raw = torch.nan_to_num(v, nan=0.0) q = q_raw.clamp(0.0, 1.0) # see "WHAT IS NOT MATCHED" 1 in the module docstring out_v = (q, q_raw) if return_logit else q if return_hops: # DF generates the horizon JOINTLY -- there is no per-hop sequence of independent # decisions to report, which is the whole point of the column. Returning the terminal # value K times would look like a hop trace and would be a lie about the mechanism. raise ValueError("return_hops has no meaning for DF: the horizon is generated jointly, " "not hop by hop") return out_v
def hop_sample(self, x, eps): raise RuntimeError("DF has no hop head: the continuation past the candidate chunk is the " "model's OWN sampled action channel (D2), not a policy over states")
def describe(self): return {"backend": "df", "frame_stack": self.frame_stack, "n_tokens": self.n_tokens, "hop_frames": self.hop_frames, "chunk": self.chunk, "d_act": self.d_act, "step": self.step, "free_tail": self.free_tail, "tf32": self._tf32, "train_frames": self.train_frames, "deterministic": False, "readout": "predicted reward channel of a jointly generated multi-step bundle", "guidance": "none (guidance_fn=None)"}
def load_critic_df(path, device="cuda", calib="auto", free_tail=None) -> DFCritic: """`path` is a train_df.py checkpoint (ckpt_s<step>.pt: keys cfg/mean/meta/model/std/step).
`free_tail` defaults to D2 (True) and can be forced to False by the env var RR_DF_FREE_TAIL=0 so the "this chunk then nothing" ablation can be run WITHOUT a new cell grammar -- the scorer has no flag for it and inventing one would change every other column's argument surface.""" ck = torch.load(str(path), map_location="cpu", weights_only=False) if "meta" not in ck or "model" not in ck: raise RuntimeError(f"{path} is not a train_df.py checkpoint (keys {sorted(ck.keys())})") if free_tail is None: free_tail = os.environ.get("RR_DF_FREE_TAIL", "1") not in ("0", "false", "False") crit = DFCritic(ck, device, free_tail=free_tail) # Accepted and IGNORED, loudly: DF's value is a regression, not a logit, so a temperature is not # defined for it. Silently reading calib.json would make the column look calibrated. if calib not in (None, "auto", "none") or (Path(path).parent / "calib.json").exists(): print(f"[df_readout] temperature calibration does not apply to DF's regression read-out; " f"T=1 (calib={calib!r})", flush=True) return crit123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""DINO-WM read-out: the same best-of-N scorer interface as dwm_readout, with DINO-WM's dynamics.
gen_q#268. The single-actor flagship asks one question -- "same RISE actor, same 128 candidates,same provenance reward, only the value estimator changes" -- so a world-model comparator is onlyworth running if it differs from RSM/DWM in the MODEL and in nothing else. That is why this moduleis 60 lines instead of 600: `DINOWMCritic` SUBCLASSES `dwm_readout.DWMCritic` and overrides exactlytwo methods, the transition and the hop length. The fold algebra, the hop-policy chaining, thereward head, the token normaliser, the temperature calibration and the two-stage rescore are thesame code objects the DWM column runs.
WHAT DINO-WM IS HERE--------------------stable-worldmodel's PreJEPA recipe: frozen DINOv2 ViT-S/14 patch features + a causal transformerthat predicts the next frame's features from the current ones and the action, trained by latent MSE.Our caches already hold exactly those features (cache/<task>/tokens/tok.f16.npy is[N, 514, 384] = 2 cameras x (CLS + 256 patches) from dinov2_vits14 at 224 px), and dwm_model.DWM isalready "the DINO-WM predictor" -- stream C built it as the velocity network of a token-space flow.So DINO-WM is that predictor trained with train_rsm_dwm.py --dynamics latent_mse, and scored here.
TRANSITION. Deterministic: s' = f_theta(s, a), one action chunk ahead. The predictor is queriedat the one fixed point of its flow-time/noise inputs that training used (x_k = 0, k = 0, beta = 0),so the "future" half of its token sequence is a learned query attending to the current frame's patchtokens under the action embedding. There is no ODE and no noise IN THE TRANSITION.
PARTICLES (gen_q#288, corrected 2026-09-25). A deterministic transition does NOT make the ESTIMATORdeterministic. Past the candidate chunk the continuation action comes from the stochastic Gaussianhop head -- the same object RSM chains with -- so at depth > 1 the M particles are M different actionsequences and Q is the mean over them, with common random numbers across candidates (`_q_once` drawseps per particle and tiles it over the rows). This module used to force n_particles = 1 at EVERYdepth, so all 855 published DINO-WM MPC cells requested 16 particles and measured one roll-out. Onlydepth == 1 is truly deterministic and keeps the force. Search cost therefore scales with M and theflagship discloses it; the effective count is in the cell's `planner.scorer.effective_particles` andin the arm key, so a repaired cell cannot pool with an old one.
HOP LENGTH. One DINO-WM hop is `hop_frames` frames (the action chunk the model was trained on, 8 =0.4 s at 20 Hz), whereas an RSM/DWM hop spans 1/(1-beta) frames. The two scorers are thereforematched on the NUMBER of hops, L in {1,2,4,8}, not on beta -- a latent-dynamics model has no beta --and the fold's per-hop discount uses gamma ** hop_frames. L is the only knob this scorer has, whichis why its arm label in verdict_table is "L<depth> N<n>" with no beta in it.
DEVIATIONS FROM THE PAPER, DECLARED-----------------------------------1. History length 1, not 3. Forced by the protocol, not chosen: rsm_planner.plan_get_action hands a scorer the SINGLE current frame (`obs_t = {k: v[:, -1] ...}`), so a history-3 world model cannot be evaluated on the same observation every other scorer sees.2. Two cameras (514 tokens) rather than one, because that is what the RISE observation is and what every other scorer in the table reads.3. Actions enter as the flattened 8-step chunk the RISE actor emits, not per-frame, for the same reason: it is the candidate the planner ranks.4. The reward probe is the checkpoint's own head on the provenance/membership label -- the same label and the same head class RSM's membership read-out uses."""from __future__ import annotations
import jsonfrom pathlib import Path
import torch
# (no direct model construction here: DWMCritic.__init__ builds the predictor and the reward head)from dwm_readout import DWMCritic
class DINOWMCritic(DWMCritic): """DWMCritic with DINO-WM's deterministic latent dynamics instead of the occupancy flow."""
def __init__(self, ck, device, use_ema=True): super().__init__(ck, device, use_ema=use_ema) # frames per hop: the action chunk the model was trained to step over. self.hop_frames = float(ck.get("hop_frames", self.config.get("chunk", 8))) self.dynamics = str(self.config.get("dynamics", "latent_mse"))
def _step(self, tzr, pzr, ar, bq, B, n, g, flow_steps, micro): """s' = f_theta(s, a): one deterministic chunk step, in normalised token space.
Mirrors the training call in train_rsm_dwm._latent_mse_terms exactly -- same zero flow-time, same zero noise input, same zero beta, same residual reparameterisation -- so the model is queried at scoring time at the one point it was fitted at. `micro` still bounds the rows per forward, because N=128 candidates x 514 tokens is the same memory problem the flow path has. """ outs_t, outs_p = [], [] m = max(int(micro), 1) for i in range(0, tzr.shape[0], m): t_i, p_i, a_i = tzr[i:i + m], pzr[i:i + m], ar[i:i + m] zt = torch.zeros_like(t_i) zp = torch.zeros_like(p_i) kz = torch.zeros(t_i.shape[0], device=t_i.device) bz = torch.zeros(t_i.shape[0], device=t_i.device) with self.autocast(): v_tok, v_pr = self.flow(t_i, p_i, a_i, bz, zt, zp, kz) nt = t_i.float() + self.rms_tok * v_tok.float() npr = (p_i.float() + self.rms_pr * v_pr.float()) if v_pr.shape[1] else p_i.float() outs_t.append(nt) outs_p.append(npr) return torch.cat(outs_t, 0), torch.cat(outs_p, 0)
def _hop_frames(self, beta): return self.hop_frames
def n_eff_particles(self, n_particles, depth, mode): """The number of DISTINCT roll-outs a (n_particles, depth, mode) cell actually averages.
Exposed so the eval cell's `planner.scorer` block can record the EFFECTIVE count rather than the requested one, the same self-verifying trick the temperature field already uses: two cells pool in verdict_table's arm key exactly when the estimator they ran was the same, whatever the grid asked for. Before gen_q#288 this class silently collapsed every count to 1, so 855 published DINO-WM cells REQUESTED 16 and MEASURED 1; without this field a re-run at a working M=16 would pool with them. """ d = 1 if mode == "d1" else int(depth or 1) return 1 if d <= 1 else int(n_particles or 1)
def q(self, *a, **kw): """gen_q#288 -- M STOCHASTIC ROLL-OUTS, not one. n_particles is forced to 1 only at depth 1.
The TRANSITION here is deterministic (`_step` above), which is why this override used to force n_particles = 1 unconditionally. That was wrong for every depth > 1 cell, and every published DINO-WM MPC cell is one: past the candidate chunk the continuation comes from the STOCHASTIC Gaussian hop head (`_q_once`'s hop_policy branch draws its own eps per particle), so particles at depth > 1 are genuinely different chains and averaging them is the estimator, exactly as it is for RSM and DWM. Owner, 2026-09-25: "should definitely be M different chains for DINOWM and LeWM with stochastic continuations just like RSM."
At depth == 1 there is no continuation to sample and the roll IS deterministic, so 16 identical roll-outs would burn 16x the compute and report the same number -- that case keeps the force. `mode="d1"` pins depth to 1 inside the parent, so it is resolved here the same way. """ if len(a) > 3: # n_particles/depth/mode passed POSITIONALLY would be invisible to the kw rewrite below and # `kw["n_particles"] = 1` would then be a duplicate argument, so say so instead of guessing. raise TypeError( "dinowm_readout.DINOWMCritic.q takes (x_tokens, a_chunk, beta) positionally; pass " "n_particles / depth / mode by keyword (rsm_scorer.DWMBackend.q already does) -- the " "particle count is rewritten here (gen_q#288) and cannot be read out of *args") mode = kw.get("mode", "d1") depth = kw.get("depth", 1) if self.n_eff_particles(kw.get("n_particles", 16), depth, mode) == 1: if kw.get("n_particles", 1) != 1: kw["n_particles"] = 1 if kw.get("n_particles_rescore"): kw["n_particles_rescore"] = 1 return super().q(*a, **kw)
def load_critic_dwm(path, device="cuda", use_ema=True, calib="auto") -> DINOWMCritic: """Same name and signature as dwm_readout.load_critic_dwm, so this module is a drop-in for the scorer's DWM backend (which imports `load_critic_dwm` from `rsm_dwm_module`).""" ck = torch.load(str(path), map_location="cpu", weights_only=False) m = str(ck.get("model", "dwm")) dyn = dict(ck.get("config", {})).get("dynamics") if m != "dinowm" or dyn != "latent_mse": raise RuntimeError( f"{path} is model={m!r} dynamics={dyn!r}; dinowm_readout needs a checkpoint trained with " f"train_rsm_dwm.py --dynamics latent_mse. A flow DWM must be loaded by " f"dwm_readout.load_critic_dwm -- reading it here would treat a velocity field as a " f"next-state predictor.") crit = DINOWMCritic(ck, device, use_ema=use_ema) if isinstance(calib, (int, float)) and not isinstance(calib, bool): crit.temperature = float(calib) elif calib == "auto": cj = Path(path).parent / "calib.json" if cj.exists(): try: crit.calib = json.loads(cj.read_text()) crit.temperature = float(crit.calib["T"]) except Exception as e: print(f"[dinowm_readout] calib.json unreadable ({e}); T=1", flush=True) return crit123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580"""DWM: the DINO-WM predictor architecture, trained as a beta-discounted SUCCESSOR model.
DINO-WM (gaoyuezhou/dino_wm, conf/predictor/vit.yaml): a ViT (depth 6, 16 heads x 64,MLP 2048, dropout 0.1) over frozen DINOv2 ViT-S/14 patch tokens (384-d) with the action andproprio embeddings CONCATENATED to every token, trained by MSE to the next frame's tokens.
Ours keeps the ViT and changes the target and the objective (LAUNCH_MATRIX rev. 4, "DWM"):
* sequence = 514 "now" tokens (agentview CLS + 256 patches, wrist CLS + 256 patches) + 514 NOISY FUTURE tokens x_k = (1-k) y + k eps, full attention, learned position embedding shared by the two halves + a 2-way TYPE embedding; * y = (x_{t+K} - x_t) / rho, the residual of the z-scored tokens, rho = running per-(token, channel) RMS of the residual (OccFlow's per-dim normalisation); * K ~ Geom(1 - beta), beta ~ U[lo, hi], truncated at the episode end (data.py sampler); * conditioning, concatenated to EVERY token as DINO-WM does: action chunk (8x7=56 -> 16), proprio (9 -> 8), Fourier(log(-log beta)) (-> 8), flow time k sinusoid (8): 384+40 = 424; * output = the flow velocity v = y - eps read at the future positions (LayerNorm+Linear); * reward head R: mean-pooled tokens per camera (2x384) ++ proprio -> MLP 512x2 -> logit.
One documented addition: a 515th "proprio" token per frame (9-d proprio embedded to 384, andits own 9-d residual on the future side, read out by a 424->9 head). The MLP cells model thepooled 1545-d state, which INCLUDES proprio, and the Stage-2 hop policy consumes the pooledstate of the sampled future, so the DWM successor has to predict proprio too. Cost: 2 tokensout of 1030.
No learned encoder: DINO is frozen and its tokens are the state (Stage 1 "no learned encoderin either case")."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import jsonfrom pathlib import Pathimport numpy as npimport torchimport torch.utils.checkpointimport torch.nn as nnimport torch.nn.functional as F
from model import beta_fourier, time_embedfrom data import truncated_geometric_future
# token layout of cache/<task>/tokens/tok.f16.npy [N, 514, 384]N_PATCH = 256D_TOK = 384TOK_LAYOUT = {"agent_cls": 0, "agent_patch": (1, 1 + N_PATCH), "wrist_cls": 1 + N_PATCH, "wrist_patch": (2 + N_PATCH, 2 + 2 * N_PATCH)}N_TOK = 2 + 2 * N_PATCH # 514# Stage-1 state normalisation rule (orchestrator, 2026-09-18; B_stage1.md "STATE DEFINITION (final)"):# x = clip((feat - mu) / max(sd, SD_FLOOR), -Z_CLIP, Z_CLIP) -- same floor/clip for pooled and token space# and the residual RMS rho is floored at RHO_FLOOR; the normalised residual y is clipped to +-Y_CLIP so a dead# channel (sd at the floor, delta up to 2*Z_CLIP) can never blow up the flow target.SD_FLOOR = 0.01Z_CLIP = 10.0RHO_FLOOR = 0.01Y_CLIP = 10.0STATS_VERSION = 2
# --------------------------------------------------------------------------- ## pooled 1545-d state from tokens (RISE's DinoV2Core(concatenate=True) ++ proprio)# --------------------------------------------------------------------------- #def gem_pool(patches: torch.Tensor, p: float = 4.0, eps: float = 1e-6) -> torch.Tensor: """GeM over the patch axis exactly as robomimic/models/obs_core.py DinoV2Core does: clamp(min=1e-6) -> mean over the 16x16 grid of x^4 -> ^(1/4). patches [..., 256, 384].""" return patches.clamp(min=eps).pow(p).mean(-2).pow(1.0 / p)
def pool_tokens(tokens: torch.Tensor, proprio: torch.Tensor | None = None) -> torch.Tensor: """[B, 514, 384] RAW DINO tokens (+ [B, 9] proprio) -> [B, 1536 (+9)] pooled state = [agent CLS ‖ GeM(agent patches) ‖ wrist CLS ‖ GeM(wrist patches)] ‖ proprio, i.e. what cache/<task>/z.f16.npy ‖ proprio.f32.npy holds (un-normalised).""" t = tokens.float() a0, (a1, a2) = TOK_LAYOUT["agent_cls"], TOK_LAYOUT["agent_patch"] w0, (w1, w2) = TOK_LAYOUT["wrist_cls"], TOK_LAYOUT["wrist_patch"] parts = [t[:, a0], gem_pool(t[:, a1:a2]), t[:, w0], gem_pool(t[:, w1:w2])] if proprio is not None: parts.append(proprio.float()) return torch.cat(parts, -1)
# --------------------------------------------------------------------------- ## data: the pooled pack's meta/actions/proprio/labels + the token memmap# --------------------------------------------------------------------------- #class TokenRSMData: """Same episode split, reward label and future sampler as data.LiberoRSMData, but the state is the [514, 384] token frame from <cache>/tokens/tok.f16.npy (memmap; the page cache is shared by the 8 DDP ranks on a node). Frame order = the pooled pack's."""
def __init__(self, root, chunk: int = 8, val_frac: float = 0.1, seed: int = 0, reward_mode: str = "dense", success_gamma: float = 0.98, in_ram: bool = False, tokens_file: str = "", goal_file: str = "", tok_rows: str = "", reward_npy: str = "", val_eps_json: 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:]) if val_eps_json: # COOKV7_DINOWM (2026-10-31): explicit plan split, same rule as data.LiberoRSMData(val_eps_json=...) # (episodes with split=='valid' -> val). Applied after the seeded permutation; unset = bit-identical. _sp = json.load(open(val_eps_json))["episodes"] assert len(_sp) == self.n_ep, f"{val_eps_json}: {len(_sp)} episodes vs cache {self.n_ep}" _lens = np.array([int(_sp[str(i)]["length"]) for i in range(self.n_ep)]) assert (_lens == self.ep_len).all(), f"{val_eps_json}: episode lengths differ from cache" self.val_eps = np.array(sorted(i for i in range(self.n_ep) if _sp[str(i)]["split"] == "valid"), np.int64) self.train_eps = np.sort(np.setdiff1d(np.arange(self.n_ep), self.val_eps)) print(f"[data] split from {val_eps_json}: {len(self.val_eps)} val / {len(self.train_eps)} train", flush=True)
# 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") if reward_npy: # COOKV7_DINOWM (2026-10-31): external per-frame label, same rule as data.LiberoRSMData(reward_npy=...) # (replaces the episode-level dense label; unset = bit-identical). _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) self.stats = self._fit_stats()
# ---- normalisation statistics (per token position x channel; per proprio dim) ---- def _fit_stats(self, stride: int = 97): # With a row map the token file belongs to the PARENT task, so its tok_stats.npz describes # the parent's frame distribution, not ours. Fit and cache our own, in our own cache dir. f = (self.root / "tokens" / "tok_stats.npz") if self.tok_rows is not None \ else self.tok_path.parent / "tok_stats.npz" f.parent.mkdir(parents=True, exist_ok=True) n = int(self.ep_to[-1]) if f.exists(): try: c = np.load(f) if c["mu"].shape == (N_TOK, D_TOK) and int(c["version"]) == STATS_VERSION \ and float(c["sd_floor"]) == SD_FLOOR and float(c["z_clip"]) == Z_CLIP: print(f"[data] token normalisation loaded from {f} (sd floor {SD_FLOOR}, clip {Z_CLIP})", flush=True) return {k: c[k] for k in ("mu", "sd", "pr_mu", "pr_sd")} print(f"[data] token stats {f} are an older version; refitting", flush=True) except Exception as e: # a half-written file from a concurrent job: refit print(f"[data] token stats unreadable ({e}); refitting", flush=True) idx = np.arange(0, n, max(1, min(stride, max(n // 64, 1)))) x = np.asarray(self.tok[self._rows(idx)], np.float32) mu = x.mean(0); sd_raw = x.std(0); sd = np.maximum(sd_raw, SD_FLOOR) if self.proprio is not None: p = np.asarray(self.proprio[idx], np.float32) pr_mu, pr_sd = p.mean(0), np.maximum(p.std(0), SD_FLOOR) else: pr_mu = np.zeros(0, np.float32); pr_sd = np.ones(0, np.float32) st = {"mu": mu.astype(np.float32), "sd": sd.astype(np.float32), "pr_mu": pr_mu.astype(np.float32), "pr_sd": pr_sd.astype(np.float32)} n_floor = int((sd_raw < SD_FLOOR).sum()) try: tmp = f.with_name(f"tok_stats.{_os.getpid()}.tmp.npz") np.savez(tmp, n=len(idx), version=STATS_VERSION, sd_floor=SD_FLOOR, z_clip=Z_CLIP, rho_floor=RHO_FLOOR, y_clip=Y_CLIP, sd_raw=sd_raw.astype(np.float32), **st) _os.replace(tmp, f) # atomic: concurrent jobs (f.parent / "TOK_STATS.json").write_text(json.dumps({ "file": "tok_stats.npz", "version": STATS_VERSION, "n_frames": int(len(idx)), "stride": int(idx[1] - idx[0]) if len(idx) > 1 else 1, "rule": "x = clip((tok - mu) / max(sd, sd_floor), -z_clip, z_clip), per (token position, channel); " "proprio: per dim, same floor/clip", "sd_floor": SD_FLOOR, "z_clip": Z_CLIP, "residual": "y = clip((x_fut - x_now) / max(rho, rho_floor), -y_clip, y_clip), rho = running " "per-(token, channel) RMS of the residual", "rho_floor": RHO_FLOOR, "y_clip": Y_CLIP, "n_token_channels_at_sd_floor": n_floor, "sd_raw_min": float(sd_raw.min()), "sd_raw_p01": float(np.percentile(sd_raw, 1)), "abs_z_max_on_fit_frames": float(np.abs((x - mu) / sd).max())}, indent=1)) print(f"[data] token normalisation fitted on {len(idx)} frames -> {f} " f"({n_floor} token-channels at the sd floor {SD_FLOOR}; z clipped to +-{Z_CLIP})", flush=True) except OSError as e: print(f"[data] token normalisation fitted but not cached ({e})", flush=True) return st
def _chunk_at(self, idx, ep_i, chunk_len=None): cl = self.chunk if chunk_len is None else chunk_len out = np.empty((len(idx), cl * self.adim), np.float32) for j, (t, e) in enumerate(zip(idx, ep_i)): hi = int(self.ep_to[e]); take = min(cl, hi - t) a = np.asarray(self.act[t:t + take], np.float32) if take < cl: a = np.concatenate([a, np.repeat(a[-1:], cl - take, 0)], 0) out[j] = a.reshape(-1) return out
def _rows(self, idx): """cache frame indices -> rows of the token file (identity unless a row map is in use).""" return idx if self.tok_rows is None else self.tok_rows[idx]
def _tok(self, idx): """RAW fp16 tokens for a set of rows (gathered in sorted order for locality).""" idx = self._rows(np.asarray(idx, np.int64)) order = np.argsort(idx, kind="stable") g = np.asarray(self.tok[idx[order]]) out = np.empty_like(g); out[order] = g return out
def _pr(self, idx): if self.proprio is None: return np.zeros((len(idx), 0), np.float32) return np.asarray(self.proprio[idx], np.float32)
def draw(self, batch, rng, beta_lo, beta_hi, split="train"): """Index-level draw (no I/O): the (t, K, beta) tuple per row.""" eps_pool = self.train_eps if split == "train" else self.val_eps w = self.ep_len[eps_pool].astype(np.float64); w /= w.sum() e = rng.choice(eps_pool, size=batch, p=w) lo = self.ep_from[e]; hi = self.ep_to[e] t = lo + (rng.random(batch) * (hi - lo)).astype(np.int64) beta = rng.uniform(beta_lo, beta_hi, size=batch) fut = truncated_geometric_future(t, hi, beta, rng.random(batch)) return e, t, fut, beta
def gather(self, e, t, fut, beta, with_fut=True): """CPU tensors for a draw. Tokens stay fp16 (normalised on the device).""" out = {"tok_now": torch.from_numpy(self._tok(t)), "pr_now": torch.from_numpy(self._pr(t)), "a_now": torch.from_numpy(self._chunk_at(t, e)), "task": torch.from_numpy(self.ep_task[e]).long(), "beta": torch.from_numpy(np.asarray(beta)).float(), "r_now": torch.from_numpy(self.r[t]), "succ": torch.from_numpy(self.ep_success[e].astype(np.float32)), "to_end": torch.from_numpy((self.ep_to[e] - t).astype(np.float32)), "t_idx": t, "ep": e, "fut_idx": fut} if with_fut: out["tok_fut"] = torch.from_numpy(self._tok(fut)) out["pr_fut"] = torch.from_numpy(self._pr(fut)) out["r_fut"] = torch.from_numpy(self.r[fut]) return out
def sample(self, batch, rng, beta_lo, beta_hi, split="train", device="cpu"): e, t, fut, beta = self.draw(batch, rng, beta_lo, beta_hi, split) b = self.gather(e, t, fut, beta) return {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v) for k, v in b.items()}
def sample_frames(self, batch, rng, split="train", device="cpu"): e, t, _, _ = self.draw(batch, rng, 0.5, 0.5, split) b = self.gather(e, t, t, np.zeros(batch), with_fut=False) b["x"] = b.pop("tok_now"); b["a"] = b.pop("a_now"); b["r"] = b.pop("r_now") return {k: (v.to(device, non_blocking=True) if torch.is_tensor(v) else v) for k, v in b.items()}
class Normalizer(nn.Module): """z-scoring of raw tokens / proprio, stored in the checkpoint as buffers."""
def __init__(self, stats): super().__init__() self.register_buffer("mu", torch.as_tensor(stats["mu"], dtype=torch.float32)) self.register_buffer("sd", torch.as_tensor(stats["sd"], dtype=torch.float32)) self.register_buffer("pr_mu", torch.as_tensor(stats["pr_mu"], dtype=torch.float32)) self.register_buffer("pr_sd", torch.as_tensor(stats["pr_sd"], dtype=torch.float32))
def tok(self, x): # raw -> z-scored, sd floored (in the stats) and clipped return ((x.float() - self.mu) / self.sd.clamp_min(SD_FLOOR)).clamp(-Z_CLIP, Z_CLIP)
def tok_inv(self, z): # z-scored -> raw return z.float() * self.sd.clamp_min(SD_FLOOR) + self.mu
def pr(self, p): return ((p.float() - self.pr_mu) / self.pr_sd.clamp_min(SD_FLOOR)).clamp(-Z_CLIP, Z_CLIP)
def pr_inv(self, z): return z.float() * self.pr_sd.clamp_min(SD_FLOOR) + self.pr_mu
# --------------------------------------------------------------------------- ## the DINO-WM ViT (vit-pytorch style: PreNorm, Attention, FeedForward, dropout)# --------------------------------------------------------------------------- #class Attention(nn.Module): def __init__(self, dim, heads=16, dim_head=64, dropout=0.0): super().__init__() inner = heads * dim_head self.heads, self.dim_head, self.dropout = heads, dim_head, dropout self.norm = nn.LayerNorm(dim) self.to_qkv = nn.Linear(dim, inner * 3, bias=False) self.to_out = nn.Sequential(nn.Linear(inner, dim), nn.Dropout(dropout))
def forward(self, x): B, N, _ = x.shape q, k, v = self.to_qkv(self.norm(x)).chunk(3, -1) q, k, v = (t.view(B, N, self.heads, self.dim_head).transpose(1, 2) for t in (q, k, v)) o = F.scaled_dot_product_attention(q, k, v, dropout_p=self.dropout if self.training else 0.0) return self.to_out(o.transpose(1, 2).reshape(B, N, -1))
class FeedForward(nn.Module): def __init__(self, dim, hidden, dropout=0.0): super().__init__() self.net = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, hidden), nn.GELU(), nn.Dropout(dropout), nn.Linear(hidden, dim), nn.Dropout(dropout))
def forward(self, x): return self.net(x)
class Transformer(nn.Module): def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout=0.0, grad_ckpt=False): super().__init__() self.layers = nn.ModuleList([nn.ModuleList([Attention(dim, heads, dim_head, dropout), FeedForward(dim, mlp_dim, dropout)]) for _ in range(depth)]) self.norm = nn.LayerNorm(dim) self.grad_ckpt = grad_ckpt
@staticmethod def _block(attn, ff, x): x = x + attn(x) return x + ff(x)
def forward(self, x): for attn, ff in self.layers: if self.grad_ckpt and self.training and torch.is_grad_enabled(): x = torch.utils.checkpoint.checkpoint(self._block, attn, ff, x, use_reentrant=False) else: x = self._block(attn, ff, x) return self.norm(x)
class DWM(nn.Module): """Successor flow in token space with the DINO-WM predictor as the velocity network."""
def __init__(self, n_tok=N_TOK, d_tok=D_TOK, n_pr=9, d_act=56, depth=6, heads=16, dim_head=64, mlp_dim=2048, dropout=0.1, d_act_emb=16, d_pr_emb=8, d_beta_emb=8, d_time_emb=8, n_fourier=6, emb_dropout=0.1, grad_ckpt=False, tok_drop=0.0): super().__init__() self.tok_drop = tok_drop # training-time dropout of WHOLE "now" tokens (regulariser probe) self.n_tok, self.d_tok, self.n_pr, self.d_act = n_tok, d_tok, n_pr, d_act self.d_cond = d_act_emb + d_pr_emb + d_beta_emb + d_time_emb self.dim = d_tok + self.d_cond # 424 self.d_time_emb = d_time_emb; self.n_fourier = n_fourier self.act_emb = nn.Linear(d_act, d_act_emb) self.pr_emb = nn.Linear(max(n_pr, 1), d_pr_emb) self.beta_emb = nn.Linear(2 * n_fourier + 1, d_beta_emb) # the extra proprio token (now: embedded proprio; future: embedded noisy residual) self.pr_tok_now = nn.Linear(max(n_pr, 1), d_tok) self.pr_tok_fut = nn.Linear(max(n_pr, 1), d_tok) self.n_seq = n_tok + 1 self.pos = nn.Parameter(torch.randn(1, self.n_seq, self.dim) * 0.02) self.type_emb = nn.Parameter(torch.randn(2, 1, self.dim) * 0.02) self.drop = nn.Dropout(emb_dropout) self.transformer = Transformer(self.dim, depth, heads, dim_head, mlp_dim, dropout, grad_ckpt) self.head_tok = nn.Linear(self.dim, d_tok) self.head_pr = nn.Linear(self.dim, max(n_pr, 1))
def _cond(self, a, pr, beta, k): c = torch.cat([self.act_emb(a), self.pr_emb(pr if self.n_pr else torch.zeros_like(a[:, :1])), self.beta_emb(beta_fourier(beta.float(), self.n_fourier)), time_embed(k.float(), self.d_time_emb)], -1) return c
def forward(self, tok_now, pr_now, a, beta, xk_tok, xk_pr, k): """tok_now [B,514,384] z-scored; pr_now [B,9] z-scored; a [B,56]; beta [B]; xk_tok [B,514,384] noisy residual; xk_pr [B,9]; k [B] flow time (1 = noise). -> (v_tok [B,514,384], v_pr [B,9])""" B = tok_now.shape[0] pr_in = pr_now if self.n_pr else torch.zeros(B, 1, device=tok_now.device) xk_pr_in = xk_pr if self.n_pr else torch.zeros(B, 1, device=tok_now.device) if self.tok_drop > 0 and self.training: keep = (torch.rand(B, tok_now.shape[1], 1, device=tok_now.device) >= self.tok_drop).to(tok_now.dtype) tok_now = tok_now * keep # dropped token -> 0 = the mean token (z-scored space) now = torch.cat([tok_now, self.pr_tok_now(pr_in)[:, None]], 1) # [B,515,384] fut = torch.cat([xk_tok, self.pr_tok_fut(xk_pr_in)[:, None]], 1) # [B,515,384] c = self._cond(a, pr_in, beta, k)[:, None].expand(-1, self.n_seq, -1) # [B,515,40] now = torch.cat([now, c], -1) + self.pos + self.type_emb[0] fut = torch.cat([fut, c], -1) + self.pos + self.type_emb[1] h = self.transformer(self.drop(torch.cat([now, fut], 1))) # [B,1030,424] hf = h[:, self.n_seq:] v_tok = self.head_tok(hf[:, :self.n_tok]) v_pr = self.head_pr(hf[:, self.n_tok]) return v_tok, (v_pr if self.n_pr else v_pr[:, :0])
class DWMReward(nn.Module): """R(x): mean-pooled tokens per camera (2 x 384) ++ proprio -> MLP 512 x 2 -> logit."""
def __init__(self, n_tok=N_TOK, d_tok=D_TOK, n_pr=9, width=512): super().__init__() self.n_tok, self.n_pr = n_tok, n_pr self.net = nn.Sequential(nn.Linear(2 * d_tok + n_pr, width), nn.SiLU(), nn.Linear(width, width), nn.SiLU(), nn.Linear(width, 1))
@staticmethod def pool(tok): h = tok.shape[1] // 2 return torch.cat([tok[:, :h].mean(1), tok[:, h:].mean(1)], -1)
def forward(self, tok, pr): x = self.pool(tok.float()) if self.n_pr: x = torch.cat([x, pr.float()], -1) return self.net(x).squeeze(-1)
# --------------------------------------------------------------------------- ## sampling# --------------------------------------------------------------------------- #@torch.no_grad()def sample_future_dwm(model, tok_now, pr_now, a, beta, rms_tok, rms_pr, n_steps=8, n=1, x0=None, micro=512, autocast=None, y_clip=Y_CLIP): """Euler ODE sample of the token residual, returned as ABSOLUTE z-scored tokens/proprio. x0: optional (noise_tok [rows,514,384], noise_pr [rows,9]) for common random numbers. autocast: zero-arg callable returning a context manager (default: bf16 on cuda). y_clip: the integrated residual is clamped to +-y_clip (rho units) after every Euler step -- the training target lives in that box, so anything outside it is a diverged velocity, not a successor (stream B measured the MLP flow's velocity growing 170 -> 8500 over 8 steps on held-out episodes; this bounds the damage at read-out). 0 = off. Returns (tok_fut_z [B*n,514,384], pr_fut_z [B*n,9]).""" B = tok_now.shape[0] if n > 1: tok_now = tok_now.repeat_interleave(n, 0); pr_now = pr_now.repeat_interleave(n, 0) a = a.repeat_interleave(n, 0); beta = beta.repeat_interleave(n, 0) R = tok_now.shape[0] dev = tok_now.device if x0 is None: xt = torch.randn(R, model.n_tok, model.d_tok, device=dev) xp = torch.randn(R, model.n_pr, device=dev) else: xt, xp = x0[0].clone(), x0[1].clone() if autocast is None: autocast = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) if dev.type == "cuda" \ else (lambda: torch.autocast("cpu", enabled=False)) for s in range(n_steps): kk = 1.0 - s / n_steps for i in range(0, R, micro): sl = slice(i, i + micro) k = torch.full((xt[sl].shape[0],), kk, device=dev) with autocast(): vt, vp = model(tok_now[sl], pr_now[sl], a[sl], beta[sl], xt[sl], xp[sl], k) xt[sl] = (xt[sl] + vt.float() / n_steps).clamp(-y_clip, y_clip) if y_clip else xt[sl] + vt.float() / n_steps xp[sl] = (xp[sl] + vp.float() / n_steps).clamp(-y_clip, y_clip) if y_clip else xp[sl] + vp.float() / n_steps return tok_now + xt * rms_tok, pr_now + xp * rms_pr
# --------------------------------------------------------------------------- ## synthetic cache with the real layout (tests, and development before stream B's dump)# --------------------------------------------------------------------------- #def make_synthetic_cache(root, n_ep=6, ep_len=(30, 50), seed=0, success_rate=0.5, n_pr=9, adim=7): """Writes meta.npz, act.f32.npy, proprio.f32.npy, z.f16.npy (pooled, via the reference GeM), tokens/tok.f16.npy [N,514,384], tokens/TOKENS.json. Tokens drift smoothly along the episode so a successor has something to learn.""" root = Path(root); (root / "tokens").mkdir(parents=True, exist_ok=True) rng = np.random.default_rng(seed) lens = rng.integers(ep_len[0], ep_len[1] + 1, size=n_ep).astype(np.int64) ep_to = np.cumsum(lens); ep_from = ep_to - lens; N = int(ep_to[-1]) tok = np.lib.format.open_memmap(root / "tokens" / "tok.f16.npy", mode="w+", dtype=np.float16, shape=(N, N_TOK, D_TOK)) act = np.zeros((N, adim), np.float32); pr = np.zeros((N, n_pr), np.float32) base = rng.normal(0, 1, size=(N_TOK, D_TOK)).astype(np.float32) base[1:1 + N_PATCH] = np.abs(base[1:1 + N_PATCH]) + 0.5 # patches mostly positive (GeM) base[2 + N_PATCH:] = np.abs(base[2 + N_PATCH:]) + 0.5 succ = rng.random(n_ep) < success_rate for i in range(n_ep): s, e = int(ep_from[i]), int(ep_to[i]); T = e - s a = np.tanh(rng.normal(0, 0.7, size=(T, adim))).astype(np.float32) a = np.cumsum(a, 0) / np.sqrt(np.arange(1, T + 1))[:, None] # correlated in time act[s:e] = np.clip(a, -1, 1) drift = rng.normal(0, 0.3, size=(D_TOK,)).astype(np.float32) for t in range(T): frac = t / max(T - 1, 1) x = base + frac * drift[None] + 0.05 * rng.normal(size=(N_TOK, D_TOK)).astype(np.float32) x += 0.2 * np.cumsum(act[s:s + t + 1], 0)[-1].sum() * (base > 0) * 0.01 tok[s + t] = x.astype(np.float16) pr[s + t] = np.concatenate([np.cumsum(act[s:s + t + 1, :3], 0)[-1] * 0.05, np.array([1, 0, 0, 0], np.float32), np.array([0.04 - 0.03 * frac, -0.04 + 0.03 * frac])])[:n_pr] tok.flush() # pooled pack with the reference formula (torch avg_pool2d, as obs_core.py) z = np.zeros((N, 4 * D_TOK), np.float16) for i in range(0, N, 64): t = torch.from_numpy(np.asarray(tok[i:i + 64], np.float32)) parts = [] for c0, (p0, p1) in ((TOK_LAYOUT["agent_cls"], TOK_LAYOUT["agent_patch"]), (TOK_LAYOUT["wrist_cls"], TOK_LAYOUT["wrist_patch"])): p = t[:, p0:p1].reshape(t.shape[0], 16, 16, -1).clamp(min=1e-6).permute(0, 3, 1, 2) g = F.avg_pool2d(p.pow(4), (16, 16)).pow(1 / 4).reshape(t.shape[0], -1) parts += [t[:, c0], g] z[i:i + 64] = torch.cat(parts, -1).numpy().astype(np.float16) np.save(root / "z.f16.npy", z) np.save(root / "act.f32.npy", act); np.save(root / "proprio.f32.npy", pr) np.savez(root / "meta.npz", ep_from=ep_from, ep_to=ep_to, ep_len=lens, ep_task=np.zeros(n_ep, np.int64), ep_success=succ, ep_demo=np.zeros(n_ep, bool), tasks=np.array(["synthetic"]), dim=4 * D_TOK, adim=adim, stride=1, n_frames=N) # goal-state label: the last 30 % of frames of every successful episode (env-success-by-replay stand-in) goal = np.zeros(N, np.uint8); first = np.full(n_ep, -1, np.int64) for i in range(n_ep): if succ[i]: s, e = int(ep_from[i]), int(ep_to[i]); first[i] = s + int(0.7 * (e - s)); goal[first[i]:e] = 1 first[i] -= s np.savez(root / "goal.npz", goal=goal, first_success=first, label="synthetic") (root / "tokens" / "TOKENS.json").write_text(json.dumps({ "file": "tok.f16.npy", "shape": [N, N_TOK, D_TOK], "dtype": "float16", "layout": "[agentview CLS, 256 agentview patches, wrist CLS, 256 wrist patches]", "encoder": "synthetic", "synthetic": True}, indent=1)) (root / "PACK.json").write_text(json.dumps({"encoder": "synthetic", "cam_res": 84, "frames": N, "episodes": n_ep, "sd_floor": SD_FLOOR, "z_clip": Z_CLIP}, indent=1)) return root123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""Stage-3 read-out of a DWM checkpoint: Q̄_β(x, A) = E_{x' ~ d_β(.|x, A)}[σ(R(x'))].
from dwm_readout import load_critic_dwm crit = load_critic_dwm("runs/<task>/rsm/DWM/ckpt_best.pt", device) q = crit.q(x_tokens, a_chunk, beta, n_particles=16, crn_seed=0, depth=1, mode="d1", proprio=proprio) # -> [B] in [0, 1]
Inputs are RAW: x_tokens [B, 514, 384] DINOv2 ViT-S/14 tokens at 224 input, in the cache order[agentview CLS, 256 agentview patches, wrist CLS, 256 wrist patches] (fp16/fp32 both fine);proprio [B, 9] = robot0_eef_pos(3) ‖ robot0_eef_quat(4) ‖ robot0_gripper_qpos(2), un-normalised;a_chunk [B, 56] = the next 8 actions flattened (7-d OSC_POSE, in [-1, 1]); beta a float.
mode="d1" one hop from the query chunk, mean over particles of σ(R(x')).mode="fold" is_ope.q_fold's product fold over `depth` hops: hop 1 from the query chunk, hop k+1 from `hop_policy` evaluated on the POOLED 1545-d state of hop k (pool_tokens: [CLS ‖ GeM(patches)] per camera ‖ proprio, RAW units, the same vector cache/<task>/z.f16.npy ‖ proprio.f32.npy holds). Q = c_L; Q = c_k + (1 - c_k) γ^h Q (h = 1/(1-β)), mean over particles. hop_policy(pooled_raw [R, 1545], eps [R, d_act]) -> a_chunk [R, 56]; the caller applies its own feature normalisation (feat_stats.npz) inside that callable. Optional attribute hop_policy.d_act (default 56) sizes the CRN noise eps.
PRIMARY read-out for planning (orchestrator 13:05): the dense expert-membership head with LOGIT averaging, q, q_logit = crit.q(x_tokens, a_chunk, beta, ..., return_logit=True) # rank candidates by q_logitq_logit = mean over particles of R(x'_i) (no sigmoid), which does not saturate/tie at 1.0 the way q does.Temperature: calib_dwm.py fits T on held-out frames -> runs/<task>/rsm/DWM/calib.json; load_critic_dwm reads it(crit.temperature) and q = mean_i sigmoid(logit_i / T); q(..., temperature=T) overrides.Two-stage screening: q(..., n_particles=4, rescore_top=16, n_particles_rescore=64) scores all candidates with 4particles, rescores the top-16 by q_logit with 64 particles, returns full-length arrays.
reward="goal_clf", reward_path="runs/<task>/goal_clf/clf.pt" (PRIVILEGED ABLATION: env success via statereplay, which RISE's baselines never see): the read-out reward is the standalone GOAL-STATEclassifier (train_goal_clf.py; env-success-by-replay label) on the pooled 1545-d state of every sampled futureinstead of the checkpoint's own head; return_logit=True also returns q_logit (mean logit over particles).
Common random numbers: crn_seed seeds a torch.Generator; every particle i draws ONE noisetensor shared by all B rows (candidates), so Q differences between candidates at the samestate are paired (same convention as is_ope.q_fold(crn=True)). Euler ODE with `flow_steps`(8) steps in token space; the EMA weights are used."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))from pathlib import Pathimport numpy as npimport torch
from dwm_model import (DWM, DWMReward, Normalizer, pool_tokens, sample_future_dwm, N_TOK, D_TOK)
class DWMCritic: def __init__(self, ck, device, use_ema=True): a = ck["arch"] self.device = torch.device(device) self.n_pr, self.d_act = int(a["n_pr"]), int(a["d_act"]) self.flow = DWM(a["n_tok"], a["d_tok"], a["n_pr"], a["d_act"], depth=a["depth"], heads=a["heads"], dim_head=a["dim_head"], mlp_dim=a["mlp_dim"], dropout=a["dropout"], emb_dropout=a["dropout"]).to(self.device) self.rew = DWMReward(a["n_tok"], a["d_tok"], a["n_pr"]).to(self.device) self.flow.load_state_dict(ck["flow_ema" if use_ema else "flow"]) self.rew.load_state_dict(ck["rew_ema" if use_ema else "rew"]) self.norm = Normalizer({k: v.numpy() if torch.is_tensor(v) else v for k, v in ck["norm"].items()}).to(self.device) self.rms_tok = ck["rms_tok"].to(self.device); self.rms_pr = ck["rms_pr"].to(self.device) self.config = dict(ck["config"]); self.step = int(ck.get("step", -1)) self.temperature = 1.0; self.calib = None self.q_action_winrate = ck.get("q_action_winrate", float("nan")) for m in (self.flow, self.rew): m.eval() for p in m.parameters(): p.requires_grad_(False) self.autocast = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) if self.device.type == "cuda" \ else (lambda: torch.autocast("cpu", enabled=False))
# ---- helpers ---- def _prep(self, x_tokens, proprio, a_chunk): x = torch.as_tensor(x_tokens).to(self.device) assert x.ndim == 3 and x.shape[1:] == (N_TOK, D_TOK), f"x_tokens must be [B,{N_TOK},{D_TOK}], got {tuple(x.shape)}" B = x.shape[0] if self.n_pr: assert proprio is not None, "this checkpoint models proprio: pass proprio=[B, 9]" p = torch.as_tensor(proprio).to(self.device).float().view(B, self.n_pr) else: p = torch.zeros(B, 0, device=self.device) a = torch.as_tensor(a_chunk).to(self.device).float().view(B, -1) assert a.shape[1] == self.d_act, f"a_chunk must be [B,{self.d_act}] (chunk x adim flattened)" return self.norm.tok(x), self.norm.pr(p), a
@torch.no_grad() def reward(self, x_tokens, proprio=None, reward="head", reward_path=None): """σ(R(x)) on RAW tokens/proprio -> [B]; reward='goal_clf' uses the goal classifier.""" tz, pz, _ = self._prep(x_tokens, proprio, torch.zeros(len(x_tokens), self.d_act)) if reward == "goal_clf": if reward_path is not None and getattr(self, "goal_clf", {}).get("path") != str(reward_path): self.load_goal_clf(reward_path) return torch.sigmoid(self.goal_logit(tz, pz)) with self.autocast(): return torch.sigmoid(self.rew(tz, pz).float())
@torch.no_grad() def sample_future(self, x_tokens, a_chunk, beta, proprio=None, n=1, crn_seed=None, flow_steps=8, micro=512): """Raw-unit successor samples: (tokens [B*n,514,384], proprio [B*n,9]).""" tz, pz, a = self._prep(x_tokens, proprio, a_chunk) B = tz.shape[0] bq = torch.full((B,), float(beta), device=self.device) x0 = self._crn_noise(B, n, crn_seed) if crn_seed is not None else None xt, xp = sample_future_dwm(self.flow, tz, pz, a, bq, self.rms_tok, self.rms_pr, flow_steps, n=n, x0=x0, micro=micro, autocast=self.autocast) return self.norm.tok_inv(xt), self.norm.pr_inv(xp)
# ---- goal-state classifier read-out (orchestrator 2026-09-18: R must be a goal classifier) ---- def load_goal_clf(self, path): """train_goal_clf.py checkpoint: MLP on the pooled z-scored state; cached on the critic.""" ck = torch.load(str(path), map_location="cpu", weights_only=False) c = ck["config"] from train_goal_clf import build_net net = build_net(c["d_in"], c["width"], c["depth"]).to(self.device) net.load_state_dict(ck["net"]); net.eval() for p in net.parameters(): p.requires_grad_(False) nm = ck["norm"] self.goal_clf = {"net": net, "mu": nm["mu"].to(self.device), "sd": nm["sd"].to(self.device), "z_clip": float(nm["z_clip"]), "sd_floor": float(nm.get("sd_floor", 0.01)), "path": str(path), "config": c} return self.goal_clf
def goal_logit(self, tz, pz): """logit of 'goal state' for z-scored token/proprio tensors (sampled futures or real frames).""" g = self.goal_clf pooled = pool_tokens(self.norm.tok_inv(tz), self.norm.pr_inv(pz) if self.n_pr else None) # raw 1545 x = (pooled - g["mu"]) / g["sd"].clamp_min(g["sd_floor"]) if g["z_clip"]: x = x.clamp(-g["z_clip"], g["z_clip"]) return g["net"](x).squeeze(-1).float()
def _gen(self, seed): g = torch.Generator(device=self.device); g.manual_seed(int(seed)); return g
def _crn_noise(self, B, n, seed, gen=None): """[n, ...] noise per particle, tiled over the B rows (rows are repeat_interleave'd by particle, so particle i of row b sits at b*n + i -> tile with .repeat(B, ...)).""" g = gen if gen is not None else self._gen(seed) nt = torch.randn(n, N_TOK, D_TOK, device=self.device, generator=g).repeat(B, 1, 1) npr = torch.randn(n, self.n_pr, device=self.device, generator=g).repeat(B, 1) return nt, npr
@torch.no_grad() def q(self, x_tokens, a_chunk, beta, n_particles=16, crn_seed=0, depth=1, mode="d1", proprio=None, hop_policy=None, gamma=0.99, flow_steps=8, micro=512, return_hops=False, reward="head", reward_path=None, return_logit=False, temperature=None, rescore_top=0, n_particles_rescore=0): """Q̄ estimate per row. See the module docstring. reward="head": the checkpoint's own reward head R (trained on the run's --reward-mode label). reward="goal_clf": the standalone goal-state classifier (train_goal_clf.py; PRIVILEGED ablation) on the POOLED state of each sampled future; reward_path = its clf.pt (loaded once and cached). temperature: q = mean_i sigmoid(logit_i / T). None -> self.temperature (calib.json next to the checkpoint, fitted by calib_dwm.py on held-out frames; 1.0 if absent). q_logit is the RAW mean logit (ranking is T-free). rescore_top=K, n_particles_rescore=M: two-stage screening -- score every candidate with n_particles, keep the top-K by q_logit, rescore those with M particles (CRN seed family crn_seed -> crn_seed*7919+1) and write the rescored values back; non-rescored rows keep their stage-1 values. Full-length outputs. return_logit=True -> (q, q_logit); return_hops=True -> (out, [c_k [B, n]]) of the stage-1 pass.""" if reward == "goal_clf": if reward_path is not None and getattr(self, "goal_clf", {}).get("path") != str(reward_path): self.load_goal_clf(reward_path) assert getattr(self, "goal_clf", None), "reward='goal_clf' needs reward_path=<clf.pt> once" elif reward != "head": raise ValueError(f"reward {reward!r}: use 'head' or 'goal_clf'") if mode == "d1": depth = 1 elif mode not in ("fold", "mpc", "mpc_disc"): # gen_q#273: "mpc" / "mpc_disc" are the MPC read-outs -- the SAME open-loop roll-out the fold # performs, combined differently (terminal latent / discounted sum) instead of through the # beta-hazard fold. Additive: "d1" and "fold" take byte-identical code paths. raise ValueError(f"mode {mode!r}: use 'd1', 'fold', 'mpc' or 'mpc_disc'") if depth > 1 and hop_policy is None: raise ValueError("depth > 1 needs hop_policy(pooled_raw [R,1545], eps [R,d_act]) -> a_chunk") T = float(self.temperature if temperature is None else temperature) tz, pz, a = self._prep(x_tokens, proprio, a_chunk) q, ql, cs = self._q_once(tz, pz, a, beta, int(n_particles), self._gen(crn_seed), depth, mode, hop_policy, gamma, flow_steps, micro, reward, T) if rescore_top and n_particles_rescore and rescore_top < tz.shape[0]: top = torch.topk(ql, int(rescore_top)).indices q2, ql2, _ = self._q_once(tz[top], pz[top], a[top], beta, int(n_particles_rescore), self._gen(int(crn_seed) * 7919 + 1), depth, mode, hop_policy, gamma, flow_steps, micro, reward, T) q = q.clone(); ql = ql.clone(); q[top] = q2; ql[top] = ql2 out = (q, ql) if return_logit else q if return_hops: return out, cs return out
# ---- the two things a different dynamics model has to change (gen_q#268) ------------------- # Factored out so DINO-WM (dinowm_readout.DINOWMCritic) can subclass this class and override # ONLY the transition and the hop length, exactly as TDFlowAgent subclasses RSMAgent to override # only the occupancy target. Everything else -- the fold algebra, the hop-policy chaining, the # reward head, the normaliser, the temperature, the two-stage rescore -- is then literally the # same code, which is what makes the two columns of a matched-proposer table comparable. def _step(self, tzr, pzr, ar, bq, B, n, g, flow_steps, micro): """One hop: a DRAW from the beta-discounted successor, by Euler-integrating the flow.""" x0 = self._crn_noise(B, n, None, gen=g) return sample_future_dwm(self.flow, tzr, pzr, ar, bq, self.rms_tok, self.rms_pr, flow_steps, n=1, x0=x0, micro=micro, autocast=self.autocast)
def _hop_frames(self, beta): """Frames one hop spans, for the fold's per-hop discount gamma ** h.""" return 1.0 / (1.0 - float(beta))
def _q_once(self, tz, pz, a, beta, n, g, depth, mode, hop_policy, gamma, flow_steps, micro, reward, T): B = tz.shape[0] tzr = tz.repeat_interleave(n, 0); pzr = pz.repeat_interleave(n, 0); ar = a.repeat_interleave(n, 0) bq = torch.full((B * n,), float(beta), device=self.device) cs = [] for k in range(depth): tzr, pzr = self._step(tzr, pzr, ar, bq, B, n, g, flow_steps, micro) with self.autocast(): lg = self.goal_logit(tzr, pzr) if reward == "goal_clf" else self.rew(tzr, pzr).float() cs.append(torch.sigmoid(lg / T)) if k == depth - 1: break pooled = pool_tokens(self.norm.tok_inv(tzr), self.norm.pr_inv(pzr) if self.n_pr else None) d_act = int(getattr(hop_policy, "d_act", self.d_act)) eps = torch.randn(n, d_act, device=self.device, generator=g).repeat(B, 1) ar = torch.as_tensor(hop_policy(pooled, eps)).to(self.device).float().view(B * n, -1) assert ar.shape[1] == self.d_act, "hop_policy must return [R, chunk*adim] chunks" if mode == "d1": q = cs[0] elif mode in ("mpc", "mpc_disc"): # gen_q#273 -- MPC READ-OUTS. `cs[k]` is the reward head on the latent the model predicts # after k+1 chunks of open-loop rolling, so the roll-out itself is unchanged; only the way the # per-step rewards are combined differs from the fold above. # mpc : the TERMINAL latent only -- score(s_K), K = depth chunks = the H frames the # discount defines. This is what a world-model MPC objective is. # mpc_disc : the discounted sum over the same roll-out with the SAME gamma that defines H, # normalised by sum_k gamma**(h k) so it stays a probability in [0, 1] and is # comparable ACROSS horizons (an unnormalised sum grows with K and would rank # longer horizons higher for arithmetic reasons alone). h = self._hop_frames(beta) if mode == "mpc": q = cs[-1] else: w = [float(gamma) ** (h * k) for k in range(len(cs))] tot = float(sum(w)) q = sum(wk * c for wk, c in zip(w, cs)) / tot else: h = self._hop_frames(beta) q = torch.zeros_like(cs[-1]) for c in reversed(cs): q = c + (1.0 - c) * (gamma ** h) * q q = torch.nan_to_num(q, nan=0.0).clamp(0.0, 1.0).view(B, n).mean(1) q_logit = torch.nan_to_num(lg, nan=0.0).view(B, n).mean(1) return q, q_logit, [c.view(B, n) for c in cs]
def load_critic_dwm(path, device="cuda", use_ema=True, calib="auto") -> DWMCritic: """calib: "auto" reads <dir of path>/calib.json (calib_dwm.py) and sets crit.temperature = T if present; a float sets T directly; None/False leaves T = 1.0.""" ck = torch.load(str(path), map_location="cpu", weights_only=False) _m = str(ck.get("model", "dwm")) if _m != "dwm": raise RuntimeError( f"{path} is a '{_m}' checkpoint (config dynamics=" f"{dict(ck.get('config', {})).get('dynamics')!r}), not a flow DWM. Load it with the " f"read-out for that model (dinowm_readout.load_critic_dwm) -- Euler-integrating a " f"network that was never trained as a velocity field would report a number that is " f"neither method.") crit = DWMCritic(ck, device, use_ema=use_ema) if isinstance(calib, (int, float)) and not isinstance(calib, bool): crit.temperature = float(calib) elif calib == "auto": cj = Path(path).parent / "calib.json" if cj.exists(): try: import json crit.calib = json.loads(cj.read_text()); crit.temperature = float(crit.calib["T"]) except Exception as e: print(f"[dwm_readout] calib.json unreadable ({e}); T=1", flush=True) return crit
# --------------------------------------------------------------------------- #@torch.no_grad()def verify_pooling(cache_dir, n=512, seed=0, tokens_file=""): """pool_tokens(tokens, proprio) vs the pooled pack z.f16.npy ‖ proprio.f32.npy on n random frames. Returns dict(max_abs, max_rel, fp16_ok). fp16_ok: every |diff| <= 2 fp16 ulps of the stored value (the pack is fp16-rounded; the pooling itself is fp32).""" cache_dir = Path(cache_dir) z = np.load(cache_dir / "z.f16.npy", mmap_mode="r") pr = np.load(cache_dir / "proprio.f32.npy", mmap_mode="r") if (cache_dir / "proprio.f32.npy").exists() else None tf = Path(tokens_file) if tokens_file else cache_dir / "tokens" / "tok.f16.npy" tok = np.load(tf, mmap_mode="r") assert tok.shape[0] == z.shape[0], f"tokens {tok.shape[0]} frames vs pooled {z.shape[0]}" rng = np.random.default_rng(seed) idx = np.sort(rng.choice(tok.shape[0], size=min(n, tok.shape[0]), replace=False)) t = torch.from_numpy(np.asarray(tok[idx], np.float32)) p = torch.from_numpy(np.asarray(pr[idx], np.float32)) if pr is not None else None got = pool_tokens(t, p).numpy() ref = np.asarray(z[idx], np.float32) if p is not None: ref = np.concatenate([ref, p.numpy()], -1) assert got.shape == ref.shape, f"pooled dim {got.shape[1]} vs pack {ref.shape[1]}" diff = np.abs(got - ref) ulp = np.abs(np.asarray(ref, np.float16)).astype(np.float32) * 2 ** -10 + 1e-6 ok = bool((diff <= 2 * ulp + 1e-4).all()) return {"n": int(len(idx)), "dim": int(got.shape[1]), "max_abs": float(diff.max()), "max_rel": float((diff / (np.abs(ref) + 1e-3)).max()), "fp16_ok": ok, "frac_within_2ulp": float((diff <= 2 * ulp + 1e-4).mean())}
if __name__ == "__main__": import argparse, json ap = argparse.ArgumentParser(description="verify pool_tokens against the pooled pack") ap.add_argument("--cache", required=True); ap.add_argument("--n", type=int, default=512) ap.add_argument("--tokens", default="") a = ap.parse_args() print(json.dumps(verify_pooling(a.cache, a.n, tokens_file=a.tokens), indent=1))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Cost of one planning step with the DWM read-out at N=128 candidates (orchestrator, 13:20 UTC).
One real held-out state (tokens + proprio) and 128 candidate 8-step chunks; times (CUDA-synchronised, median of--reps) for flat n_particles in {4, 16, 64} and for the two-stage screen (4 -> top-16 x 64), in d1 mode, plus theagreement between the rankings. Candidates: `--chunks hop` loads stream B's hop head (runs/<task>/hop/flow) if itsloader is importable, else (default `logged`) 128 logged chunks from 128 random frames of the val split -- the timingdoes not depend on which chunks are used. Writes <out>/readout_timing.json."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, json, timefrom pathlib import Pathimport numpy as npimport torch
from dwm_model import TokenRSMDatafrom dwm_readout import load_critic_dwm
def timed(fn, reps, dev): fn() # warm-up (compile/caches) ts = [] for _ in range(reps): if dev.type == "cuda": torch.cuda.synchronize() t0 = time.time(); out = fn() if dev.type == "cuda": torch.cuda.synchronize() ts.append(time.time() - t0) return float(np.median(ts)), out
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True); ap.add_argument("--ckpt", required=True) ap.add_argument("--n-cand", type=int, default=128); ap.add_argument("--reps", type=int, default=3) ap.add_argument("--beta", type=float, default=0.95); ap.add_argument("--micro", type=int, default=512) ap.add_argument("--seed", type=int, default=0); ap.add_argument("--out", default="") a = ap.parse_args() dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") d = TokenRSMData(a.cache, chunk=8, seed=a.seed) crit = load_critic_dwm(a.ckpt, dev) rng = np.random.default_rng(a.seed) fb = d.sample_frames(1, rng, "val"); cb = d.sample_frames(a.n_cand, rng, "val") N = a.n_cand x = torch.as_tensor(fb["x"]).expand(N, -1, -1).contiguous(); pr = torch.as_tensor(fb["pr_now"]).expand(N, -1).contiguous() a_c = cb["a"] res = {"n_cand": N, "beta": a.beta, "device": torch.cuda.get_device_name(0) if dev.type == "cuda" else "cpu", "ckpt": a.ckpt, "step": crit.step, "temperature": crit.temperature, "micro": a.micro, "reps": a.reps} outs = {} for n in (4, 16, 64): t, (q, ql) = timed(lambda: crit.q(x, a_c, a.beta, n_particles=n, crn_seed=0, proprio=pr, micro=a.micro, return_logit=True), a.reps, dev) outs[n] = ql.cpu().numpy() res[f"flat_{n}_particles_s"] = t res[f"flat_{n}_q_mean"] = float(q.mean()); res[f"flat_{n}_q_max"] = float(q.max()) res[f"flat_{n}_frac_q_gt_0.99"] = float((q > 0.99).float().mean()) print(f"[timing] flat n={n}: {t:.3f} s for {N} candidates ({N*n*8} ViT forwards); q mean {float(q.mean()):.3f} " f"max {float(q.max()):.3f} frac>0.99 {float((q > 0.99).float().mean()):.3f}", flush=True) t, (q2, ql2) = timed(lambda: crit.q(x, a_c, a.beta, n_particles=4, rescore_top=16, n_particles_rescore=64, crn_seed=0, proprio=pr, micro=a.micro, return_logit=True), a.reps, dev) res["two_stage_4_top16_64_s"] = t top64 = set(np.argsort(-outs[64])[:16].tolist()); top2 = set(np.argsort(-ql2.cpu().numpy())[:16].tolist()) top4 = set(np.argsort(-outs[4])[:16].tolist()) res["top16_overlap_two_stage_vs_flat64"] = len(top64 & top2) / 16 res["top16_overlap_flat4_vs_flat64"] = len(top64 & top4) / 16 res["argmax_agree_two_stage_vs_flat64"] = bool(int(np.argmax(outs[64])) == int(torch.argmax(ql2))) res["spearman_flat4_vs_flat64"] = float(np.corrcoef(np.argsort(np.argsort(outs[4])), np.argsort(np.argsort(outs[64])))[0, 1]) print(f"[timing] two-stage 4 -> top16 x 64: {t:.3f} s; top-16 overlap with flat-64 {res['top16_overlap_two_stage_vs_flat64']:.2f} " f"(flat-4 alone {res['top16_overlap_flat4_vs_flat64']:.2f}); spearman flat4/flat64 {res['spearman_flat4_vs_flat64']:.3f}", flush=True) out = Path(a.out) if a.out else Path(a.ckpt).parent / "readout_timing.json" out.write_text(json.dumps(res, indent=1)); print(f"[timing] -> {out}", flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Encode RLinf LeRobot parquet rollouts straight from their RECORDED frames into theper-episode npz the cache packer consumes (z fp16 [T,4096], proprio [T,8], actions [T,7],success, prompt, task_index) -- no re-rendering, no EGL.
The recorded frames ARE the evaluation environment's frames (the collector renders atcam_res 256 and RLinf stores them upright, i.e. already in the evaluator's servingorientation), and the parquet `state` equals the evaluator's proprio exactly (checked:max |state - proprio| = 0 on the existing corpus). The encoder is whatever OGPO_PI05_BASEpoints at, so this is how a LIBERO-finetuned pi0.5 (lerobot/pi05_libero_base) becomes thefeature encoder for a new cache; the tag is recorded in every episode.
usage: OGPO_PI05_BASE=<ckpt dir> encode_parquet.py --root <collect root> --out <corpus dir> [--shard i --num-shards n] [--task-file lib10_tasks.txt]Layout in: <root>/task{t}_block{b}/rank_*/id_{i}/data/chunk-*/episode_{k:06d}.parquetLayout out: <out>/<taskname>/ep_t{t}_b{b}_i{i}_{k:06d}.npz (same as the existing corpus)"""from __future__ import annotationsimport argparse, io, os, re, sys, glob, timefrom pathlib import Pathimport numpy as npsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from eval_closed_loop import BUILDER, ogpo, to224 # the evaluator's own encoder path
PAT = re.compile(r"task(\d+)_block(\d+)/rank_(\d+)/id_(\d+)/data/chunk-(\d+)/episode_(\d+)\.parquet$")
def main(): ap = argparse.ArgumentParser() ap.add_argument("--root", required=True); ap.add_argument("--out", required=True) ap.add_argument("--shard", type=int, default=0); ap.add_argument("--num-shards", type=int, default=1) ap.add_argument("--batch", type=int, default=64) ap.add_argument("--task-file", default=os.environ.get("RSM_TASKS_FILE", "")) a = ap.parse_args() import torch, pyarrow.parquet as pq from PIL import Image from libero.libero import benchmark dev = "cuda" if torch.cuda.is_available() else "cpu" enc_tag = os.path.basename(os.path.normpath(os.environ.get("OGPO_PI05_BASE", "pi05_base_pytorch"))) canon = [n.strip() for n in Path(a.task_file).read_text().replace("\n", ",").split(",") if n.strip()] bench = benchmark.get_benchmark_dict()["libero_10"]() lang = {bench.get_task(i).name: bench.get_task(i).language for i in range(bench.n_tasks)} files = sorted(glob.glob(f"{a.root}/task*_block*/rank_*/id_*/data/chunk-*/episode_*.parquet")) files = [f for k, f in enumerate(files) if k % a.num_shards == a.shard] print(f"[enc] encoder={enc_tag} shard {a.shard}/{a.num_shards}: {len(files)} episodes", flush=True) model = ogpo.build_paligemma(dev) ids_cache = {} n_done = n_skip = 0; t0 = time.time() for k, f in enumerate(files): m = PAT.search(f) if not m: continue t, b, i, _c, ep = (int(x) for x in (m.group(1), m.group(2), m.group(4), m.group(5), m.group(6))) tname = canon[t] op = Path(a.out) / tname / f"ep_t{t}_b{b}_i{i}_{ep:06d}.npz" if op.exists(): n_skip += 1; continue tb = pq.read_table(f, columns=["state", "actions", "is_success", "image", "wrist_image"]) st = np.asarray(tb.column("state").to_pylist(), np.float32) ac = np.asarray(tb.column("actions").to_pylist(), np.float32) succ = bool(np.asarray(tb.column("is_success").to_pylist()).any()) frames = {} for cam in ("image", "wrist_image"): col = tb.column(cam).to_pylist() frames[cam] = np.stack([to224(np.asarray(Image.open(io.BytesIO(x["bytes"])).convert("RGB"))) for x in col]) if t not in ids_cache: ids_cache[t] = ogpo.tokenize_prompt(lang[tname]) za = ogpo.encode_frames(model, frames["image"], ids_cache[t], dev, a.batch) zw = ogpo.encode_frames(model, frames["wrist_image"], ids_cache[t], dev, a.batch) z = np.concatenate([za, zw], 1).astype(np.float16) op.parent.mkdir(parents=True, exist_ok=True) tmp = str(op) + ".tmp.npz" np.savez(tmp, z=z, proprio=st, actions=ac, success=succ, prompt=ids_cache[t], task_index=t, encoder=enc_tag, cam_res=256) os.replace(tmp, op); n_done += 1 if n_done % 20 == 0: el = time.time() - t0 print(f"[enc] {k+1}/{len(files)} done={n_done} skip={n_skip} {el/n_done:.1f}s/ep", flush=True) print(f"[enc] DONE shard {a.shard}: {n_done} written, {n_skip} existed, encoder={enc_tag}", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Encode the ten LIBERO-10 instructions with T5 and cache the vectors.
Replaces the learned nn.Embedding(n_task) conditioning. An index lookup carries noinformation about WHAT the task is: it cannot transfer to a held-out instruction, and itgives the network a free shortcut so nothing forces the visual latent to represent theinstruction. A frozen T5 embedding conditions on the sentence itself.
Ten short strings, so this runs once and the result is a few hundred KB."""import argparse, numpy as np, torch, os
ap = argparse.ArgumentParser()ap.add_argument("--cache", required=True)ap.add_argument("--out", required=True)ap.add_argument("--model", default="google-t5/t5-11b")ap.add_argument("--pool", default="mean", choices=["mean", "first"])a = ap.parse_args()
m = np.load(f"{a.cache}/meta.npz", allow_pickle=True)# the cache stores directory names; recover the instruction the way the evaluator doesfrom libero.libero import benchmarkb = benchmark.get_benchmark_dict()["libero_10"]()names = [str(t) for t in m["tasks"]]by_name = {b.get_task(i).name: b.get_task(i).language for i in range(b.n_tasks)}texts = [by_name.get(n, n.replace("_", " ")) for n in names]for i, t in enumerate(texts): print(f" [{i}] {t}", flush=True)
from transformers import T5EncoderModel, T5Tokenizertok = T5Tokenizer.from_pretrained(a.model, legacy=False)enc = T5EncoderModel.from_pretrained(a.model, torch_dtype=torch.float16).eval()dev = "cuda" if torch.cuda.is_available() else "cpu"enc = enc.to(dev)with torch.no_grad(): bt = tok(texts, return_tensors="pt", padding=True) out = enc(input_ids=bt["input_ids"].to(dev), attention_mask=bt["attention_mask"].to(dev)).last_hidden_state msk = bt["attention_mask"].to(dev).unsqueeze(-1).float() vec = ((out.float() * msk).sum(1) / msk.sum(1)) if a.pool == "mean" else out[:, 0].float()vec = vec.cpu().numpy().astype(np.float32)np.savez(a.out, emb=vec, tasks=np.array(names, dtype=object), texts=np.array(texts, dtype=object), model=a.model, pool=a.pool)print(f"[t5] wrote {a.out} shape={vec.shape} " f"norm mean={np.linalg.norm(vec,axis=1).mean():.2f}", flush=True)# sanity: the two LIVING_ROOM_SCENE2 tasks differ only in the objects namedimport itertoolsD = np.linalg.norm(vec[:, None] - vec[None], axis=-1)iu = list(itertools.combinations(range(len(vec)), 2))d = [(D[i, j], i, j) for i, j in iu]d.sort()print(f"[t5] closest pair : t{d[0][1]} / t{d[0][2]} dist {d[0][0]:.2f}")print(f"[t5] farthest pair : t{d[-1][1]} / t{d[-1][2]} dist {d[-1][0]:.2f}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025"""Closed-loop LIBERO-10 success rate for an rsm_libero policy.
Reuses the LANE'S evaluator wholesale -- featurization, env construction, seeding,task ordering, chunk execution -- and swaps ONLY the policy call. That isdeliberate: the 0.584 +- 0.025 `bcdemos_m120k` bar was produced by`09032026_latent_head_eval.py`, and a success rate measured by any other harnessis not comparable to it.
Featurization contract copied exactly from that evaluator: * ROT180 to serving orientation (`obs[key][::-1, ::-1]`) * 128 -> 224 bilinear * per-camera 2048-d pool, agentview ++ wrist -> 4096 * proprio = eef_pos(3) ++ eef_ori(3) ++ gripper_qpos(2) = 8
Features are z-scored with the SAME per-dim statistics the policy trained under,loaded from the training cache (`feat_stats.npz`). Getting normalisation wrong ineither direction evaluates a good policy off-distribution and isindistinguishable from the policy being bad, so the stats travel with the runrather than being reconstructed here."""from __future__ import annotationsimport argparse, hashlib, importlib.util, json, os, sysfrom pathlib import Pathimport numpy as npimport torch
WT = os.environ.get("RSM_WT", "/data/pulkitag/hamer_diffusion_policy_project/projects/" "continual_learning_for_manipulation/.claude/worktrees/08312026_jvq_recap_worktree")# RSM_WT: the CLM worktree holding scripts/rlinf_jvq (the latent-cache BUILDER). On IBM it# is /proj/dmfexp/zwhong/rli14_jvq_worktree; the builder itself reads OGPO_PI05_BASE and# OGPO_TOKENIZER for its weights.sys.path.insert(0, WT + "/scripts/rlinf_jvq")sys.path.insert(0, str(Path(__file__).resolve().parent))
# build_paligemma / tokenize_prompt / encode_frames live in the latent-cache# BUILDER; the rollout producer merely imports it under the local name `ogpo`.# Importing the producer instead gives a module without those attributes, which# kills the evaluator on its first line of work. This is the SAME builder that# wrote the training cache -- verified to reproduce it at cos 0.9999 offline and# 0.9903 from live env frames.BUILDER = WT + "/scripts/rlinf_jvq/08312026_1110pm_ogpo_latent_cache.py"_spec = importlib.util.spec_from_file_location("ogpo_cache", BUILDER)ogpo = importlib.util.module_from_spec(_spec)sys.modules["ogpo_cache"] = ogpo_spec.loader.exec_module(ogpo)
from model import Encoder, FlowPolicy, BCHead, ConcatFlowPolicyfrom is_ope import _LatWithProprio
def to224(img): """128 -> 224 bilinear, then ROUND AND CLAMP TO uint8.
The uint8 quantisation is not cosmetic. The latent cache was built from PIL uint8 images, so the encoder has only ever seen quantised pixels. Feeding it the raw float32 interpolation instead shifts the latent by up to 0.31 in a space whose per-dimension standard deviation is 0.107 -- a three-sigma perturbation on the dimensions that matter, re-applied at every one of the ~52 chunk decisions in an episode. Measured: the lane's own 0.584 policy scores 0/50 through this evaluator with float input and 0.46 through its own evaluator, which quantises. Cosine similarity (0.999898) hides this entirely, which is why it was not caught by the featurisation checks. """ t = torch.from_numpy(np.ascontiguousarray(img[None])).permute(0, 3, 1, 2).float() t = torch.nn.functional.interpolate(t, size=(224, 224), mode="bilinear", align_corners=False) return t.permute(0, 2, 3, 1).round().clamp(0, 255).byte().numpy()[0]
def _eef_ori(obs): """End-effector orientation as AXIS-ANGLE, matching the cache.
This was the bug that produced 0% everywhere. The cache's 8-d proprio is eef_pos(3) ++ ee_ori(3) ++ gripper_qpos(2), and LIBERO's `ee_ori` is robosuite AXIS-ANGLE. This evaluator previously converted the quaternion to Euler roll/pitch/yaw, so three of the eight proprio dimensions were a different quantity at every timestep. The policy still emitted plausible first actions -- the visual latent dominates the input -- which is why the featurisation checks, the offline fit and even a bit-exact comparison of the first action chunk all looked healthy.
Measured with the lane's own 0.584 policy on task 5: 0/5 through this evaluator with Euler, 5/5 through theirs with axis-angle, same machine and same weights. """ q = obs.get("robot0_eef_quat") if q is None: return np.zeros(3, np.float32) try: from robosuite.utils.transform_utils import quat2axisangle return np.asarray(quat2axisangle(np.asarray(q)), dtype=np.float32) except Exception: w = np.clip(q[3], -1, 1) ang = 2 * np.arccos(abs(w)) axis = q[:3] / (np.linalg.norm(q[:3]) + 1e-8) return (axis * ang).astype(np.float32)
_oodx = [] # (task, online t=0 feature) when --probe-ood: lets the online region be # compared against the cached demo and rollout clouds offline
# A checkpoint records the cache it trained on. When it was trained on the OTHER cluster,# resolve that path to the local twin: both caches are packed from the same pinned# episode list (index-identical, latents bit-identical) and their stats come from the# same arrays. Extend with RSM_CACHE_REMAP="from1=to1,from2=to2" if a new pair appears._CACHE_TWINS = { "/proj/dmfexp/zwhong/rsm_libero/cache/": "/data/pulkitag/users/rli14/rsm_libero_cache/", "/data/pulkitag/users/rli14/rsm_libero_cache/": "/proj/dmfexp/zwhong/rsm_libero/cache/",}
def _resolve_cache(path): import os as _os p = str(path or "") if not p or _os.path.exists(p): return p pairs = list(_CACHE_TWINS.items()) for kv in filter(None, _os.environ.get("RSM_CACHE_REMAP", "").split(",")): a, b = kv.split("=", 1); pairs.append((a, b)) for a, b in pairs: if p.startswith(a) and _os.path.exists(b + p[len(a):]): print(f"[cache] {p} -> {b + p[len(a):]} (cluster twin)", flush=True) return b + p[len(a):] return p
def _declared_cam_res(ckpt_path): """What resolution were this checkpoint's latents rendered at? From the checkpoint itself, else from its cache's RENDER.json / PACK.json. 'UNKNOWN' if neither.""" import json as _j try: ck = torch.load(ckpt_path, map_location="cpu", weights_only=False) except Exception: return "UNKNOWN" if ck.get("cam_res") not in (None, "UNKNOWN"): return ck["cam_res"] cache = _resolve_cache((ck.get("config") or {}).get("cache", "")) for f in ("RENDER.json", "PACK.json"): try: v = _j.load(open(f"{cache}/{f}")).get("cam_res") if v is not None: return v except Exception: pass return "UNKNOWN"
def _declared_encoder(ckpt_path): """Which feature encoder produced this checkpoint's latents (basename of the OGPO_PI05_BASE it was built with). Legacy checkpoints predate the tag -> pi05_base_pytorch.""" import json as _j try: ck = torch.load(ckpt_path, map_location="cpu", weights_only=False) except Exception: return "UNKNOWN" if ck.get("encoder"): return ck["encoder"] cache = _resolve_cache((ck.get("config") or {}).get("cache", "")) for f in ("PACK.json", "RENDER.json"): try: v = _j.load(open(os.path.join(cache, f))).get("encoder") if v: return v except Exception: pass return "pi05_base_pytorch"
def _guard_encoder(args): """Refuse to evaluate with a feature encoder different from the one the latents were encoded with (the 128/256 lesson applied to the encoder weights themselves).""" mine = os.path.basename(os.path.normpath(os.environ.get("OGPO_PI05_BASE", "pi05_base_pytorch"))) bad = [] for label, path in (("policy", args.policy), ("policy2", getattr(args, "policy2", "")), ("critic", args.critic), ("qf-ckpt", args.qf_ckpt), ("hop-policy", getattr(args, "hop_policy", ""))): if not path: continue v = _declared_encoder(path) if v != mine: bad.append(f"{label} {path}: latents from encoder '{v}', evaluator encoder '{mine}'") if bad and not args.allow_cam_mismatch: raise SystemExit("[guard] ENCODER MISMATCH -- refusing:\n " + "\n ".join(bad)) for b in bad: print(f"[guard] OVERRIDDEN encoder mismatch: {b}", flush=True)
def _guard_render_resolution(args): """Refuse to evaluate a policy/critic at a resolution its latents were not rendered at. This is the defect that voided every result before 2026-09-13 (i251): rollout latents at 256, evaluator at 128, and nothing complained.""" bad = [] for label, path in (("policy", args.policy), ("critic", args.critic), ("qf-ckpt", args.qf_ckpt), ("hop-policy", getattr(args, "hop_policy", ""))): if not path: continue v = _declared_cam_res(path) if v == "UNKNOWN": # trusting an undeclared checkpoint is exactly how the 128/256 mismatch ran # unnoticed for weeks; undeclared is refused like a mismatch bad.append(f"{label} {path}: render resolution UNDECLARED (no cam_res in checkpoint " f"or in its cache's RENDER.json/PACK.json)") elif str(v) != str(args.cam_res): bad.append(f"{label} {path}: latents rendered at {v}, evaluator at {args.cam_res}") if bad and not args.allow_cam_mismatch: raise SystemExit("[guard] RENDER RESOLUTION MISMATCH -- refusing:\n " + "\n ".join(bad) + "\n (--allow-cam-mismatch 1 to override; never for a reported number)") for b in bad: print(f"[guard] OVERRIDDEN mismatch: {b}", flush=True)
def load_policy(critic_path, policy_path, n_task, device, lane_norm=""): """Encoder from the critic checkpoint + the trained policy.
The policy may read the FULL observation (`policy_features=raw`, the default since the reward-predictive bottleneck was found to strip action detail) or the critic latent. Which one is recorded in the policy checkpoint, so the evaluator can never feed a policy the features it was not trained on. """ d_in = 4096 + 8 pk = torch.load(policy_path, map_location=device, weights_only=False)
# HARNESS CONTROL: a lane checkpoint (key "model") is wrapped so it runs # through THIS evaluator unchanged. If it reproduces the score its own # evaluator gives, this harness is proven equivalent and any 0% belongs to # our training rather than to deployment. if "model" in pk: import importlib.util as _il _sp = _il.spec_from_file_location("lh", WT + "/scripts/rlinf_jvq/" "09032026_latent_head_bc.py") _lh = _il.module_from_spec(_sp); sys.modules["lh"] = _lh _sp.loader.exec_module(_lh) c = pk["config"] head = _lh.Head(4096, 8, len(_lh.FS15), c["hidden"], c["depth"], c["chunk"]).to(device) head.load_state_dict(pk["model"]); head.eval() if not lane_norm: raise SystemExit("a lane checkpoint needs --lane-norm <norm npz>") nz = np.load(lane_norm) zm = torch.tensor(nz["zm"], dtype=torch.float32, device=device) zs = torch.tensor(nz["zs"], dtype=torch.float32, device=device) pm = torch.tensor(nz["pm"], dtype=torch.float32, device=device) ps = torch.tensor(nz["ps"], dtype=torch.float32, device=device)
class _LaneWrap(torch.nn.Module): """Exposes the lane Head through our (pfeat, sample) interface.""" d_act = c["chunk"] * 7
def __init__(self): super().__init__(); self.h = head; self.chunk = c["chunk"]
@torch.no_grad() def sample(self, x, task): z = (x[:, :4096] - zm) / zs pr = (x[:, 4096:] - pm) / ps adv = torch.full((x.shape[0],), 2, dtype=torch.long, device=x.device) a = torch.randn(x.shape[0], self.chunk, 7, device=x.device) for st in range(10): kk = torch.full((x.shape[0],), 1 - st / 10, device=x.device) a = a + self.h(z, pr, task, adv, a, kk).view_as(a) / 10 return a.flatten(1)
mu0 = torch.zeros(d_in, device=device); sd1 = torch.ones(d_in, device=device) return ((lambda x: x), _LaneWrap(), c["chunk"], {"d_z": 0}, "lane", d_in, (mu0, sd1)) # the exact transform the policy trained under -- never re-derived here # the stats file must match the pool the policy trained under _np = pk["config"].get("norm_pool", "all") st = Path(_resolve_cache(pk["config"].get("cache", ""))) / ( "feat_stats.npz" if _np == "all" else f"feat_stats_{_np}.npz") if not st.exists(): raise FileNotFoundError( f"feature stats missing: {st}. The policy was trained on normalised " f"features; evaluating it on raw ones is off-distribution.") _s = np.load(st) if int(_s["dim"]) != d_in: raise ValueError(f"feat_stats dim {int(_s['dim'])} != evaluator dim {d_in}") nmu = torch.tensor(_s["mu"], dtype=torch.float32, device=device) nsd = torch.tensor(_s["sd"], dtype=torch.float32, device=device) # A raw-feature policy trains on CENTERED input, which the data layer # produces by z-scoring and then rescaling the visual block back by # sd / mean(sd). Rebuilt here from the same stats file so the evaluator and # is_ope.policy_features cannot drift apart. Proprio (last 8 dims) keeps its # per-dim z-score. _sd = np.asarray(_s["sd"], np.float32) _sc = np.ones(d_in, np.float32) _sc[:4096] = _sd[:4096] / max(float(_sd[:4096].mean()), 1e-6) nsc = torch.tensor(_sc, dtype=torch.float32, device=device) if pk["config"].get("policy_features", "latent") == "raw": # a raw-feature policy needs no encoder at all, so a BC arm evaluates # without ever loading a critic cls = (ConcatFlowPolicy if pk["config"].get("policy_family", "flow") == "concat" else FlowPolicy) _kw = {} if pk["config"].get("policy_family", "flow") == "concat": _kw = dict(width=int(pk["config"].get("pol_width", 1024) or 1024), depth=int(pk["config"].get("pol_depth", 4) or 4)) pol = cls(d_in, pk["config"]["chunk"] * 7, n_task, **_kw).to(device) pol.load_state_dict(pk["pol"]); pol.eval() return ((lambda x: x * nsc), pol, pk["config"]["chunk"], {"d_z": 0}, "raw", d_in, (nmu, nsd)) if not critic_path: raise SystemExit("this policy reads latent features; pass --critic") ck = torch.load(critic_path, map_location=device, weights_only=False) c = ck["config"] n_pr = int(ck.get("n_pr", 0) or 0) base = Encoder(d_in, c["d_z"], c["enc_width"]).to(device) base.load_state_dict(ck["enc"]) pcfg = pk["config"] chunk = pcfg["chunk"] mode = pcfg.get("policy_features", "latent")
mu = sd = torch.zeros(0, device=device) if n_pr: # proprio normalisation must come from the cache the CRITIC was fit on, # not a hard-coded path: different caches have different proprio stats. pcache = Path(pcfg.get("cache", "")) / "proprio.f32.npy" if not pcache.exists(): raise FileNotFoundError(f"proprio stats cache missing: {pcache}") pr = np.asarray(np.load(pcache, mmap_mode="r")[::37], np.float32) mu = torch.tensor(pr.mean(0), device=device) sd = torch.tensor(pr.std(0) + 1e-6, device=device) enc = _LatWithProprio(base, n_pr, mu, sd).to(device).eval()
if mode == "raw": pfeat, d_lat = (lambda x: x), d_in else: pfeat, d_lat = enc, c["d_z"] + n_pr
cls = (ConcatFlowPolicy if pcfg.get("policy_family", "flow") == "concat" else FlowPolicy) pol = cls(d_lat, chunk * 7, n_task).to(device) pol.load_state_dict(pk["pol"]) pol.eval() return pfeat, pol, chunk, c, mode, d_lat, (nmu, nsd)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--critic", default="", help="only needed when the policy reads latent features") ap.add_argument("--policy", required=True) ap.add_argument("--tasks", default="0,1,2,3,4,5,6,7,8,9") ap.add_argument("--n-init", type=int, default=10) ap.add_argument("--execute", type=int, default=10) ap.add_argument("--max-steps", type=int, default=520) ap.add_argument("--suite", default="libero_10") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--policy-seed", type=int, default=0) ap.add_argument("--fresh", type=int, default=0) ap.add_argument("--qf-gate", type=float, default=0.0, help="only OVERRIDE the policy's own action when the best " "candidate beats it by more than this margin in Q units. " "0 = always take the arg-max (plain ranking, 0.550); a " "large value never fires and reduces exactly to the " "policy (0.630). The ranker is weak on average -- " "expert-vs-perturbation wins only 0.515 at small " "perturbations -- so acting on it only where it is " "confident is the way to use it without paying for its " "average quality.") ap.add_argument("--policy-sde", type=float, default=0.0, help="noise injected DURING integration when --q-filter is " "on. Unlike --policy-temp this follows the learned " "drift, so candidates stay near the manifold. Measured: " "test-time ranking (0.550) beats distilling the selected " "actions (0.410), because distillation replaces the " "policy while ranking only picks among its own samples.") ap.add_argument("--policy-sde-anneal", type=int, default=0, help="1 = scale --policy-sde noise by the remaining noise " "fraction so the last integration steps are clean.") ap.add_argument("--policy-temp", type=float, default=1.0, help="scales the proposal's initial noise when --q-filter is " "on. A trained flow clone samples at action std 0.029 " "against the data's 0.421, so 8 candidates are near " "copies and there is nothing to rank. Diversity only " "pays once the ranker has the right SIGN, which the " "supervised student Q does and our counterfactual Q did " "not.") ap.add_argument("--qf-ckpt", default="", help="main_rsm.pt from rsm_main.py. Ranks --q-filter candidate " "chunks by the DISTILLED student qf(z,a), which main " "supervises on real (s,a,s') transitions, instead of by " "conditioning the occupancy on a counterfactual action.") ap.add_argument("--save-frames", default="", help="directory to write per-episode agentview JPEG strips. Lets a " "closed-loop FAILURE be inspected: the scalar SR says an arm " "lost an episode, not what the arm did wrong.") ap.add_argument("--frame-stride", type=int, default=12) ap.add_argument("--init-jitter", type=float, default=0.0, help="metres of uniform xy perturbation applied to every object " "free joint after reset. BOTH stock init states and env.reset() " "are narrow (std 0.024 / 0.014), and both sit inside " "BC-on-demos's training support, so neither tests whether a " "demo-trained policy degrades off-support. This widens the " "initial-state distribution explicitly. Applies to A and B " "alike; 0 = off.") ap.add_argument("--select", default="argmaxq", choices=["argmaxq", "random", "medoid", "qnear", "quantile", "randgate"], help="how to pick among the --q-filter candidates. argmaxq uses " "the critic. random picks uniformly (must reproduce plain BC, " "and is the sanity check that the harness adds nothing). " "medoid picks the candidate nearest the other N-1, a " "CRITIC-FREE variance reducer -- if best-of-N helps for any " "reason other than value, medoid captures it, and any gain " "over medoid is what the critic actually contributes.") ap.add_argument("--demo-cand", type=int, default=0, help="append this many nearest-DEMO action chunks to the " "candidate set, retrieved by L2 in the same normalised " "feature space the policy reads. The ranker is otherwise " "confined to the proposal's own support: 8 samples from a " "flow with action std 0.029 against the data's 0.421 are " "near-copies, so even a perfect ranker has nothing to " "choose. Demo chunks are off-proposal but ON-manifold, " "unlike --policy-sde noise which cost 0.22.") ap.add_argument("--q-filter", type=int, default=0, help="sample this many action chunks from the policy and " "execute the one the RSM critic scores highest. 0 = off. " "Uses the occupancy model at DEPLOYMENT, which needs only " "a critic that RANKS actions, not one that is calibrated.") ap.add_argument("--qf-beta", type=float, default=0.97, help="hop length for the filter, inside the critic's training " "band [0.85, 0.97]; 0.97 looks ~33 frames ahead") ap.add_argument("--qf-depth", type=int, default=1, help="depth 1 needs no continuation policy: the recursion " "breaks before it would have to re-draw an action in a " "latent the flow only imagined") ap.add_argument("--qf-particles", type=int, default=16) ap.add_argument("--qf-mode", default="restart", choices=["restart", "fold"], help="restart: geometric mixture of beta-hops (restart prob " "(gamma-beta)/(gamma(1-beta))) = the gamma-occupancy, reward read " "once at the stopping state. fold: the OCBench product fold " "Q_k = c_k + (1-c_k) gamma^(1/(1-beta)) Q_{k+1} over a FIXED " "number of hops (--qf-depth).") ap.add_argument("--policy2", default="", help="second proposer checkpoint; --q-filter2 of its samples are appended " "to the candidate set (test-time stitching of two policies)") ap.add_argument("--q-filter2", type=int, default=0) ap.add_argument("--select-q", type=float, default=0.9, help="select=quantile: execute the candidate at this quantile of Q " "(rank round(q*(N-1)) in ascending order) instead of the arg-max.") ap.add_argument("--qf-crn", type=int, default=0, help="1 = common random numbers across candidates in the Q " "recursion (same flow noise / restart coins / hop-policy noise " "for particle i of every candidate), so the arg-max compares " "paired estimates. Independent draws rank near-copies by noise.") ap.add_argument("--qnear-k", type=int, default=4, help="select=qnear: arg-max Q among the K candidates nearest the medoid") ap.add_argument("--hop-policy", default="", help="bc_arm checkpoint trained with --policy-features latent over the " "SAME critic encoder. Required for --qf-depth >= 2: the beta-hop " "composition continues the trajectory from the sampled latent z' " "with pi(a|z'), and the raw-feature proposer cannot read z'.") ap.add_argument("--qf-pessimism", type=float, default=2.0) ap.add_argument("--partial-only", type=int, default=0, help="write only <out>.partial.t<k> files; the final JSON is left to an assembly run") ap.add_argument("--allow-cam-mismatch", type=int, default=0, help="override the render-resolution guard. Never for a reported number.") ap.add_argument("--init-source", default="libero", choices=["libero", "demo", "rollout"], help="where episode k's initial state comes from. libero = the stock " "init_states (protocol A) or env.reset() (protocol B); demo = the " "EXACT first sim state of demo k from the LIBERO hdf5; rollout = the " "first sim_state of the k-th cached rollout of this task.") ap.add_argument("--save-video-frames", default="", help="dir: write full-res agentview frames (uint8, every --video-stride " "steps) per episode, for mp4 export") ap.add_argument("--video-stride", type=int, default=2) ap.add_argument("--cam-res", type=int, default=256, help="render resolution of both cameras. 128 is the LIBERO demo-hdf5 " "convention and what the demo cache was encoded from; 256 is what " "RLinf's libero_10 env (the lane's evaluator AND the rollout " "collector) uses, i.e. the space the 43k rollout latents live in. " "A policy must be evaluated at the resolution its latents were " "encoded at, or it is off-support from step 1 (i251).") ap.add_argument("--probe-ood", type=int, default=0, help="print the first decision's action scale per episode. Default " "off so queued evals are unaffected.") ap.add_argument("--lane-norm", default="", help="norm npz for a lane checkpoint run as a harness control") ap.add_argument("--out", required=True) args = ap.parse_args() _guard_render_resolution(args) _guard_encoder(args)
dev = "cuda" if torch.cuda.is_available() else "cpu" # an assembly run (all tasks in partials) needs no GPU tower = ogpo.build_paligemma(dev) from libero.libero import benchmark, get_libero_path from libero.libero.envs import OffScreenRenderEnv import time as _time _T0 = _time.time() def _lap(msg): print(f"[eval][t+{_time.time()-_T0:6.0f}s] {msg}", flush=True) bench = benchmark.get_benchmark_dict()[args.suite]() _lap("imports + benchmark ready")
canon = [n.strip() for n in Path( os.environ.get("RSM_TASKS_FILE", "/data/pulkitag/hamer_diffusion_policy_project/projects/" "continual_learning_for_manipulation/logs/09052026_lib10_tasks.txt") ).read_text().replace("\n", ",").split(",") if n.strip()] by_name = {t: i for i, t in enumerate(canon)}
pfeat, pol, chunk, ccfg, pmode, d_lat, (nmu, nsd) = load_policy( args.critic, args.policy, len(canon), dev, lane_norm=args.lane_norm) _lap("policy (+encoder) loaded") pol2 = pfeat2 = None if args.policy2: # Second proposer: its candidates are appended to the first's, so the selector # can stitch between a narrow strong policy (demos) and a broad one (successes) # per decision. Both must share the feature normalisation (checked). pfeat2, pol2, chunk2, _c2, _m2, _d2, (nmu2, nsd2) = load_policy( args.critic, args.policy2, len(canon), dev, lane_norm=args.lane_norm) if chunk2 != chunk or not torch.allclose(nmu2, nmu) or not torch.allclose(nsd2, nsd): raise SystemExit("--policy2 must share chunk length and feature normalisation with --policy") print(f"[eval] second proposer: {args.policy2} x {args.q_filter2} candidates", flush=True)
qf = None gate_stats = {"fire": 0, "hold": 0} if args.q_filter and args.qf_ckpt and torch.load(args.qf_ckpt, map_location="cpu", weights_only=False).get("iql_q"): # IQL baseline, ranked with EXACTLY the RSM arm's best-of-N machinery: same # proposal policy, same N, same arg-max; only the source of Q differs. The IQL # Q reads the frozen encoder of the RSM critic it was trained against. from iql import QNet as _QNet from is_ope import load_critic as _lc from data import LiberoRSMData ck = torch.load(args.qf_ckpt, map_location=dev, weights_only=False) _pc = torch.load(args.policy, map_location="cpu", weights_only=False)["config"] _dq = LiberoRSMData(_resolve_cache(_pc["cache"]), chunk=chunk, seed=0, in_ram=False, reward_mode="dense", norm_pool=_pc.get("norm_pool", "all")) _enc, _r, _f, _rms, _cfg = _lc(_resolve_cache(ck["critic"]), _dq.feat_dim, _dq.n_task, dev, data=_dq) _enc.eval() _qc = ck.get("config") or {} qnet = _QNet(ck["d_z"], ck["d_act"], ck["n_task"], width=int(_qc.get("width", 512) or 512), depth=int(_qc.get("depth", 3) or 3)).to(dev) qnet.load_state_dict(ck["q"]); qnet.eval()
def qf(x_norm, tt, cand): z = _enc(x_norm).expand(cand.shape[0], -1) q = qnet(z, cand, tt.expand(cand.shape[0])) if args.select == "quantile": # Rank the candidates by Q and execute the one at quantile --select-q # (0.9 of 8 -> the 2nd best, of 32 -> the 4th best). The arg-max is the # candidate most exposed to off-support optimism; a high-but-not-top # quantile keeps a strongly-scored action while discarding the extreme. _order = torch.argsort(q) # ascending _r = int(round(args.select_q * (cand.shape[0] - 1))) gate_stats["fire"] += 1 return int(_order[min(max(_r, 0), cand.shape[0] - 1)]) best = int(q.argmax()) if args.qf_gate > 0 and float(q[best] - q[0]) < args.qf_gate: gate_stats["hold"] += 1 return 0 gate_stats["fire"] += 1 return best print(f"[eval] IQL Q reader ON: {args.q_filter} candidates (tau={ck['config'].get('tau')})", flush=True) elif args.q_filter and args.qf_ckpt: # main's reader: a student Q supervised on logged transitions. from model import Encoder as _Enc from rsm_main import QStudent ck = torch.load(args.qf_ckpt, map_location=dev, weights_only=False) c = ck["config"] qenc = _Enc(4096 + 8, c["d_z"], c["enc_width"]).to(dev) qenc.load_state_dict(ck["enc"]); qenc.eval() qnet = QStudent(c["d_z"], ck["d_act"], len(canon)).to(dev) qnet.load_state_dict(ck["qf"]); qnet.eval()
def qf(x_norm, tt, cand): z = qenc(x_norm).expand(cand.shape[0], -1) q = qnet(z, cand, tt.expand(cand.shape[0])) best = int(q.argmax()) # candidate 0 is an ordinary draw from the policy: the default action if args.qf_gate > 0 and float(q[best] - q[0]) < args.qf_gate: gate_stats["hold"] += 1 return 0 gate_stats["fire"] += 1 return best print(f"[eval] qf reader ON: {args.q_filter} candidates, student Q " f"(arrival AUC {ck.get('arrival_auc', float('nan')):.4f})", flush=True) elif args.q_filter and args.select not in ("argmaxq", "qnear", "quantile"): # randgate/medoid/random are critic-free qf = None # critic-free selector; no critic needed print(f"[eval] CRITIC-FREE selector '{args.select}' over " f"{args.q_filter} candidates", flush=True) elif args.q_filter: if not args.critic: raise SystemExit("--q-filter needs --critic or --qf-ckpt") from data import LiberoRSMData from is_ope import load_critic, q_recursive pcfg_cache = torch.load(args.policy, map_location="cpu", weights_only=False)["config"] _d = LiberoRSMData(_resolve_cache(pcfg_cache["cache"]), chunk=chunk, seed=0, in_ram=False, reward_mode="dense", norm_pool=pcfg_cache.get("norm_pool", "all")) q_enc, q_rew, q_flow, q_rms, q_cfg = load_critic( args.critic, _d.feat_dim, _d.n_task, dev, data=_d)
hop_pol = None if args.qf_depth >= 2: if not args.hop_policy: raise SystemExit("--qf-depth >= 2 needs --hop-policy (latent-feature BC over the critic encoder)") from is_ope import make_policy as _mk _hk = torch.load(args.hop_policy, map_location=dev, weights_only=False) _hc = _hk["config"] if _hc.get("policy_features") != "latent": raise SystemExit(f"--hop-policy must be a --policy-features latent checkpoint (got {_hc.get('policy_features')})") class _HA: pass _ha = _HA(); [setattr(_ha, k, v) for k, v in _hc.items()] hop_pol = _mk(_ha, _d, dev, d_z=q_cfg["d_z"]) hop_pol.load_state_dict(_hk["pol"]); hop_pol.eval() print(f"[eval] beta-hop policy loaded: {args.hop_policy} (depth {args.qf_depth}, " f"restart p={(0.99 - args.qf_beta) / (0.99 * (1 - args.qf_beta)):.3f})", flush=True)
from is_ope import q_fold if args.qf_mode == "fold": print(f"[eval] Q = OCBench product fold, depth {args.qf_depth}, " f"gamma^h = {0.99 ** (1 / (1 - args.qf_beta)):.3f} per hop, crn={args.qf_crn}", flush=True) def qf(x_norm, tt, cand): """cand: [N, chunk*7] -> index of the highest-scoring chunk.""" z = q_enc(x_norm).expand(cand.shape[0], -1) if args.qf_mode == "fold": q, _ = q_fold(z, cand, tt.expand(cand.shape[0]), rew=q_rew, flow=q_flow, rms=q_rms, pol=hop_pol, beta=args.qf_beta, gamma=0.99, depth=args.qf_depth, n_particles=args.qf_particles, crn=bool(args.qf_crn)) else: q, _ = q_recursive(z, cand, tt.expand(cand.shape[0]), rew=q_rew, flow=q_flow, rms=q_rms, pol=hop_pol, wend=None, beta=args.qf_beta, gamma=0.99, depth=args.qf_depth, n_particles=args.qf_particles, use_is=False, pessimism=args.qf_pessimism, crn=bool(args.qf_crn)) if args.select == "qnear": # Support-constrained arg-max: the critic orders only the K candidates # nearest the medoid. Measured failure of plain arg-max: off-support # candidates draw diffuse futures whose read-out drifts to the base rate # and outranks confident low scores on real actions; the medoid never # selects those outliers, and beat plain arg-max on B by 0.05-0.08. _dd = torch.cdist(cand, cand).sum(1) _near = torch.topk(-_dd, k=min(args.qnear_k, cand.shape[0])).indices best = int(_near[q[_near].argmax()]) gate_stats["fire"] += 1 return best if args.select == "quantile": # Rank the candidates by Q and execute the one at quantile --select-q # (0.9 of 8 -> the 2nd best, of 32 -> the 4th best). The arg-max is the # candidate most exposed to off-support optimism; a high-but-not-top # quantile keeps a strongly-scored action while discarding the extreme. _order = torch.argsort(q) # ascending _r = int(round(args.select_q * (cand.shape[0] - 1))) gate_stats["fire"] += 1 return int(_order[min(max(_r, 0), cand.shape[0] - 1)]) best = int(q.argmax()) if args.qf_gate > 0 and float(q[best] - q[0]) < args.qf_gate: gate_stats["hold"] += 1 return 0 gate_stats["fire"] += 1 return best print(f"[eval] Q-filter ON: {args.q_filter} candidates, beta={args.qf_beta}, " f"depth={args.qf_depth}, pessimism={args.qf_pessimism}, " f"gate={args.qf_gate}", flush=True) print(f"[eval] chunk={chunk} policy_features={pmode} d_policy={d_lat} " f"suite={args.suite}", flush=True) _lap("critic / selector ready")
demo_bank = None if args.demo_cand > 0: import numpy as _np pcfg_c = torch.load(args.policy, map_location="cpu", weights_only=False)["config"] _ca = pcfg_c["cache"] _m = _np.load(f"{_ca}/meta.npz", allow_pickle=True) _isd = _m["ep_demo"].astype(bool) if not _isd.any(): raise SystemExit("--demo-cand: cache has no demo episodes") _zs = _np.load(f"{_ca}/z.f16.npy", mmap_mode="r") _pr = _np.load(f"{_ca}/proprio.f32.npy", mmap_mode="r") _ac = _np.load(f"{_ca}/act.f32.npy", mmap_mode="r") _idx = [] for _e in _np.where(_isd)[0]: _lo, _hi = int(_m["ep_from"][_e]), int(_m["ep_to"][_e]) # only frames with a full chunk ahead inside the same episode if _hi - _lo > chunk: _idx.append(_np.arange(_lo, _hi - chunk)) _idx = _np.concatenate(_idx) _f = _np.concatenate([_np.asarray(_zs[_idx], _np.float32), _np.asarray(_pr[_idx], _np.float32)], 1) _f = torch.tensor(_f, device=dev) _f = ((_f - nmu) / nsd).half() # identical transform to x _off = _np.arange(chunk)[None, :] + _idx[:, None] _A = torch.tensor(_np.asarray(_ac[_off], _np.float32).reshape(len(_idx), -1), device=dev) demo_bank = (_f, _A) print(f"[eval] demo-cand ON: {args.demo_cand} nearest of " f"{len(_idx)} demo frames appended to each candidate set", flush=True)
demo_pick = {"demo": 0, "policy": 0} mix_pick = {"p1": 0, "p2": 0} results, episodes = {}, {} # Resume from a preempted run: tasks already finished are in <out>.partial. On IBM's # preemptable queue an hour-long eval is interrupted every ~30 min; without this it # never completes. Episodes within a task are re-run (seeds are per-episode, so the # completed tasks are unaffected by where the restart happens). import glob as _glob for _pp in sorted(_glob.glob(args.out + ".partial*")): try: _pj = json.loads(Path(_pp).read_text()) results.update(_pj.get("results", {})); episodes.update(_pj.get("episodes", {})) except Exception as _e: print(f"[eval] partial file {_pp} unreadable ({_e}); ignored", flush=True) if results: print(f"[eval] RESUMED: {len(results)} tasks already done from partial files", flush=True) for tid in [int(x) for x in args.tasks.split(",")]: task = bench.get_task(tid) tname = task.name if tname in results: print(f"[eval] t{tid} {tname[:40]}: done in a previous run (SR {results[tname]:.2f}), skipping", flush=True) continue if tname not in by_name: raise ValueError(f"task {tid} ({tname}) not in the canonical libero_10 list") thead = by_name[tname] ids = ogpo.tokenize_prompt(task.language) inits = bench.get_task_init_states(tid) if args.init_source == "demo": import h5py as _h5 with _h5.File(f"/data/pulkitag/users/rli14/libero_datasets/libero_10/{tname}_demo.hdf5", "r") as _H: _ks = sorted(_H["data"].keys(), key=lambda q: int(q.split("_")[1])) inits = [np.asarray(_H["data"][q]["states"][0]) for q in _ks] print(f"[eval] t{tid}: {len(inits)} EXACT demo initial states from hdf5", flush=True) elif args.init_source == "rollout": import pyarrow.parquet as _pq, re as _re _m = np.load("/data/pulkitag/users/rli14/rsm_libero_cache/full_demo_cam256/meta.npz", allow_pickle=True) _PAT = _re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$") inits = [] for _e in np.where((_m["ep_task"] == tid) & ~_m["ep_demo"].astype(bool))[0]: _g = _PAT.search(str(_m["ep_src"][_e])); _t, _b, _i, _x = _g.groups() _pp = (f"/data/pulkitag/users/rli14/pi05_lib10_sde_v1/task{int(_t)}_block{int(_b)}" f"/rank_0/id_{int(_i)}/data/chunk-000/episode_{int(_x):06d}.parquet") if not Path(_pp).exists(): continue inits.append(np.asarray(_pq.read_table(_pp, columns=["sim_state"])["sim_state"][0].as_py())) if len(inits) >= args.n_init: break print(f"[eval] t{tid}: {len(inits)} rollout initial sim_states from parquet", flush=True) _lap(f"t{tid}: creating env") env = OffScreenRenderEnv( bddl_file_name=str(Path(get_libero_path("bddl_files")) / task.problem_folder / task.bddl_file), camera_heights=args.cam_res, camera_widths=args.cam_res) _lap(f"t{tid}: env ready") _objn, _objb, _target = [], [], [] if args.save_frames: try: _objn = list(env.env.obj_body_id.keys()) _objb = [env.env.obj_body_id[n] for n in _objn] _target = list(env.env.obj_of_interest) print(f"[eval] t{tid} objects={_objn} target={_target}", flush=True) except Exception as _e: print(f"[eval] object handles unavailable: {_e}", flush=True) succ, episodes[tname] = [], [] # Per-episode progress: the EGL driver on IBM aborts the process (SIGABRT, no # traceback) at random points DURING a task, not only at teardown, so a 50-episode # task job that dies at episode 40 must not redo 40 episodes. Every finished # episode is appended to <out>.progress.t<tid>; a restarted job reloads it and # skips those episode indices (inits are seeded per (seed, tid, k), so the # remaining episodes are the same ones the dead job would have run). _prog = Path(args.out + f".progress.t{tid}") _done_k = set() try: if _prog.exists(): for _e in json.loads(_prog.read_text()): if int(_e["episode"]) < args.n_init and int(_e["episode"]) not in _done_k: episodes[tname].append(_e); succ.append(bool(_e["success"])) _done_k.add(int(_e["episode"])) if _done_k: print(f"[eval] t{tid}: resumed {len(_done_k)} episodes from {_prog.name}", flush=True) except Exception as _e: print(f"[eval] t{tid}: progress file unreadable ({_e}); starting over", flush=True) episodes[tname], succ, _done_k = [], [], set() for k in range(args.n_init): if k in _done_k: continue pseed = 7_919_003 + args.policy_seed * 500_009 + tid * 1_013 + k torch.manual_seed(pseed); torch.cuda.manual_seed_all(pseed) np.random.seed(args.seed * 100003 + tid * 1009 + k) if hasattr(env, "seed"): env.seed(args.seed * 100003 + tid * 1009 + k) env.reset() if args.init_source != "libero": env.env.sim.set_state_from_flattened(np.asarray(inits[k % len(inits)], np.float64)) env.env.sim.forward() elif not args.fresh: env.set_init_state(inits[k % len(inits)]) if args.init_jitter > 0: # Perturb object free joints only. mjtJoint FREE == 0; its qpos block is # [x, y, z, qw, qx, qy, qz], so writing indices 0-1 moves the object in # the table plane without touching height or orientation (which would # make the state unphysical). The robot is welded in LIBERO, so free # joints are exactly the manipulable objects. _sim = env.env.sim _st = np.asarray(_sim.get_state().flatten()).copy() _nq = _sim.model.nq _rs = np.random.RandomState( 987_631 + args.seed * 7919 + tid * 131 + k) _moved = 0 for _j in range(_sim.model.njnt): if int(_sim.model.jnt_type[_j]) != 0: continue _a = int(_sim.model.jnt_qposadr[_j]) if _a + 1 >= _nq: continue _st[1 + _a] += _rs.uniform(-args.init_jitter, args.init_jitter) _st[1 + _a + 1] += _rs.uniform(-args.init_jitter, args.init_jitter) _moved += 1 _sim.set_state_from_flattened(_st) _sim.forward() for _ in range(5): # let contacts settle onto the table _sim.step() if tid == 0 and k == 0: print(f"[eval] init-jitter {args.init_jitter*100:.1f} cm on " f"{_moved} object free joints", flush=True) done, steps = False, 0 _frames, _geo, _vid = [], [], [] obs, _, _, _ = env.step(np.zeros(7)) init_hash = hashlib.sha256( np.asarray(env.env.sim.get_state().flatten()).tobytes()).hexdigest() while steps < args.max_steps and not done: cams = [] for key in ("agentview_image", "robot0_eye_in_hand_image"): img = obs[key][::-1, ::-1] cams.append(to224(img)[None]) if args.save_video_frames and steps % args.video_stride == 0: _vid.append(np.asarray(obs["agentview_image"][::-1, ::-1], np.uint8).copy()) if args.save_frames and steps % args.frame_stride == 0: _frames.append(np.asarray(obs["agentview_image"][::-1, ::-1]).copy()) # geometry for offline failure typing: where the hand is, whether it # is closed, and where every object is. obj_of_interest names the # BDDL goal's target, so "went to the wrong object" is measurable # without touching a network. _ee = np.asarray(obs["robot0_eef_pos"], np.float32) _gq = np.asarray(obs["robot0_gripper_qpos"], np.float32) _op = np.stack([np.asarray(env.env.sim.data.body_xpos[_b], np.float32) for _b in _objb]) if _objb else np.zeros((0, 3), np.float32) _geo.append(np.concatenate([_ee, _gq[:2], _op.reshape(-1)])) z = np.concatenate( [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0] prop = np.concatenate([ obs["robot0_eef_pos"], _eef_ori(obs), obs["robot0_gripper_qpos"], ]).astype(np.float32) x = torch.tensor(np.concatenate([z, prop])[None], dtype=torch.float32, device=dev) x = (x - nmu) / nsd # same transform as LiberoRSMData._feat tt = torch.tensor([thead], device=dev) if args.probe_ood and steps == 0: # Off-distribution guard. A policy cloned from one pool can be a # near-perfect predictor on its own frames (held-out action MSE # 0.0008 at t=0 for BC_rollsucc) and still emit actions 5x too # large on the evaluator's first observation, which reads as a # flat 0/500 indistinguishable from a weak policy. Printing the # first action's scale next to the reference pools' action scale # separates "bad policy" from "policy evaluated off its manifold". with torch.no_grad(): _a0 = pol.sample(pfeat(x), tt)[0].view(chunk, 7) _oodx.append((int(tid), np.asarray(x[0].cpu(), np.float32))) print(f"[ood] task {tid} init {k}: |a| std={float(_a0.std()):.3f} " f"max={float(_a0.abs().max()):.3f} " f"frac|a|>1={float((_a0.abs() > 1).float().mean()):.3f} " f"(corpus action std ~0.43) |x|={float(x.norm()):.2f}", flush=True) with torch.no_grad(): if qf is None and not args.q_filter: a = pol.sample(pfeat(x), tt)[0].view(chunk, 7).cpu().numpy() else: feats = pfeat(x).expand(args.q_filter, -1) cand = pol.sample(feats, tt.expand(args.q_filter), temp=args.policy_temp, sde=args.policy_sde, sde_anneal=bool(args.policy_sde_anneal)) if pol2 is not None and args.q_filter2 > 0: cand2 = pol2.sample(pfeat2(x).expand(args.q_filter2, -1), tt.expand(args.q_filter2)) cand = torch.cat([cand, cand2], 0) n_pol = cand.shape[0] if demo_bank is not None: _fb, _Ab = demo_bank _d = torch.cdist(x.half(), _fb).squeeze(0) _nn = torch.topk(_d, args.demo_cand, largest=False).indices cand = torch.cat([cand, _Ab[_nn].to(cand.dtype)], 0) if args.select == "random": _pick = int(torch.randint(cand.shape[0], (1,)).item()) elif args.select == "randgate": # control for the critic gate: with prob --select-q execute a # random NON-default candidate, else the default (candidate 0) _pick = int(torch.randint(1, cand.shape[0], (1,)).item()) \ if float(torch.rand(1)) < args.select_q else 0 elif args.select == "medoid": _dd = torch.cdist(cand, cand) # [N,N] _pick = int(_dd.sum(1).argmin()) else: _pick = qf(x, tt, cand) if demo_bank is not None: demo_pick["demo" if _pick >= n_pol else "policy"] += 1 if pol2 is not None: mix_pick["p2" if args.q_filter <= _pick < args.q_filter + args.q_filter2 else "p1"] += 1 a = cand[_pick].view(chunk, 7).cpu().numpy() for act in a[: args.execute]: obs, _, done, _ = env.step(act.astype(np.float64)) steps += 1 if done or steps >= args.max_steps: break succ.append(bool(done)) episodes[tname].append({"episode": k, "success": bool(done), "steps": steps, "init_sha256": init_hash}) try: Path(args.out).parent.mkdir(parents=True, exist_ok=True) _tmp = _prog.with_suffix(_prog.suffix + ".tmp") _tmp.write_text(json.dumps(episodes[tname])); _tmp.replace(_prog) except Exception as _e: print(f"[eval] progress write failed ({_e})", flush=True) if (len(episodes[tname]) % 10) == 0: _lap(f"t{tid}: {len(episodes[tname])}/{args.n_init} episodes, SR so far {np.mean(succ):.2f}") if args.save_video_frames and _vid: _vd = Path(args.save_video_frames); _vd.mkdir(parents=True, exist_ok=True) np.savez_compressed(_vd / f"t{tid}_e{k}.npz", frames=np.stack(_vid), success=bool(done), steps=steps, task=tid, ep=k, stride=args.video_stride) if args.save_frames and _frames: import io as _io, base64 as _b64 from PIL import Image as _Im _fd = Path(args.save_frames); _fd.mkdir(parents=True, exist_ok=True) _enc = [] for _fr in _frames[:40]: _im = _Im.fromarray(_fr).convert("RGB"); _im.thumbnail((144, 144)) _bb = _io.BytesIO(); _im.save(_bb, "JPEG", quality=70) _enc.append(_b64.b64encode(_bb.getvalue()).decode()) np.savez_compressed( _fd / f"t{tid}_e{k}.npz", frames=np.array(_enc, dtype=object), geo=np.asarray(_geo, np.float32), objects=np.array(_objn, dtype=object), target=np.array(_target, dtype=object), success=bool(done), steps=steps, task=tid, ep=k) episodes[tname].sort(key=lambda _e: int(_e["episode"])) results[tname] = float(np.mean(succ)) try: # partial results survive a teardown abort or a preemption. Written BEFORE # env.close(): on IBM's EGL driver close() aborts the process (rc=134). Path(args.out).parent.mkdir(parents=True, exist_ok=True) # one file per task: parallel per-task jobs never write the same file Path(args.out + f".partial.t{tid}").write_text(json.dumps( {"results": {tname: results[tname]}, "episodes": {tname: episodes[tname]}}, indent=1)) except Exception: pass if os.environ.get("RSM_NO_ENV_CLOSE"): _keep_alive = globals().setdefault("_KEEP_ENVS", []); _keep_alive.append(env) else: try: env.close() except Exception as _e: print(f"[eval] env.close() raised (ignored): {_e}", flush=True) print(f"task {tid} {tname[:40]}: SR {results[tname]:.2f} " f"({sum(succ)}/{len(succ)})", flush=True)
overall = float(np.mean(list(results.values()))) n_tot = sum(len(v) for v in episodes.values()) n_suc = sum(e["success"] for v in episodes.values() for e in v) pooled = n_suc / max(n_tot, 1) # THROUGHPUT = SR * max_steps / mean_steps. Rewards finishing FAST, not just # finishing: a policy that solves in half the horizon does twice the work per # unit time. Reported two ways because they answer different questions: # _succ : mean over SUCCESSFUL episodes -- how fast is it when it works # _all : mean over ALL episodes -- failures burn the full horizon, so this # penalises failing twice (once in SR, once in the time it wasted) all_steps = [e["steps"] for v in episodes.values() for e in v] suc_steps = [e["steps"] for v in episodes.values() for e in v if e["success"]] mean_all = float(np.mean(all_steps)) if all_steps else float("nan") mean_suc = float(np.mean(suc_steps)) if suc_steps else float("nan") thr_all = pooled * args.max_steps / mean_all if mean_all == mean_all and mean_all > 0 else float("nan") thr_suc = pooled * args.max_steps / mean_suc if mean_suc == mean_suc and mean_suc > 0 else float("nan") per_task_thr = {} for tname, eps in episodes.items(): s = [e["steps"] for e in eps if e["success"]] if s: per_task_thr[tname] = results[tname] * args.max_steps / float(np.mean(s)) out = {"overall_task_mean_SR": overall, "successes": n_suc, "episodes": n_tot, "pooled_SR": pooled, "throughput_succ": thr_suc, "throughput_all": thr_all, "mean_steps_success": mean_suc, "mean_steps_all": mean_all, "max_steps": args.max_steps, "per_task_throughput": per_task_thr, "per_task": results, "critic": args.critic, "policy": args.policy, "chunk": chunk, "policy_features": pmode, "seed": args.seed, "n_init": args.n_init, "suite": args.suite, "episodes_detail": episodes} Path(args.out).parent.mkdir(parents=True, exist_ok=True) if args.partial_only: print("[eval] --partial-only: final JSON left to the assembly run", flush=True) else: Path(args.out).write_text(json.dumps(out, indent=1)) if args.probe_ood and _oodx: _p = str(Path(args.out).with_suffix("")) + "_oodx.npz" np.savez_compressed(_p, task=np.array([t for t, _ in _oodx], np.int64), x=np.stack([v for _, v in _oodx])) print(f"[ood] wrote {len(_oodx)} online t=0 features to {_p}", flush=True) if pol2 is not None: _m1, _m2 = mix_pick["p1"], mix_pick["p2"] print(f"[eval] mixed proposer: policy2 chosen {_m2}/{_m1+_m2} ({_m2/max(_m1+_m2,1):.3f})", flush=True) _dp, _pp = demo_pick["demo"], demo_pick["policy"] if _dp + _pp: print(f"[eval] demo-cand: expert chunk chosen {_dp}/{_dp+_pp} " f"({_dp/(_dp+_pp):.3f}) of decisions", flush=True) _gf, _gh = gate_stats["fire"], gate_stats["hold"] if _gf + _gh: print(f"[eval] gate={args.qf_gate}: fired {_gf}/{_gf+_gh} " f"({_gf/(_gf+_gh):.3f}) decisions overridden", flush=True) print(f"\nOVERALL task-mean SR {overall:.4f} | pooled {n_suc}/{n_tot} = {pooled:.4f}", flush=True) print(f"THROUGHPUT succ-only {thr_suc:.4f} all-episodes {thr_all:.4f} " f"(mean steps: success {mean_suc:.0f}, all {mean_all:.0f}, max {args.max_steps})", flush=True) print(f"BAR: bcdemos_m120k = 0.584 +- 0.025 (n=500, same harness family)", flush=True) # Everything is on disk. Skip interpreter teardown: on IBM's EGL driver robosuite's # context destructor aborts the process (rc=134), which on a normal exit would turn a # finished, written evaluation into a "failed" job. import sys as _sys; _sys.stdout.flush(); _sys.stderr.flush() os._exit(0)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Build playable clips: demos (hdf5) vs rollout successes vs rollout failures (parquet).
Same task, same frame budget, same size -- so the three slices are directly comparableby eye. Demos come from the stock LIBERO hdf5 (agentview_rgb); rollouts from the sourcecorpus PNGs."""import argparse, base64, io, json, os, reimport numpy as np
SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"DEMO = "/data/pulkitag/users/rli14/libero_datasets/libero_10"PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
def src_parquet(ep_src): m = PAT.search(str(ep_src)) if not m: return None t, b, i, idx = m.groups() p = (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") return p if os.path.exists(p) else None
def enc(arr, px, q): from PIL import Image im = Image.fromarray(arr).convert("RGB") im.thumbnail((px, px)) b = io.BytesIO(); im.save(b, "JPEG", quality=q) return base64.b64encode(b.getvalue()).decode()
def pick(n, k): """k evenly spaced indices spanning 0..n-1, always including the last frame.""" if n <= k: return list(range(n)) return [int(round(i * (n - 1) / (k - 1))) for i in range(k)]
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True); ap.add_argument("--out", required=True) ap.add_argument("--per", type=int, default=3, help="episodes per slice per task") ap.add_argument("--nf", type=int, default=36); ap.add_argument("--px", type=int, default=84) ap.add_argument("--quality", type=int, default=45) args = ap.parse_args()
import pyarrow.parquet as pq, h5py m = np.load(f"{args.cache}/meta.npz", allow_pickle=True) d, s, task = m["ep_demo"].astype(bool), m["ep_success"].astype(bool), m["ep_task"] tasks = [str(t) for t in m["tasks"]] rng = np.random.default_rng(0) out = {"tasks": tasks, "nf": args.nf, "clips": []}
for ti, tname in enumerate(tasks): # demos straight from the stock LIBERO hdf5 h = f"{DEMO}/{tname}_demo.hdf5" if os.path.exists(h): with h5py.File(h, "r") as f: keys = sorted(f["data"].keys(), key=lambda x: int(x.split("_")[1])) for k in keys[:args.per]: rgb = f["data"][k]["obs"]["agentview_rgb"] ids = pick(rgb.shape[0], args.nf) # robosuite stores bottom-up; flip to human-upright like the evaluator fr = [enc(np.asarray(rgb[i])[::-1], args.px, args.quality) for i in ids] out["clips"].append({"slice": "demo", "task": ti, "len": int(rgb.shape[0]), "f": fr}) else: print(f"[clip] MISSING demo hdf5 for {tname}", flush=True) # rollouts from the source parquet for name, mask in (("success", s & ~d), ("failure", ~s & ~d)): cand = np.where(mask & (task == ti))[0] rng.shuffle(cand) got = 0 for e in cand: if got >= args.per: break p = src_parquet(m["ep_src"][e]) if not p: continue try: tb = pq.read_table(p, columns=["image"]) ids = pick(tb.num_rows, args.nf) from PIL import Image fr = [] for i in ids: im = Image.open(io.BytesIO(tb["image"][i].as_py()["bytes"])) fr.append(enc(np.asarray(im.convert("RGB")), args.px, args.quality)) out["clips"].append({"slice": name, "task": ti, "len": int(tb.num_rows), "f": fr}) got += 1 except Exception as ex: print(f"[clip] t{ti} {name}: {str(ex)[:50]}", flush=True) print(f"[clip] task {ti} done ({len(out['clips'])} clips)", flush=True)
json.dump(out, open(args.out, "w")) print(f"[clip] wrote {args.out} {os.path.getsize(args.out)/1e6:.1f} MB " f"{len(out['clips'])} clips", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Sample episodes from each corpus slice and emit a compact JSON bundle for the viewer.
Demos have no frames anywhere on disk (the OGPO demo cache stores latents only, andLIBERO's datasets/ dir is not installed), so frames are rollout-only. End-effectortrajectories come from proprio and exist for all three slices, which makes them the onedirectly comparable view."""import argparse, base64, io, json, os, re, sysimport numpy as np
SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")
def src_parquet(ep_src): m = PAT.search(str(ep_src)) if not m: return None t, b, i, idx = m.groups() p = (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") return p if os.path.exists(p) else None
def jpeg(png_bytes, px, q): from PIL import Image im = Image.open(io.BytesIO(png_bytes)).convert("RGB") im.thumbnail((px, px)) b = io.BytesIO(); im.save(b, "JPEG", quality=q) return base64.b64encode(b.getvalue()).decode()
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--out", required=True) ap.add_argument("--n", type=int, default=100) ap.add_argument("--px", type=int, default=110) ap.add_argument("--quality", type=int, default=55) args = ap.parse_args()
import pyarrow.parquet as pq m = np.load(f"{args.cache}/meta.npz", allow_pickle=True) d, s = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) task, lo, hi = m["ep_task"], m["ep_from"], m["ep_to"] tasks = [str(t) for t in m["tasks"]] prop = np.load(f"{args.cache}/proprio.f32.npy", mmap_mode="r") rng = np.random.default_rng(0)
slices = {"demo": np.where(d)[0], "success": np.where(s & ~d)[0], "failure": np.where(~s & ~d)[0]} out = {"tasks": tasks, "episodes": []} for name, pool in slices.items(): # stratify across tasks so no slice is dominated by one scene pick = [] per = max(1, args.n // max(len(set(task[pool].tolist())), 1)) for t in sorted(set(task[pool].tolist())): c = pool[task[pool] == t] pick += list(rng.choice(c, size=min(per, len(c)), replace=False)) pick = list(rng.permutation(pick))[:args.n] print(f"[viz] {name}: {len(pick)} episodes", flush=True) for e in pick: a, b = int(lo[e]), int(hi[e]) P = np.asarray(prop[a:b], np.float32) k = max(1, len(P) // 60) rec = {"slice": name, "task": int(task[e]), "len": int(b - a), "eef": [[round(float(v), 4) for v in p[:3]] for p in P[::k]], "grip": [round(float(p[6]), 4) for p in P[::k]]} if name != "demo": p = src_parquet(m["ep_src"][e]) if p: try: tb = pq.read_table(p, columns=["image"]) n = tb.num_rows rec["frames"] = [ jpeg(tb["image"][i].as_py()["bytes"], args.px, args.quality) for i in (0, n // 2, n - 1)] except Exception as ex: rec["err"] = str(ex)[:60] out["episodes"].append(rec) with open(args.out, "w") as f: json.dump(out, f) mb = os.path.getsize(args.out) / 1e6 nf = sum(1 for e in out["episodes"] if "frames" in e) print(f"[viz] wrote {args.out} {mb:.1f} MB " f"{len(out['episodes'])} episodes, {nf} with frames", flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#!/bin/bash# Autoresearch for "RSM beats BC-on-demos": screen settings on a VALIDATION set of initial# conditions (protocol V: fresh inits, SEED=7, 20 per task = 200 episodes), select# checkpoints on BOTH sides by arg-max over checkpoints on V, then confirm the winners on# the untouched test protocols A/B x 3 seeds at n=500. Cells are named <arm>_<prop>_s7e7_V.# usage: ibm_autoresearch.sh train | stage1 | bcsel | stage2 <beta> <depth> | stage3 <arm> <env> [prop] [policy] [hop]set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; CACHE=$IB/cache/full_r256S="ssh -o BatchMode=yes -o ConnectTimeout=20"CB=$R/qsg_f/ckpt_best.pt; PROPL=$R/BCdemo_f/policy_last.pt; HOP=$R/HOPdemo_f/policy_r1.ptV="SEED=7, QFCRN=1, QFPART=${QFPART:-256}"; VN=20sub(){ echo "$(NINIT=$VN ./ibm_cell.sh "$1" "$2" 7 1 "$3" </dev/null) $1"; }cell(){ $S bluevela "bsub -G grp_preemptable -q preemptable -r -gpu num=1 -n 8 -M 160G -R 'rusage[mem=160G]' -J $1 -o $R/logs/$1.out -e $R/logs/$1.err -env \"all, CELL=$1, CMD=$2, O=$R\" $IB/run_cell.sh" 2>&1 | grep -o "<[0-9]*>"; }CR="train_rsm.py --cache $CACHE --d-z 256 --enc-width 1024 --flow-width 1024 --flow-depth 4 --chunk 10 --batch 512 --lr 3e-4 --ema 0.995 --var-floor 0.1 --w-reward 1.0 --flow-steps 8 --w-actcon 0.5 --warmup-reward 2000 --in-ram 1 --append-proprio 1 --resume 1 --steps 400000 --eval-every 10000 --seed 0 --reward-mode subgoal --subgoal-dir $R/subgoals_full --success-mask $R/verified_mask.npz --save-every 20000"BC="bc_arm.py --cache $CACHE --chunk 10 --bc-steps 120000 --batch 1024 --lr 3e-4 --norm-pool demos --feat-scale center --policy-features raw --policy-family concat --in-ram 1 --reward-mode soft --success-gamma 0.995 --seed 0 --save-every 10000"case "${1:?}" intrain) # BC with periodic checkpoints (for fair arg-max selection) + two critic variants echo "$(cell BCdemo_c "$BC --pool demos --out $R/BCdemo_c" </dev/null) BCdemo_c" echo "$(cell qsg_b90 "$CR --beta-lo 0.85 --beta-hi 0.95 --beta-q 0.90 --out $R/qsg_b90" </dev/null) qsg_b90" echo "$(cell qsg_wide "$CR --beta-lo 0.93 --beta-hi 0.995 --beta-q 0.98 --flow-width 2048 --flow-depth 6 --out $R/qsg_wide" </dev/null) qsg_wide";;stage1) # beta_q x depth on V, plus the value-free baselines sub plain_DL_s7e7_V $PROPL "QFILTER=0, $V" sub medoid8_DL_s7e7_V $PROPL "SELECT=medoid, QFILTER=8, QFDEPTH=1, QFBETA=0.98, QFPES=0, QFGATE=0, $V" sub random8_DL_s7e7_V $PROPL "SELECT=random, QFILTER=8, QFDEPTH=1, QFBETA=0.98, QFPES=0, QFGATE=0, $V" for b in 90 95 98; do for d in 1 2 3; do sub RSMb${b}d${d}p${QFPART:-256}_DL_s7e7_V $PROPL "CRITIC=$CB, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=$d, QFILTER=8, QFBETA=0.$b, QFPES=0, QFGATE=0, $V" done; done;;bcsel) # plain BC at every periodic checkpoint of BCdemo_c, on V for st in $($S bluevela "ls $R/BCdemo_c/policy_s*.pt 2>/dev/null | sed -E 's/.*policy_s([0-9]+)\.pt/\1/' | sort -n"); do sub plainC${st}_DL_s7e7_V $R/BCdemo_c/policy_s${st}.pt "QFILTER=0, $V" done;;stage2) # around the best (beta, depth): N, selector, Q mode, critic ckpt, pessimism, CRN off b=${2:?}; d=${3:?}; base="CRITIC=$CB, HOPPOL=$HOP, QFDEPTH=$d, QFBETA=0.$b, QFGATE=0, $V" sub RSMb${b}d${d}n32_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=32, QFPES=0, $base" sub RSMb${b}d${d}n16_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=16, QFPES=0, $base" sub RSMb${b}d${d}q90_DL_s7e7_V $PROPL "SELECT=quantile, SELQ=0.9, QFILTER=8, QFPES=0, $base" sub RSMb${b}d${d}q90n32_DL_s7e7_V $PROPL "SELECT=quantile, SELQ=0.9, QFILTER=32, QFPES=0, $base" sub RSMb${b}d${d}near4_DL_s7e7_V $PROPL "SELECT=qnear, QNEARK=4, QFILTER=8, QFPES=0, $base" sub RSMb${b}d${d}fold_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=0, QFMODE=fold, $base" sub RSMb${b}d${d}pes1_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=1, $base" sub RSMb${b}d${d}nocrn_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=0, CRITIC=$CB, HOPPOL=$HOP, QFDEPTH=$d, QFBETA=0.$b, QFGATE=0, SEED=7, QFCRN=0" sub RSMb${b}d${d}cL_DL_s7e7_V $PROPL "SELECT=argmaxq, QFILTER=8, QFPES=0, CRITIC=$R/qsg_f/ckpt.pt, HOPPOL=$HOP, QFDEPTH=$d, QFBETA=0.$b, QFGATE=0, $V";;critsel) # critic checkpoint selection on V: RSM 3-hop at every periodic checkpoint of <run> run=${2:?}; b=${3:-95}; d=${4:-3} for st in $($S bluevela "ls $R/$run/ckpt_s*.pt 2>/dev/null | sed -E 's/.*ckpt_s([0-9]+)\.pt/\1/' | sort -n"); do sub RSMc${run}S${st}_DL_s7e7_V $PROPL "CRITIC=$R/$run/ckpt_s${st}.pt, SELECT=argmaxq, HOPPOL=$HOP, QFDEPTH=$d, QFILTER=8, QFBETA=0.$b, QFPES=0, QFGATE=0, SEED=7, QFCRN=1, QFPART=16" done;;stage3) # confirm: <arm> <env> on A/B x seeds 0,1e1,2e2 at n=500 (proposer = BC ckpt of record) arm=${2:?}; env=${3:?}; prop=${4:-DL}; pol=${5:-$PROPL} for s in 0 1 2; do for P in A B; do F=0; [ $P = B ] && F=1; sfx=$s; [ $s != 0 ] && sfx=${s}e${s} echo "$(./ibm_cell.sh ${arm}_${prop}_s${sfx}_$P $pol $s $F "$env, SEED=$s" </dev/null) ${arm}_${prop}_s${sfx}_$P" done; done;;esac12345678910111213141516#!/bin/bash# Proposer-bias diagnostic on IBM: no env, one GPU. Reuses ibm_eval.sh's environment block.set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/pythonexport RSM_TASKS_FILE=$IB/lib10_tasks.txt RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktreeexport OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorchexport OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.modelexport LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard MUJOCO_GL=egl PYOPENGL_PLATFORM=eglexport TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/"cd $IB/code$PY proposer_bias_diag.py --cache $IB/cache/full_r256 --critic "${CRITIC:-$R/qsg_f/ckpt_best.pt}" \ --hop-policy "${HOP:-$R/HOPdemo_f/policy_r1.pt}" --pol1 $R/BCdemo_f/policy_last.pt --pol2 $R/BCsuccv_f2/policy_r1.pt \ --depth "${DEPTH:-3}" --beta "${BETA:-0.95}" --n "${N:-8}" --frames "${FRAMES:-512}" --particles "${PART:-16}" \ --out "${OUT:-$R/diag/proposer_bias_d${DEPTH:-3}.json}"123456789101112131415161718192021#!/bin/bash# Submit one eval cell on IBM as 10 single-task jobs + 1 assembly job.# ibm_cell.sh <name> <policy> <pseed> <fresh> "<extra env, comma-separated>"# Each task job gets its own GPU (a second env on a used GPU aborts on this EGL driver);# the assembly job runs once all ten are done, resumes from the per-task partials, builds# no env, and writes <name>.json. Wall-clock per cell drops ~10x.set -uo pipefailNAME=${1:?}; POLICY=${2:?}; PSEED=${3:-0}; FRESH=${4:-0}; EXTRA=${5:-}IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logsQ=${LSF_QUEUE:-normal}; G=${LSF_GROUP:-grp_runtime}MANIFEST_ONLY=${MANIFEST_ONLY:-0}COMMON="all, POLICY=$POLICY, OUT=$E/$NAME.json, NINIT=${NINIT:-50}, PSEED=$PSEED, FRESH=$FRESH, CAMRES=256${EXTRA:+, $EXTRA}"ssh -o BatchMode=yes -o ConnectTimeout=20 bluevela "export MANIFEST_ONLY=$MANIFEST_ONLYprintf '%s' \"$COMMON\" > $E/$NAME.cell # manifest: the env this cell was submitted with (retries read it)[ \"\${MANIFEST_ONLY:-0}\" = 1 ] && exit 0for t in 0 1 2 3 4 5 6 7 8 9; do bsub -G $G -q $Q -gpu num=1 -n 8 -M 64G -J ${NAME}_t\$t -o $L/${NAME}_t\$t.out -e $L/${NAME}_t\$t.err -env \"$COMMON, TASKS=\$t, PARTIALONLY=1\" $IB/code/ibm_eval.sh >/dev/null 2>&1donebsub -G $G -q $Q -n 4 -M 32G -J ${NAME}_asm -o $L/${NAME}_asm.out -e $L/${NAME}_asm.err -env \"$COMMON, ASM=1\" $IB/code/ibm_eval.sh 2>&1 | grep -o '<[0-9]*>'" </dev/null 2>&1 | grep -v Authorized | tr -d '<>'12345678910111213#!/bin/bash# CRN diagnostic on IBM: no env, one GPU. Reuses ibm_eval.sh's environment block.set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/pythonexport RSM_TASKS_FILE=$IB/lib10_tasks.txt RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktreeexport OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorchexport OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.modelexport LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standard MUJOCO_GL=egl PYOPENGL_PLATFORM=eglexport TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/"cd $IB/code$PY crn_diag.py --critic $R/qsg_f/ckpt_best.pt --policy "${POLICY:?}" --hop "${HOP:?}" --depth "${DEPTH:-3}" --n "${N:-8}" --states "${STATES:-200}" --particles "${PART:-16}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#!/bin/bash# Closed-loop LIBERO-10 eval on IBM. Same evaluator (eval_closed_loop.py), the pinned venv# (version-identical to MIT), and the same 256 render -- results are admissible alongside# MIT's. Env: POLICY OUT [CRITIC QFCKPT QFILTER SELECT PSEED FRESH NINIT TASKS CAMRES ...]set -uo pipefailIB=/proj/dmfexp/zwhong/rsm_liberoexport RSM_TASKS_FILE=/proj/dmfexp/zwhong/rsm_libero/lib10_tasks.txtexport RSM_WT=/proj/dmfexp/zwhong/rli14_jvq_worktreeexport OGPO_PI05_BASE=/proj/dmfexp/zwhong/rli14_jvq_worktree/models/pi05_base_pytorchexport OGPO_TOKENIZER=/proj/dmfexp/zwhong/rlinf_models/openpi_tokenizer/big_vision/paligemma_tokenizer.modelexport LIBERO_CONFIG_PATH=$IB/libero_config ROBOT_PLATFORM=LIBERO LIBERO_TYPE=standardexport MUJOCO_GL=egl PYOPENGL_PLATFORM=egl_G="$(echo "${CUDA_VISIBLE_DEVICES:-0}" | cut -d, -f1)"; export MUJOCO_EGL_DEVICE_ID="$_G" EGL_DEVICE_ID="$_G"export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1# robosuite EGL context free() aborts the process on this driver: never close envs hereexport RSM_NO_ENV_CLOSE=1export RSM_CACHE_REMAP="/data/pulkitag/users/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/scratch/rli14/rsm_libero_cache/=$IB/cache/,/data/pulkitag/users/rli14/rsm_libero_runs/mit/=$IB/runs/full_r256/"PY=/proj/dmfexp/zwhong/rli14_jvq_worktree/venvs/rlinf-libero-eval-venv/bin/pythonTASKS=${TASKS:-0,1,2,3,4,5,6,7,8,9}; TASKS=${TASKS//;/,} # LSF -env cannot carry commas: pass task lists with ";"cd $IB/code# One LSF job = one GPU = one process. A second OffScreenRenderEnv on a GPU that already# hosted one aborts on this EGL driver (even across processes), so a full n=500 cell is# submitted as 10 single-task jobs (ibm_eval_matrix.sh) plus an assembly job that runs# with every task already in <out>.partial.t* and therefore builds no env.run_eval(){ $PY eval_closed_loop.py ${CRITIC:+--critic "$CRITIC"} --policy "${POLICY:?}" \ --tasks "${TASKS:-0,1,2,3,4,5,6,7,8,9}" --n-init "${NINIT:-50}" --seed "${SEED:-0}" --policy-seed "${PSEED:-0}" --fresh "${FRESH:-0}" \ --cam-res "${CAMRES:-256}" --q-filter "${QFILTER:-0}" --select "${SELECT:-argmaxq}" \ --qf-beta "${QFBETA:-0.98}" --qf-depth "${QFDEPTH:-1}" ${HOPPOL:+--hop-policy "$HOPPOL"} --qf-pessimism "${QFPES:-0}" --qf-gate "${QFGATE:-0}" --qnear-k "${QNEARK:-4}" --qf-crn "${QFCRN:-0}" --qf-particles "${QFPART:-16}" --select-q "${SELQ:-0.9}" ${POLICY2:+--policy2 "$POLICY2"} --q-filter2 "${QFILTER2:-0}" --qf-mode "${QFMODE:-restart}" \ ${QFCKPT:+--qf-ckpt "$QFCKPT"} --policy-temp "${TEMP:-1.0}" --policy-sde "${SDE:-0.0}" --policy-sde-anneal "${SDEANN:-0}" --probe-ood "${PROBEOOD:-0}" \ --suite libero_10 --max-steps "${MAXSTEPS:-520}" --execute 10 --out "${OUT:?}" --partial-only "${PARTIALONLY:-0}"; }if [ "${ASM:-0}" = 1 ]; then # Assembly: wait until every task's partial exists (task jobs retry on EGL aborts), then # run with nothing left to do -- no env is built, the JSON is written. for i in $(seq 1 360); do n=$(ls "${OUT}.partial.t"* 2>/dev/null | wc -l); [ "$n" -ge "${NTASKS:-10}" ] && break; sleep 60; done echo "[eval] assembly: $n/${NTASKS:-10} partials present"; run_eval; echo "[eval] done rc=$?"; exit 0fiRETRY=${RETRY:-0}; PARTIALONLY=${PARTIALONLY:-0}echo "[eval] start $(date -u +%FT%TZ) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}"run_eval; RC=$?echo "[eval] done rc=$RC $(date -u +%FT%TZ)"# Some GPUs are left in a bad EGL state by earlier jobs: the first env creation aborts# (SIGABRT 134 / SIGSEGV 139) with no traceback. Resubmit the task -- a different node is# likely -- up to 6 times. Only for single-task partial jobs, and only if the partial is# still missing.if [ "${PARTIALONLY:-0}" = 1 ] && { [ "$RC" = 134 ] || [ "$RC" = 139 ]; } && [ ! -f "${OUT}.partial.t${TASKS}" ] && [ "${RETRY:-0}" -lt 6 ]; then echo "[eval] EGL abort on $(hostname); resubmitting task ${TASKS} (retry $((RETRY+1)))" bsub -G "${LSF_GROUP:-grp_runtime}" -q "${LSF_QUEUE:-normal}" -gpu num=1 -n 8 -M 64G -J "${LSB_JOBNAME}" \ -o "${LSB_OUTPUTFILE:-/dev/null}" -e "${LSB_ERRORFILE:-/dev/null}" \ -env "all, RETRY=$((RETRY+1))" $IB/code/ibm_eval.shfiexit $RC1234567#!/bin/bash# beta-hop sweep cells only. usage: ibm_eval_depth.sh <proposer_run> <tag> <hop_run> [seeds] [depths]set -uo pipefailPROPRUN=${1:?}; TAG=${2:?}; HOPRUN=${3:?}; SEEDS=${4:-0}; DEPTHS=${5:-2,3}IB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logsS="ssh -o BatchMode=yes -o ConnectTimeout=20"sub(){ ./ibm_cell.sh "$1" "$2" "$3" "$4" "$5"; }12345678910111213141516171819202122232425#!/bin/bash# Extraction matrix on IBM over a given PROPOSER policy: n=500, protocols A/B, evaluator# at 256, one LSF job per cell. usage: ibm_eval_matrix.sh <proposer_run_dir_name> <tag> [seeds]# e.g. ibm_eval_matrix.sh BCdemo_f D 0,1,2 -> cells RSMsg8_D_s0_A ... (D = demos proposer)# ibm_eval_matrix.sh BCsuccv_f2 S 0 -> the successes proposer ladderset -uo pipefailPROPRUN=${1:?proposer run dir}; TAG=${2:?tag}; SEEDS=${3:-0}; HOPRUN=${4:-} # 4th arg: latent hop policy run dir -> depth 2/3 cellsIB=/proj/dmfexp/zwhong/rsm_libero; R=$IB/runs/full_r256; E=$R/eval; L=$R/logsS="ssh -o BatchMode=yes -o ConnectTimeout=20"sub(){ ./ibm_cell.sh "$1" "$2" "$3" "$4" "$5"; }PROP=$R/$PROPRUN/policy_r1.pt; BON="QFILTER=8, QFBETA=0.98, QFDEPTH=1, QFPES=0, QFGATE=0"for s in ${SEEDS//,/ }; do for P in A B; do F=0; [ $P = B ] && F=1 echo "$(sub RSMsg8_${TAG}_s${s}_$P $PROP $s $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=argmaxq, $BON") RSMsg8_$TAG s$s $P" echo "$(sub medoid8_${TAG}_s${s}_$P $PROP $s $F "SELECT=medoid, $BON") medoid8_$TAG s$s $P" echo "$(sub plain_${TAG}_s${s}_$P $PROP $s $F "QFILTER=0") plain_$TAG s$s $P"done; done# beta-hop sweep (depth 2, 3) with the matching latent hop policy (4th arg)[ -n "$HOPRUN" ] && HOP=$R/$HOPRUN && for D in 2 3; do for s in ${SEEDS//,/ }; do for P in A B; do F=0; [ $P = B ] && F=1 echo "$(sub RSMsg8d${D}_${TAG}_s${s}_$P $PROP $s $F "CRITIC=$R/qsg_f/ckpt_best.pt, SELECT=argmaxq, HOPPOL=$HOP/policy_r1.pt, QFDEPTH=$D, QFILTER=8, QFBETA=0.98, QFPES=0, QFGATE=0") RSMsg8 depth$D $TAG s$s $P"done; done; donefor P in A B; do F=0; [ $P = B ] && F=1 echo "$(sub RSMind8_${TAG}_s0_$P $PROP 0 $F "CRITIC=$R/qind_f/ckpt_best.pt, SELECT=argmaxq, $BON") RSMind8_$TAG s0 $P" echo "$(sub random8_${TAG}_s0_$P $PROP 0 $F "SELECT=random, $BON") random8_$TAG s0 $P" [ -n "${IQLQ:-}" ] && echo "$(sub IQL8_${TAG}_s0_$P $PROP 0 $F "QFCKPT=$IQLQ, SELECT=argmaxq, $BON") IQL8_$TAG s0 $P"done.gitattributes+24
frozen/rsm_libero_rsmpi/stats_full.sbatchAdded+18
frozen/rsm_libero_rsmpi/stats_r256.sbatchAdded+18
frozen/rsm_libero_rsmpi/subgoals_from_npz.pyAdded+24
frozen/rsm_libero_rsmpi/sweep_horizon.pyAdded+140
frozen/rsm_libero_rsmpi/sync_to_ibm.shAdded+75
frozen/rsm_libero_rsmpi/test_dwm.pyAdded+262
frozen/rsm_libero_rsmpi/test_lewm_port.pyAdded+143
frozen/rsm_libero_rsmpi/their_ctl.sbatchAdded+16
frozen/rsm_libero_rsmpi/their_trainer_control.pyAdded+46
frozen/rsm_libero_rsmpi/thr_test.pyAdded+32
frozen/rsm_libero_rsmpi/train_goal_clf.pyAdded+122
frozen/rsm_libero_rsmpi/train_lewm.pyAdded+244
frozen/rsm_libero_rsmpi/train_rsm.pyAdded+1312
frozen/rsm_libero_rsmpi/train_rsm_dwm.pyAdded+765
frozen/rsm_libero_rsmpi/train_slurm.sbatchAdded+22
frozen/rsm_libero_rsmpi/verify_cpu.sbatchAdded+19
frozen/rsm_libero_rsmpi/verify_full.sbatchAdded+20
frozen/rsm_libero_rsmpi/verify_fullg.sbatchAdded+22
frozen/rsm_libero_rsmpi/verify_successes.pyAdded+97
frozen/rsm_libero_rsmpi/verify_successes.sbatchAdded+20
frozen/rsm_libero_snap_20261030/.pytest_cache/README.mdAdded+8
frozen/rsm_libero_snap_20261030/CLAUDE.mdAdded+291
frozen/rsm_libero_snap_20261030/FINDINGS.mdAdded+344
frozen/rsm_libero_snap_20261030/README.mdAdded+737
frozen/rsm_libero_snap_20261030/audit_logged_goal.pyAdded+93
frozen/rsm_libero_snap_20261030/autoresearch_driver.pyAdded+78
frozen/rsm_libero_snap_20261030/awr.pyAdded+275
frozen/rsm_libero_snap_20261030/bc_arm.pyAdded+168
frozen/rsm_libero_snap_20261030/calib_dwm.pyAdded+106
frozen/rsm_libero_snap_20261030/capture_init_feats.pyAdded+88
frozen/rsm_libero_snap_20261030/crn_diag.pyAdded+58
frozen/rsm_libero_snap_20261030/data.pyAdded+644
frozen/rsm_libero_snap_20261030/df_readout.pyAdded+228
frozen/rsm_libero_snap_20261030/dinowm_readout.pyAdded+168
frozen/rsm_libero_snap_20261030/dwm_model.pyAdded+580
frozen/rsm_libero_snap_20261030/dwm_readout.pyAdded+314
frozen/rsm_libero_snap_20261030/dwm_readout_timing.pyAdded+78
frozen/rsm_libero_snap_20261030/encode_parquet.pyAdded+83
frozen/rsm_libero_snap_20261030/encode_t5.pyAdded+52
frozen/rsm_libero_snap_20261030/eval_closed_loop.pyAdded+1025
frozen/rsm_libero_snap_20261030/extract_clips.pyAdded+98
frozen/rsm_libero_snap_20261030/extract_viz.pyAdded+90
frozen/rsm_libero_snap_20261030/ibm_autoresearch.shAdded+53
frozen/rsm_libero_snap_20261030/ibm_bias_diag.shAdded+16
frozen/rsm_libero_snap_20261030/ibm_cell.shAdded+21
frozen/rsm_libero_snap_20261030/ibm_crn_diag.shAdded+13
frozen/rsm_libero_snap_20261030/ibm_eval.shAdded+51
frozen/rsm_libero_snap_20261030/ibm_eval_depth.shAdded+7
frozen/rsm_libero_snap_20261030/ibm_eval_matrix.shAdded+25