rsm_rise code snapshot (HF_PUSH_ALL) (part 13)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/merge_verify.pyAdded+60
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/mislabel_report.pyAdded+41
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/model.pyAdded+528
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pack.pyAdded+278
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/paired_test.pyAdded+55
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/parl_rsm.pyAdded+305
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pooled_test.pyAdded+25
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_actcon.pyAdded+95
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_action_info.pyAdded+97
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_crn.pyAdded+105
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits.pyAdded+46
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits2.pyAdded+39
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_perturb.pyAdded+81
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_pessimism.pyAdded+73
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_qf.pyAdded+76
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/proposer_bias_diag.pyAdded+105
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/q_vs_return_diag.pyAdded+85
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/recheck_encoding.pyAdded+157
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reencode_rollouts.pyAdded+121
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report.pyAdded+96
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report_arms.pyAdded+95
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rerender_rollouts.pyAdded+318
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reward_diag.pyAdded+56
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rsm_main.pyAdded+325
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/run_ope.pyAdded+171
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/subgoals_from_npz.pyAdded+24
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/sweep_horizon.pyAdded+140
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_dwm.pyAdded+262
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_lewm_port.pyAdded+143
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/their_trainer_control.pyAdded+46
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/thr_test.pyAdded+32
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_goal_clf.pyAdded+122
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_lewm.pyAdded+244
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm.pyAdded+1287
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm_dwm.pyAdded+765
- rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/verify_successes.pyAdded+97
- rsm_rise/scripts/real/v7/nonmarkov/rsm_nm_qall.pyAdded+187
- rsm_rise/scripts/real/v7/nonmarkov/run_eval_dw_nm.shAdded+35
- rsm_rise/scripts/real/v7/nonmarkov/run_eval_iql_nm.shAdded+33
- rsm_rise/scripts/real/v7/nonmarkov/run_eval_rsm_nm.shAdded+27
- rsm_rise/scripts/real/v7/nonmarkov/score_iql_nm.pyAdded+105
- rsm_rise/scripts/real/v7/nonmarkov/smoke.sbatchAdded+61
- rsm_rise/scripts/real/v7/nonmarkov/smoke2.sbatchAdded+30
- rsm_rise/scripts/real/v7/nonmarkov/smokeC.sbatchAdded+30
- rsm_rise/scripts/real/v7/nonmarkov/smoke_rsmnm.sbatchAdded+23
- rsm_rise/scripts/real/v7/nonmarkov/table.pyAdded+122
- rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nm.pyAdded+224
- rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nmxn.pyAdded+232
- rsm_rise/scripts/real/v7/nonmarkov/train_iql_nm.pyAdded+121
- rsm_rise/scripts/real/v7/nonmarkov/train_iql_nmxn.pyAdded+124
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Merge the per-task replay-verification shards into one success mask.
Output: keep[i] over cache episode indices. An episode stays in the success pool onlyif it is a demo (ground truth, never replayed), or a rollout whose logged successREPRODUCED when its actions were re-executed from the logged sim_state. Episodes thatcould not be resolved (source parquet missing) are dropped from the success pool ratherthan trusted -- the whole point is that an unverified success is not a success."""import argparse, glob, numpy as np
ap = argparse.ArgumentParser()ap.add_argument("--cache", required=True)ap.add_argument("--shards", required=True, help="REPLAY shards (reproducibility)")ap.add_argument("--goal-shards", default="", help="GOAL-AUDIT shards (goal predicate at the logged final state). " "DIAGNOSTIC ONLY -- do NOT filter on this. It answers 'was the label " "honest about the state the episode reached', which is not the " "admissibility question. Admissibility is REPRODUCIBILITY in the eval " "environment; see --shards.")ap.add_argument("--out", required=True)ap.add_argument("--keep-unresolvable", type=int, default=0)a = ap.parse_args()
m = np.load(f"{a.cache}/meta.npz", allow_pickle=True)demo, succ = m["ep_demo"].astype(bool), m["ep_success"].astype(bool)keep = demo.copy() # demos always keptseen = np.zeros(len(demo), bool)rep = unres = 0# ADMISSIBILITY RULE: a trajectory may train an offline learner only if its reward# labels REPRODUCE in the environment we evaluate in. A label that was honest about the# state its own run reached is still inadmissible if replaying those actions here does# not get there -- those (s,a,r) tuples describe different dynamics than the ones the# policy will be scored against, which is exactly what breaks offline RL.src, mode = a.shards, "REPLAY in the eval environment (admissibility)"if a.goal_shards: print("[merge] NOTE: goal-audit shards given but NOT used as the filter; " "they are diagnostic. Filtering on reproducibility.")print(f"[merge] filtering on: {mode}")for f in sorted(glob.glob(f"{src}/task*.npz")): z = np.load(f, allow_pickle=True) if a.goal_shards: r = z["rows"]; idx, ver = r[:, 0], r[:, 1] else: idx, ver = z["ep_index"], z["verified"] for e, v in zip(idx, ver): seen[e] = True if v == 1: keep[e] = True; rep += 1 elif v < 0: unres += 1 if a.keep_unresolvable: keep[e] = Truen_succ = int((succ & ~demo).sum())missing = int((succ & ~demo & ~seen).sum())np.savez(a.out, keep=keep, n_checked=int(seen.sum()), n_reproduced=rep)print(f"[merge] rollout successes in cache : {n_succ}")print(f"[merge] checked : {int(seen.sum())} (missing shards: {missing})")print(f"[merge] reproduced : {rep} ({rep/max(seen.sum(),1):.1%})")print(f"[merge] unresolvable : {unres} " f"({'kept' if a.keep_unresolvable else 'DROPPED'})")print(f"[merge] success pool: {int((succ).sum())} -> {int(keep.sum())} episodes")print(f"[merge] wrote {a.out}")1234567891011121314151617181920212223242526272829303132333435363738394041"""Per-task mislabelling breakdown: episodes AND reward-frames affected.
An episode's success bit is one label, but the reward is per-frame and derived fromit, so a single mislabelled episode corrupts every frame it occupies. Both counts arereported because they answer different questions: how much of the success POOL isfake (episodes), and how much of the reward SIGNAL is wrong (frames)."""import glob, sys, numpy as npV = sys.argv[1] if len(sys.argv) > 1 else "/data/pulkitag/users/rli14/rsm_libero_runs/verify"C = "/data/pulkitag/users/rli14/rsm_libero_cache/full_demo"m = np.load(f"{C}/meta.npz", allow_pickle=True)elen = (m["ep_to"] - m["ep_from"]).astype(int)tn = [str(t) for t in m["tasks"]]d, s = m["ep_demo"].astype(bool), m["ep_success"].astype(bool)rows, TE, TB, TF, TFB = [], 0, 0, 0, 0for f in sorted(glob.glob(f"{V}/task*.npz")): z = np.load(f); t = int(z["task"]) idx, ver = z["ep_index"], z["verified"] ok = ver >= 0; idx, ver = idx[ok], ver[ok] if len(idx) == 0: rows.append((t, 0, 0, 0, 0)); continue bad = idx[ver == 0] nf, nfb = int(elen[idx].sum()), int(elen[bad].sum()) rows.append((t, len(idx), len(bad), nf, nfb)) TE += len(idx); TB += len(bad); TF += nf; TFB += nfbprint(f"{'task':4s} {'name':36s} {'checked':>8s} {'MISLAB':>7s} {'rate':>6s} " f"{'frames':>9s} {'bad frames':>11s} {'%':>6s}")for t, n, b, nf, nfb in sorted(rows): if n == 0: print(f" {t:<3d} {tn[t][:36]:36s} {'--':>8s} {'--':>7s} {'--':>6s}" f" {'--':>9s} {'--':>11s} {'--':>6s} (no logged successes)") continue print(f" {t:<3d} {tn[t][:36]:36s} {n:8d} {b:7d} {b/n:6.1%} " f"{nf:9,d} {nfb:11,d} {nfb/nf:6.1%}")nd = sum(1 for r in rows if r[1] > 0)print(f"\n TOTAL over {nd} tasks with successes: {TE} checked, " f"{TB} mislabelled ({TB/max(TE,1):.1%})")print(f" reward frames: {TF:,} in verified episodes, {TFB:,} carry a wrong label " f"({TFB/max(TF,1):.1%})")npool = int((s & ~d).sum())print(f" rollout successes in cache: {npool}; checked {TE} ({TE/npool:.0%})" f" -> projected ~{round(npool*TB/max(TE,1))} mislabelled at the pooled rate")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528"""Nets for RSM on the LIBERO-10 pi0.5 rollout corpus.
Design follows the unified-RSM recipe on gen_q `main` (ogbench_unified_rsm/RECIPE.md,notes/COLLAPSE_ANALYSIS.md), adapted from goal-ball OGBench to sparse-success LIBERO:
* beta BAND training, not a single discount (RECIPE "train beta [0.8,0.98]") * Fourier features on log(-log beta) (RECIPE "fourier_unit, n_fourier=6") * residual successor z' = z + delta, with delta divided by the per-dimension dataset RMS of (z_fut - z_now) (RECIPE v6.1 "horizon-normalize then per-dimension divide by rms((s'-s)_i)") * EMA target encoder supplies the future target, stop-grad, plus a per-coordinate variance floor (RECIPE "variance floor keeps the embedding from collapsing"; smolvla_rsm METHOD.md) * action chunk conditions the occupancy on an equal footing with the task embedding, via concat + FiLM (RECIPE v6 "condition on g and a equally")
What is deliberately NOT ported: the goal-ball arrival likelihood (`q_readout=lik`,`p = exp(-d^2/2 tol^2)` on privileged xy/xyz). LIBERO has no privileged success ballin this latent, so the read-out is a learned reward decoder over the same latent, asthe image branch of CLAUDE.md requires.
COLLAPSE_ANALYSIS lesson carried over: a value that scores STATES but cannot rankACTIONS produces flat batch metrics and a closed-loop cliff. The occupancy here isaction-conditioned for exactly that reason, and action ranking is the headlinediagnostic rather than state ranking."""from __future__ import annotationsimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
def beta_fourier(beta: torch.Tensor, n: int = 6) -> torch.Tensor: """Fourier features on the log-horizon of a discount in (0,1).""" x = torch.log(-torch.log(beta.clamp(1e-6, 1 - 1e-6))) fr = torch.arange(1, n + 1, device=beta.device, dtype=beta.dtype) a = x[:, None] * fr[None] return torch.cat([a.sin(), a.cos(), x[:, None]], -1) # 2n+1
def time_embed(t: torch.Tensor, dim: int = 64) -> torch.Tensor: half = dim // 2 fr = torch.exp(-np.log(10000.0) * torch.arange(half, device=t.device, dtype=t.dtype) / half) a = t[:, None] * fr[None] * 1000.0 return torch.cat([a.sin(), a.cos()], -1)
def mlp(sizes, act=nn.SiLU, out_act=False, norm=False): layers = [] for i in range(len(sizes) - 1): layers.append(nn.Linear(sizes[i], sizes[i + 1])) if i < len(sizes) - 2 or out_act: if norm: layers.append(nn.LayerNorm(sizes[i + 1])) layers.append(act()) return nn.Sequential(*layers)
class TaskCond(nn.Module): """Task conditioning: a frozen T5 sentence embedding, projected.
The alternative -- nn.Embedding(n_task, d_task) -- conditions on an INDEX. It carries nothing about what the task is, cannot transfer to a held-out instruction, and gives the network a shortcut that removes any pressure on the visual latent to represent the instruction. Passing t5_path swaps in the frozen sentence embedding; omitting it keeps the index embedding so old checkpoints still load. """
def __init__(self, n_task: int, d_task: int = 64, t5_path: str = ""): super().__init__() self.t5 = bool(t5_path) if self.t5: import numpy as _np emb = _np.load(t5_path)["emb"].astype("float32") emb = emb / (_np.linalg.norm(emb, axis=1, keepdims=True) + 1e-6) self.register_buffer("E", torch.tensor(emb), persistent=True) self.proj = nn.Linear(emb.shape[1], d_task) else: # hold the table as `weight` and look it up with F.embedding, so the # state_dict key stays `<owner>.task.weight` -- exactly what # nn.Embedding produced. Wrapping it as a submodule would rename the # key and break every checkpoint written before this change. self.weight = nn.Parameter(torch.randn(n_task, d_task) * 0.02)
def forward(self, task): if self.t5: return self.proj(self.E[task]) return F.embedding(task, self.weight)
class Encoder(nn.Module): """OGPO 4096-d -> compact reward-predictive latent."""
def __init__(self, d_in: int, d_z: int = 256, width: int = 1024, depth: int = 3): super().__init__() self.net = mlp([d_in] + [width] * depth + [d_z], norm=True) self.d_z = d_z
def forward(self, x): return self.net(x)
class IdentityEncoder(nn.Module): """`--enc identity`: the (z-scored) input feature IS the latent. No parameters, so the EMA target, the variance floor and the reward warm-up are all no-ops. Used when the feature is a frozen foundation-model embedding modelled directly (rsm_rise: DINOv2 CLS|GeM per camera + proprio, 1545-d), as the OCBench visual recipe did."""
def __init__(self, d_in: int): super().__init__() self.d_z = int(d_in)
def forward(self, x): return x
class PCAEncoder(nn.Module): """`--pca-dim k`: a FIXED linear map fitted once on training frames (not a learned encoder). z = (x - mean) @ W with W [d_in, k] orthonormal columns (top-k right singular vectors), so the pseudo-inverse is W^T: back(z) = z @ W^T + mean. mean/W are persistent buffers, saved in the checkpoint's `enc` state_dict and reloaded by is_ope.load_critic."""
def __init__(self, d_in: int, k: int): super().__init__() self.d_z = int(k) self.register_buffer("mean", torch.zeros(int(d_in))) self.register_buffer("W", torch.zeros(int(d_in), int(k)))
@torch.no_grad() def fit(self, X): """X [n, d_in] float tensor of (z-scored) training states. Returns explained-variance ratio.""" self.mean.copy_(X.mean(0)) _u, S, Vh = torch.linalg.svd(X - self.mean, full_matrices=False) self.W.copy_(Vh[: self.d_z].T) var = S.pow(2) return float(var[: self.d_z].sum() / var.sum())
def forward(self, x): return (x - self.mean) @ self.W
def back(self, z): return z @ self.W.T + self.mean
class RewardHead(nn.Module): """Goal-conditioned reward decoder R(z, task) -> logit of 'task complete here'."""
def __init__(self, d_z: int, n_task: int, d_task: int = 64, width: int = 512, t5_path: str = ""): super().__init__() self.task = TaskCond(n_task, d_task, t5_path) self.net = mlp([d_z + d_task, width, width, 1])
def forward(self, z, task): return self.net(torch.cat([z, self.task(task)], -1)).squeeze(-1)
class GoalLikelihood(nn.Module): """Dense two-tower goal likelihood -- the recipe's `q_readout=lik`.
`l = sigmoid(<phi(z), psi(g)> / tau)` with phi, psi unit-norm MLPs. Asymmetric on purpose (phi != psi), because "z is at goal g" is not "g is at goal z".
Why this replaces a binary success head: the success head is SPARSE -- terminal labels are ~0.5% of frames, so almost every sampled future reads ~0 and Q is near-constant in the action, leaving nothing to rank. This gives EVERY (z, g) pair a probability, which is what makes the read-out able to separate actions.
Trained by in-batch InfoNCE: positive is (z + eps, z), negatives are the other goals in the batch. Recipe knobs: goal_feat_dim 256, towers (512,)x3, goal_nce_tau 0.2, nce_noise 0.1. The scorer is STOP-GRAD in the Q path -- NCE is the only gradient into the towers. """
def __init__(self, d_z: int, d_feat: int = 256, width: int = 512, depth: int = 3, tau: float = 0.2, noise: float = 0.1): super().__init__() self.phi = mlp([d_z] + [width] * depth + [d_feat], norm=True) self.psi = mlp([d_z] + [width] * depth + [d_feat], norm=True) self.tau = tau self.noise = noise
def _emb(self, net, z): e = net(z) return e / e.norm(dim=-1, keepdim=True).clamp_min(1e-6)
def logit(self, z, g): return (self._emb(self.phi, z) * self._emb(self.psi, g)).sum(-1) / self.tau
def forward(self, z, g): return torch.sigmoid(self.logit(z, g))
def nce_loss(self, z): """In-batch InfoNCE. Positive (z+eps, z); negatives are other batch rows.""" zp = z + self.noise * torch.randn_like(z) a = self._emb(self.phi, zp) b = self._emb(self.psi, z) logits = (a @ b.t()) / self.tau tgt = torch.arange(z.shape[0], device=z.device) return F.cross_entropy(logits, tgt)
class FiLM(nn.Module): def __init__(self, d_cond, d_h): super().__init__() self.to_gb = nn.Linear(d_cond, 2 * d_h)
def forward(self, h, c): g, b = self.to_gb(c).chunk(2, -1) return h * (1 + g) + b
class OccFlow(nn.Module): """Conditional flow-matching velocity for the beta-discounted successor.
Predicts the velocity of the RESIDUAL delta = (z_fut - z_now) / rms, so the network never has to re-encode z_now's own coordinates. """
def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, width: int = 1024, depth: int = 4, n_fourier: int = 6, t5_path: str = "", norm: bool = False, dropout: float = 0.0, d_cond_z: int = 0): super().__init__() self.task = TaskCond(n_task, d_task, t5_path) # V7_NONMARKOV: d_cond_z > 0 = width of the CONDITIONING state (history H(t), 3*d_z); the # flowed variable and the output stay d_z. 0 (default) = d_z, i.e. unchanged. self.d_out = d_z d_cond = (d_cond_z or d_z) + d_act + d_task + (2 * n_fourier + 1) self.cond = mlp([d_cond, width, width], out_act=True, norm=True) self.in_proj = nn.Linear(d_z + 128, width) # norm=True (train_rsm.py --flow-norm 1): LayerNorm inside every residual block and on the # stream before the output head. rsm_rise measured the un-normalised trunk amplifying # held-out states (velocity 170 -> 8500 over 8 Euler steps on val rows, 8 -> 11 on train). # Default False keeps every existing checkpoint loadable (Identity has no parameters). self.blocks = nn.ModuleList([mlp([width, width], out_act=True, norm=norm) for _ in range(depth)]) if dropout > 0: # appended INSIDE each block's Sequential so the Linear keeps state_dict index 0 for blk in self.blocks: blk.append(nn.Dropout(dropout)) self.films = nn.ModuleList([FiLM(width, width) for _ in range(depth)]) self.final_norm = nn.LayerNorm(width) if norm else nn.Identity() self.out = nn.Linear(width, d_z) self.n_fourier = n_fourier
def forward(self, z_now, a_chunk, task, beta, x_k, k): c = self.cond(torch.cat( [z_now, a_chunk, self.task(task), beta_fourier(beta, self.n_fourier)], -1)) h = self.in_proj(torch.cat([x_k, time_embed(k, 128)], -1)) for blk, film in zip(self.blocks, self.films): h = h + film(blk(h), c) return self.out(self.final_norm(h))
class RatioNet(nn.Module): """Per-decision density-ratio classifier.
Trained to separate a LOGGED action chunk at state z (from the behavior policy mu) from a chunk freshly SAMPLED from the target policy pi at the same z. On balanced classes the logit is exactly log pi/mu, so we never need a normalized density for either policy -- which matters because mu here is a flow model sampled as an SDE and has no tractable likelihood. This is the substitute for the notes' w_{t,k} = prod pi(a_j|s_j)/mu(a_j|s_j). """
def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, width: int = 512, depth: int = 3, t5_path: str = ""): super().__init__() self.task = TaskCond(n_task, d_task, t5_path) self.net = mlp([d_z + d_act + d_task] + [width] * depth + [1], norm=True)
def forward(self, z, a_chunk, task): return self.net(torch.cat([z, a_chunk, self.task(task)], -1)).squeeze(-1)
class EndpointRatio(nn.Module): """Rao-Blackwellized endpoint weight w*(z,a,z') = d^pi_beta / d^mu_beta.
Regression target is the chunk-level product of per-decision ratios; the squared-loss minimizer is the conditional expectation given the endpoint, which is precisely the notes' Section-9 identity. Predicts LOG w for stability. """
def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, width: int = 512, depth: int = 3, t5_path: str = ""): super().__init__() self.task = TaskCond(n_task, d_task, t5_path) self.net = mlp([2 * d_z + d_act + d_task] + [width] * depth + [1], norm=True) # start at w ~= 1: softplus(0.5413) = 1.0 nn.init.zeros_(self.net[-1].weight); nn.init.constant_(self.net[-1].bias, 0.5413)
def forward(self, z, a_chunk, z_fut, task): """Returns w > 0 directly. softplus rather than exp: under squared loss an exponential head has gradient proportional to w itself, so once it undershoots it stops learning -- observed as E_mu[w]=0.45 against a target of 1.0. softplus keeps the gradient alive as w -> 0.""" o = self.net(torch.cat([z, a_chunk, z_fut, self.task(task)], -1)).squeeze(-1) return F.softplus(o)
class RawFeat(nn.Module): """Feature map for policy extraction: full observation, CENTERED only.
Two separate findings drive this.
(1) The policy must not read the critic's latent. That encoder is trained to predict REWARD, so its bottleneck keeps what separates success from failure and discards what an action head needs. Measured: a flow policy on the 264-d reward latent beat a predict-the-mean action baseline by only 14% in MSE, with a biased gripper channel.
(2) It must not read PER-DIM Z-SCORED features either. Whitening gives all 4104 dimensions equal variance, which amplifies thousands of near-dead directions up to the scale of the informative ones. Measured on BC-on-demos: action loss rose 0.158 -> 0.355 and closed-loop success fell from 3/10 to 0/10 on task 2 when the policy input was whitened.
What the input actually needed was CENTERING: the mean feature vector has norm 51.1 against a per-frame deviation of norm 9.0, so 85% of the raw magnitude is a constant carrying no information. Centering removes that without touching the relative importance of dimensions.
The data layer hands over z-scored features (the critic wants those), so this module rescales them back by `scale` = sd / mean(sd) over the visual block, recovering (x - mu) / s_global exactly. Proprio keeps its per-dim z-score: its 8 dims are genuinely different units, spanning std 0.014 to 1.372."""
def __init__(self, d, scale=None): super().__init__() self.d_out = int(d) if scale is None: scale = torch.ones(int(d)) self.register_buffer("scale", torch.as_tensor(scale, dtype=torch.float32))
def forward(self, x): return x * self.scale
class ConcatFlowPolicy(nn.Module): """Flow-matching action-chunk policy, CONCATENATION-conditioned.
A faithful port of the head behind this lane's 0.584 bcdemos bar. The difference from FlowPolicy is not cosmetic: FlowPolicy squeezes the whole 4104-d observation through a `cond` MLP and injects it only as FiLM scale and shift, so the action branch never sees the observation directly. Measured consequence at identical chunk (10), width (1024), depth (4) and demo cache: held-out ODE-sampled reconstruction MSE was 0.0480 for FiLM against 0.00319 for the concatenation head that reaches 0.584 -- a 15x gap that no amount of normalisation or feature choice closed.
Everything else matches that recipe: SiLU, no normalisation layers, 64-d task embedding, 128-d sinusoidal flow-time embedding, the noisy chunk fed straight in, and 10 Euler steps at sampling time. """
def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, width: int = 1024, depth: int = 4, steps: int = 10, t5_path: str = ""): super().__init__() self.task = TaskCond(n_task, d_task, t5_path) ind = d_z + d_task + 128 + d_act layers = [] for i in range(depth): layers += [nn.Linear(ind if i == 0 else width, width), nn.SiLU()] layers += [nn.Linear(width, d_act)] self.net = nn.Sequential(*layers) self.d_act = d_act self.steps = steps
def velocity(self, z, task, a_k, k): return self.net(torch.cat([z, self.task(task), time_embed(k, 128), a_k], -1))
def fm_loss(self, z, task, a, reduce=True): k = torch.rand(a.shape[0], device=a.device) noise = torch.randn_like(a) a_k = (1 - k)[:, None] * a + k[:, None] * noise per = (self.velocity(z, task, a_k, k) - (a - noise)).pow(2).mean(-1) return per.mean() if reduce else per
@torch.no_grad() def sample(self, z, task, temp: float = 1.0, sde: float = 0.0, sde_anneal: bool = False): """temp scales the initial noise; sde injects noise DURING integration.
sde_anneal scales the injected noise by the remaining noise fraction k, so the perturbation is large early (where the drift can still re-project it onto the manifold) and vanishes at the last steps; constant sde leaves an un-corrected sde*sqrt(dt) kick on the final action.
These buy diversity in different places and it matters here. temp inflates the PRIOR the ODE transports, so every sample starts further out and the map carries it somewhere the data never was -- measured closed-loop 0.550 at temp 1.0, 0.310 at 1.5, 0.000 at 2.0, with the ranker held fixed. sde follows the learned drift and perturbs along the way, which keeps samples near the manifold the drift was fitted on. That is the mechanism that produced usable candidate diversity in the related lane.
Flow matching learns a near-deterministic map for a unimodal conditional, so a trained policy's samples barely differ: measured action std 0.029 at 120k steps and 0.053 at 20k, against 0.421 in the data. PARL cannot rank N copies of one action, so temp>1 widens the prior the ODE transports and gives the critic something to choose between. Candidates further from the mode are exactly what the value is there to accept or reject. """ return self.sample_eps(z, task, torch.randn(z.shape[0], self.d_act, device=z.device), temp=temp, sde=sde, sde_anneal=sde_anneal)
def sample_eps(self, z, task, eps, temp: float = 1.0, sde: float = 0.0, sde_anneal: bool = False): """sample() with caller-supplied initial noise eps [B, d_act] (common random numbers across candidates); the SDE perturbations, if any, stay independent.""" x = eps * temp dt = 1.0 / self.steps for s in range(self.steps): k = torch.full((z.shape[0],), 1 - s / self.steps, device=z.device) x = x + self.velocity(z, task, x, k) * dt if sde: # Euler-Maruyama style: the drift is followed exactly and the # perturbation scales as sqrt(dt), so total injected variance is # independent of the number of solver steps. sc = sde * (dt ** 0.5) if sde_anneal: sc = sc * float(k[0]) x = x + sc * torch.randn_like(x) return x
class BCHead(nn.Module): """Gaussian action-chunk policy over the frozen latent: pi(A | z, task).
Deliberately a tractable Gaussian, unlike the flow-SDE behavior policy: the target policy is the one we must SAMPLE from many times per state (for the ratio classifier and for AWR), and a closed form keeps that cheap. """
def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, width: int = 1024, depth: int = 4, log_std_init: float = -1.0, t5_path: str = ""): super().__init__() self.task = TaskCond(n_task, d_task, t5_path) self.trunk = mlp([d_z + d_task] + [width] * depth, out_act=True, norm=True) self.mu = nn.Linear(width, d_act) self.log_std = nn.Parameter(torch.full((d_act,), log_std_init))
def forward(self, z, task): h = self.trunk(torch.cat([z, self.task(task)], -1)) return self.mu(h), self.log_std.clamp(-5.0, 2.0)
def sample(self, z, task, n: int = 1): mu, ls = self(z, task) if n == 1: return mu + torch.randn_like(mu) * ls.exp() mu = mu[:, None].expand(-1, n, -1) return mu + torch.randn_like(mu) * ls.exp()
def sample_eps(self, z, task, eps): """Sample with caller-supplied standard-normal noise (common random numbers).""" mu, ls = self(z, task) return mu + eps * ls.exp()
def log_prob(self, z, task, a): mu, ls = self(z, task) var = (2 * ls).exp() return (-0.5 * ((a - mu) ** 2 / var + 2 * ls + np.log(2 * np.pi))).sum(-1)
class FlowPolicy(nn.Module): """Flow-matching action-chunk policy pi(A | z, task).
Replaces the Gaussian head because of a measured failure: with a Gaussian target and a flow-SDE behaviour policy, the density-ratio classifier hit 99.9-100% accuracy. It was not separating good actions from bad, it was separating "Gaussian sample" from "flow sample" -- a parametric-family artifact -- which drove E_mu[W] to 0.18 against a required 1.0 and made the importance weights meaningless. Matching the family removes that shortcut.
No tractable density, which is fine: the classifier supplies the ratio, and AWR weights the per-sample flow-matching loss instead of a log-likelihood (the same substitution the smolvla AWR run used). """
def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, width: int = 1024, depth: int = 4, steps: int = 8, t5_path: str = ""): super().__init__() self.task = TaskCond(n_task, d_task, t5_path) self.cond = mlp([d_z + d_task, width, width], out_act=True, norm=True) self.in_proj = nn.Linear(d_act + 128, width) self.blocks = nn.ModuleList([mlp([width, width], out_act=True) for _ in range(depth)]) self.films = nn.ModuleList([FiLM(width, width) for _ in range(depth)]) self.out = nn.Linear(width, d_act) self.d_act = d_act self.steps = steps
def velocity(self, z, task, a_k, k): c = self.cond(torch.cat([z, self.task(task)], -1)) h = self.in_proj(torch.cat([a_k, time_embed(k, 128)], -1)) for blk, film in zip(self.blocks, self.films): h = h + film(blk(h), c) return self.out(h)
def fm_loss(self, z, task, a, reduce=True): """Per-sample flow-matching loss; stands in for -log pi(a|z).""" k = torch.rand(a.shape[0], device=a.device) noise = torch.randn_like(a) a_k = (1 - k)[:, None] * a + k[:, None] * noise v = self.velocity(z, task, a_k, k) per = (v - (a - noise)).pow(2).mean(-1) return per.mean() if reduce else per
@torch.no_grad() def sample(self, z, task, n: int = 1): if n > 1: z = z.repeat_interleave(n, 0) task = task.repeat_interleave(n, 0) a = torch.randn(z.shape[0], self.d_act, device=z.device) for s in range(self.steps): k = torch.full((z.shape[0],), 1.0 - s / self.steps, device=z.device) a = a + self.velocity(z, task, a, k) / self.steps return a
@torch.no_grad()def ema_update(target: nn.Module, online: nn.Module, m: float = 0.995): for pt, po in zip(target.parameters(), online.parameters()): pt.mul_(m).add_(po.detach(), alpha=1 - m) for bt, bo in zip(target.buffers(), online.buffers()): bt.copy_(bo)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278"""Pack the LIBERO-10 pi0.5 OGPO rollout corpus into a flat memmap cache.
Source layout (one npz per episode, 43,135 episodes over 10 task dirs): <TASK_NAME>/ep_t{T}_b{B}_i{id}_{epidx:06d}.npz z [F,4096] float16 OGPO latent (agentview | wrist) (task_index is NOT read -- see the guard in main()) proprio [F,8] float32 actions [F,7] float32 success () bool prompt () str
Cache layout (written atomically into <out>/): z.f16 memmap [N,D] latents, frame-major, episodes contiguous act.f32 memmap [N,7] executed action at that frame meta.npz ep_from/ep_to/ep_len/ep_task/ep_success/ep_src, tasks, dim
LEAKAGE NOTE recorded here because it shapes every downstream label choice:failed episodes are ALL exactly 520 frames (the timeout) while successful onesterminate early (mean ~263). Episode LENGTH therefore predicts success almostperfectly. Any label built from "frames remaining" leaks the outcome, so thereward label is defined on terminal states of successful episodes only, and theheadline diagnostic is action ranking at a FIXED state, never state ranking."""from __future__ import annotationsimport argparse, io, json, os, time, zipfilefrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathimport numpy as np
def read_header(path, assume_success=None): """(n_frames, success) without reading the arrays.
`np.load(f)["z"].shape` materialises the whole 2.3 MB latent block, which for 43k episodes is ~99 GB of pointless NFS traffic. npz is a zip of .npy members, so the shape lives in the member's own header: parse that and stop. """ with zipfile.ZipFile(path) as zf: with zf.open("z.npy") as f: ver = np.lib.format.read_magic(f) shape, _fortran, _dt = np.lib.format._read_array_header(f, ver) if assume_success is None or "success.npy" in zf.namelist(): # rollouts always carry it; REPLAYED demo caches (rerender_rollouts.py # --pool demos_replay) carry it too, and a demo whose live replay did not # end in success is inadmissible exactly like a non-reproducing rollout with zf.open("success.npy") as f: succ = bool(np.load(io.BytesIO(f.read()), allow_pickle=False)) else: succ = assume_success # legacy demo caches carry no success field return int(shape[0]), succ
def episode_files(root: Path): """-> list of (task_name, path, is_demo). Task id comes from the directory name.
Rollout dirs hold ep_*.npz and carry a `success` flag. The demo cache uses the same task name with a `_demo` suffix, holds demo_*.npz, and has no success field because every demonstration succeeds.""" out = [] for d in sorted(p for p in root.iterdir() if p.is_dir()): demo = d.name.endswith("_demo") name = d.name[:-5] if demo else d.name for f in sorted(d.glob("demo_*.npz" if demo else "ep_*.npz")): out.append((name, f, demo)) return out
def main(): ap = argparse.ArgumentParser() ap.add_argument("--src", required=True) ap.add_argument("--out", required=True) ap.add_argument("--demos", default="", help="optional demo cache root to union in") ap.add_argument("--max-eps", type=int, default=0, help="0 = all") ap.add_argument("--stride", type=int, default=1) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--workers", type=int, default=32, help="threads for the header scan (NFS latency-bound)") ap.add_argument("--header-cache", default="", help="npz to cache/reuse the (success,length) scan") ap.add_argument("--tasks-file", default="/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation/logs/09052026_lib10_tasks.txt", help="canonical LIBERO benchmark-id task order; task ids are " "assigned from THIS list, never from directory sort order " "and never from the npz `task_index` field.") ap.add_argument("--keep-all-demos", action="store_true", help="always include EVERY demo episode, then fill the rest " "with rollouts. Balanced sampling kept only 94 of 500 " "demos, which starves a BC-on-demos baseline.") ap.add_argument("--episode-list", default="", help="text file, one '<task_dir>/<file>.npz' per line: pack EXACTLY these " "rollouts in this order. Two clusters packing from the same list produce " "index-identical caches, so per-episode artefacts (subgoal labels, " "admissibility mask) transfer by index.") ap.add_argument("--encoder", default="pi05_base_pytorch", help="feature-encoder tag (basename of OGPO_PI05_BASE the latents were encoded " "with). Written to PACK.json/RENDER.json; the evaluator refuses a mismatch.") ap.add_argument("--cam-res", default="", help="render resolution the SOURCE latents were encoded from (e.g. 256). " "Written to PACK.json and RENDER.json; the evaluator refuses a cache " "whose cam_res is undeclared or differs from its own --cam-res.") ap.add_argument("--balance", action="store_true", help="equalize success/failure count within each task") args = ap.parse_args()
rng = np.random.default_rng(args.seed) src, out = Path(args.src), Path(args.out) out.mkdir(parents=True, exist_ok=True) files = episode_files(src) if args.episode_list: _want = [l.strip() for l in open(args.episode_list) if l.strip()] _by = {f"{f.parent.name}/{f.name}": (n, f, dm) for n, f, dm in files if not dm} _missing = [w for w in _want if w not in _by] if _missing: raise SystemExit(f"--episode-list: {len(_missing)} listed episodes absent under --src, e.g. {_missing[:3]}") files = [_by[w] for w in _want] + [t for t in files if t[2]] # rollouts in list order, then demos print(f"[pack] episode list: {len(_want)} rollouts pinned from {args.episode_list}", flush=True) if args.demos: files += episode_files(Path(args.demos)) print(f"[pack] found {len(files)} episodes in {len(set(t for t, *_ in files))} tasks", flush=True)
# ---- pass 1: read headers (success + length), pick the subset ---- hc = Path(args.header_cache) if args.header_cache else out / "headers.npz" if hc.exists(): c = np.load(hc, allow_pickle=True) if len(c["paths"]) == len(files) and set(map(str, c["paths"])) == {str(f[1]) for f in files}: dm_col = c["demo"] if "demo" in c.files else np.zeros(len(c["paths"]), bool) hdr = [(t, Path(p), bool(s), int(L), bool(dm)) for t, p, s, L, dm in zip(c["tasknames"], c["paths"], c["succ"], c["lens"], dm_col)] print(f"[pack] header scan reused from {hc}", flush=True) else: hc.unlink() if not hc.exists(): def rd(tf): task, f, demo = tf L, succ = read_header(f, assume_success=True if demo else None) return (task, f, succ, L, demo) t_scan = time.time() with ThreadPoolExecutor(max_workers=args.workers) as ex: hdr = list(ex.map(rd, files, chunksize=16)) print(f"[pack] header scan {len(hdr)} files in {time.time()-t_scan:.0f}s", flush=True) hc.parent.mkdir(parents=True, exist_ok=True) np.savez(hc, tasknames=np.array([h[0] for h in hdr]), paths=np.array([str(h[1]) for h in hdr]), succ=np.array([h[2] for h in hdr]), lens=np.array([h[3] for h in hdr]), demo=np.array([h[4] for h in hdr]))
# Task ids come from the canonical benchmark-id list so they agree with every # other trainer in this lane. Two things are deliberately NOT used: directory # sort order (incidental, and disagrees with benchmark id), and the npz # `task_index` field (0 in every episode of this corpus). canon = [n.strip() for n in Path(args.tasks_file).read_text().replace("\n", ",").split(",") if n.strip()] tid = {t: i for i, t in enumerate(canon)} present = sorted(set(t for t, *_ in hdr)) unknown = [t for t in present if t not in tid] if unknown: raise SystemExit(f"[pack] refusing: task dir(s) not in {args.tasks_file}: {unknown}") tasks = canon chosen = [] unbalanced = [] forced = [] if args.keep_all_demos: forced = [h for h in hdr if h[4]] hdr = [h for h in hdr if not h[4]] print(f"[pack] forcing all {len(forced)} demo episodes into the cache", flush=True) if args.max_eps and args.max_eps < len(hdr): per_task = args.max_eps // len(tasks) for t in tasks: pool = [h for h in hdr if h[0] == t] if args.balance: s = [h for h in pool if h[2]] f_ = [h for h in pool if not h[2]] k = min(per_task // 2, len(s), len(f_)) pick = ([s[i] for i in rng.choice(len(s), k, replace=False)] + [f_[i] for i in rng.choice(len(f_), k, replace=False)]) if k == 0 and pool: # A task can be entirely one-sided: STUDY_SCENE1 has 0 # successes in 2,962 rollouts, so 50/50 balancing would drop # it silently. Keep it at natural composition and record that # it could not be balanced -- a task the behaviour policy # never solves is a result, not a reason to hide the task. kk = min(per_task, len(pool)) pick = [pool[i] for i in rng.choice(len(pool), kk, replace=False)] unbalanced.append((t, len(s), len(f_))) else: k = min(per_task, len(pool)) pick = [pool[i] for i in rng.choice(len(pool), k, replace=False)] chosen += pick else: chosen = hdr chosen = forced + chosen rng.shuffle(chosen) sel_task = np.array([tid[h[0]] for h in chosen]) n_per = np.bincount(sel_task, minlength=len(tasks)) missing = [tasks[i] for i, n in enumerate(n_per) if n == 0 and any(h[0] == tasks[i] for h in hdr)] if missing: raise SystemExit(f"[pack] refusing: task(s) present in source but absent " f"from the selection: {missing}") print(f"[pack] packing {len(chosen)} episodes " f"(success {np.mean([h[2] for h in chosen]):.3f}) " f"per-task {n_per.tolist()}", flush=True) if unbalanced: print(f"[pack] NOT balanceable (kept at natural composition): " f"{[(u[0][:28], u[1], u[2]) for u in unbalanced]}", flush=True)
# ---- pass 2: sizes, allocate, fill ---- lens = np.array([1 + (h[3] - 1) // args.stride for h in chosen], dtype=np.int64) ep_demo = np.array([h[4] for h in chosen], bool) ep_to = np.cumsum(lens); ep_from = ep_to - lens N = int(ep_to[-1]) with np.load(chosen[0][1], allow_pickle=True) as n: D = int(n["z"].shape[1]); A = int(n["actions"].shape[1]) print(f"[pack] N={N} frames D={D} A={A} " f"({N*D*2/1e9:.1f} GB latents)", flush=True)
zmm = np.lib.format.open_memmap(out / "z.f16.npy", mode="w+", dtype=np.float16, shape=(N, D)) # proprio is cheap (8 floats/frame) and the lane's closed-loop policy head # consumes it alongside the latent, so pack it for interoperability even # though the occupancy critic here does not use it. pmm = np.lib.format.open_memmap(out / "proprio.f32.npy", mode="w+", dtype=np.float32, shape=(N, 8)) amm = np.lib.format.open_memmap(out / "act.f32.npy", mode="w+", dtype=np.float32, shape=(N, A)) ep_task = np.zeros(len(chosen), np.int64) ep_succ = np.zeros(len(chosen), bool) ep_src = [] for i, (task, f, succ, _L, _dm) in enumerate(chosen): with np.load(f, allow_pickle=True) as n: z = n["z"][::args.stride] a = n["actions"][::args.stride] pr = n["proprio"][::args.stride] if "proprio" in n.files else None s, e = int(ep_from[i]), int(ep_to[i]) zmm[s:e] = z[: e - s] amm[s:e] = a[: e - s] if pr is not None: pmm[s:e] = pr[: e - s] ep_task[i] = tid[task]; ep_succ[i] = succ ep_src.append(str(f)) if (i + 1) % 250 == 0: # Bound dirty-page accumulation: without periodic flushes the whole # written cache sits dirty in page cache and the box is reported as # out of memory (it killed this job and the concurrent upload once). zmm.flush(); amm.flush(); pmm.flush() print(f"[pack] {i+1}/{len(chosen)} episodes", flush=True) zmm.flush(); amm.flush(); pmm.flush()
np.savez(out / "meta.npz", ep_from=ep_from, ep_to=ep_to, ep_len=lens, ep_task=ep_task, ep_success=ep_succ, ep_demo=ep_demo, tasks=np.array(tasks), dim=D, adim=A, stride=args.stride, n_frames=N, ep_src=np.array(ep_src)) _cam = int(args.cam_res) if str(args.cam_res).isdigit() else (args.cam_res or "UNKNOWN") (out / "RENDER.json").write_text(json.dumps({ "cam_res": _cam, "encoder": args.encoder, "flip": "[::-1,::-1] to serving orientation", "resize": "-> 224 bilinear, uint8", "encoder": "08312026_1110pm_ogpo_latent_cache.py PaliGemma base||wrist", "proprio": "eef_pos(3)+axis_angle(3)+gripper(2)"}, indent=1)) (out / "PACK.json").write_text(json.dumps({ "cam_res": _cam, "encoder": args.encoder, "src": str(src), "episodes": len(chosen), "frames": N, "dim": D, "adim": A, "stride": args.stride, "success_rate": float(ep_succ.mean()), "n_demo": int(ep_demo.sum()), "tasks": tasks, "task_id_source": f"canonical benchmark order from {args.tasks_file} " f"(dir sort order and the npz task_index field are both ignored)", "episodes_per_task": n_per.tolist(), "tasks_not_balanceable": [[u[0], int(u[1]), int(u[2])] for u in unbalanced], }, indent=2)) print(f"[pack] DONE -> {out}", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""Paired comparison of two closed-loop evals.
Arms are paired by construction: the env seed depends only on (seed, tid, k), so twoarms run at the same SEED see identical initial conditions. This verifies that from therecorded init_sha256 and then runs McNemar's exact test on the discordant pairs, whichis the correct test for paired binary outcomes. The unpaired two-proportion z-test usedelsewhere is conservative here and understates real differences."""import json, sysfrom math import comb
def load(p): """Key on (task, episode index), NOT on init_sha256.
The env seed is a pure function of (seed, tid, k), so episode k is the same initial condition in every arm run at the same SEED. init_sha256 hashes raw float64 sim-state bytes and therefore differs between compute nodes for a logically identical state, which made it useless as a join key.""" r = json.load(open(p)) out, sha = {}, {} for task, eps in r["episodes_detail"].items(): for e in eps: out[(task, e["episode"])] = bool(e["success"]) sha[(task, e["episode"])] = e.get("init_sha256") return out, r["pooled_SR"], sha
def mcnemar(b, c): """two-sided exact binomial on the discordant pairs""" n = b + c if n == 0: return 1.0 k = min(b, c) tail = sum(comb(n, i) for i in range(0, k + 1)) / (2 ** n) return min(1.0, 2 * tail)
A, srA, shA = load(sys.argv[1])B, srB, shB = load(sys.argv[2])shared = set(A) & set(B)print(f" {sys.argv[1].split('/')[-1][:-5]:26s} SR {srA:.3f} n={len(A)}")print(f" {sys.argv[2].split('/')[-1][:-5]:26s} SR {srB:.3f} n={len(B)}")nsha = sum(1 for k in shared if shA.get(k) and shA[k] == shB.get(k))print(f" matched episodes: {len(shared)}/{min(len(A),len(B))}" f" ({'PAIRED' if len(shared)==min(len(A),len(B)) else 'PARTIAL'})" f" [identical init hash on {nsha}/{len(shared)}" f"{'' if nsha==len(shared) else ' — rest differ only in float bits across nodes'}]")if not shared: print(" no shared inits; arms used different seeds"); raise SystemExitb = sum(1 for k in shared if A[k] and not B[k])c = sum(1 for k in shared if B[k] and not A[k])agree = len(shared) - b - cp = mcnemar(b, c)d = srA - srBprint(f" concordant {agree} A-only {b} B-only {c}")print(f" diff {d:+.3f} McNemar exact p = {p:.4g}" f" {'SIGNIFICANT' if p < 0.05 else 'not significant'} at 0.05")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305"""PARL with the RSM occupancy value: rank proposal samples by Q, distill the argmax.
Faithful to the lane's PARL recipe (MaxSobolMark/PolicyAgnosticRL actionoptimisation): sample N action chunks from a base proposal policy, rank them byQ, keep the best, and distill those into a fresh head with the ordinary flowloss. Our Q is the RSM occupancy read-out rather than a TD value.
Why this is different from the Q-filtering already tried, and why that one washandicapped: PARL's own note is that it "only helps if the proposal policy's Nsamples are DIVERSE -- an overtrained flow collapses to the mean, so there isnothing to rank". Our behaviour clones are trained 120k steps and then thecheckpoint is selected by BEST held-out sampled reconstruction MSE, which selectsprecisely the most mean-collapsed checkpoint. Measured here as `proposal_std`,which is reported before any distillation so a collapsed proposal is visiblerather than silently wasting the run.
Selection uses depth 1 by default so the recursion never has to re-draw an actionin a latent the flow only imagined, which a raw-feature policy cannot be queriedfor."""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, make_policy, policy_nll, policy_features, \ q_recursive, sampled_action_msefrom awr import offline_score
@torch.no_grad()def proposal_diversity(pol, pfeat, d, rng, device, n_states=256, n_samp=16, temp=1.0, sde=0.0): """Mean per-dimension std across N samples at a FIXED state.
This is the quantity PARL lives or dies on. A collapsed proposal gives the ranker N copies of the same action and the argmax is then meaningless. """ b = d.sample_frames(n_states, rng, "val", device) z = pfeat(b["x"]) acts = torch.stack([pol.sample(z, b["task"], temp=temp, sde=sde) for _ in range(n_samp)]) return float(acts.std(0).mean()), float(b["a"].std())
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--critic", required=True) ap.add_argument("--proposal", required=True, help="base policy checkpoint") ap.add_argument("--out", required=True) ap.add_argument("--chunk", type=int, default=10) ap.add_argument("--proposal-sde", type=float, default=0.0, help="noise injected during integration. Unlike temp it " "follows the learned drift, so candidates stay near " "the manifold instead of being thrown off it.") ap.add_argument("--proposal-temp", type=float, default=1.0, help="scales the proposal's initial noise; >1 widens the " "candidate set the value ranks over") ap.add_argument("--n-actions", type=int, default=32, help="candidates per state (PARL repo default 32)") ap.add_argument("--select-pool", default="demos", choices=["demos", "succ", "demos_succ", "all"], help="states the distillation set is drawn from") ap.add_argument("--qf-ckpt", default="", help="rank with the SUPERVISED student Q from rsm_main.py " "instead of the counterfactual-conditioned occupancy " "read-out. The student is fit on real (s,a,s') " "transitions and is the only reader measured to rank " "actions correctly on this corpus.") ap.add_argument("--num-keep", type=int, default=4, help="keep the top-k candidates, not only the arg-max. " "Distilling a single arg-max concentrates all of the " "estimator's error into the target.") ap.add_argument("--margin-quantile", type=float, default=0.7, help="confidence GATE. Keep only states whose critic margin " "(best minus median candidate) is above this quantile; " "apply selection only where the value actually separates " "candidates, and leave the rest to the anchor. 0 = off.") ap.add_argument("--include-demos", type=int, default=1, help="anchor the distillation set on (state, LOGGED demo " "action) pairs alongside the selected ones. PA-RL's " "distil set is selected pairs PLUS demonstrations; " "without the anchor the student has nothing holding it " "on the demonstration manifold.") ap.add_argument("--distill-states", type=int, default=200000) ap.add_argument("--distill-steps", type=int, default=60000) ap.add_argument("--batch", type=int, default=1024) ap.add_argument("--lr", type=float, default=3e-4) ap.add_argument("--beta-q", type=float, default=0.90) ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--depth", type=int, default=1) ap.add_argument("--particles", type=int, default=8) ap.add_argument("--q-pessimism", type=float, default=2.0) ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"]) ap.add_argument("--feat-scale", default="center", choices=["zscore", "center"]) ap.add_argument("--policy-family", default="concat", choices=["concat", "flow", "gauss"]) ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) ap.add_argument("--reward-mode", default="dense", choices=["dense", "terminal", "subgoal", "soft"]) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--proposal-sde-anneal", type=int, default=0, help="1 = anneal --proposal-sde to zero by the last integration step") ap.add_argument("--rank", default="critic", choices=["critic", "random"], help="random = keep --num-keep random candidates (critic-free control)") ap.add_argument("--hop-policy", default="", help="latent-feature BC checkpoint for hops >= 2 (required if --depth > 1)") ap.add_argument("--crn", type=int, default=1, help="common random numbers across candidates when scoring") ap.add_argument("--save-every", type=int, default=10000, help="save policy_s<step>.pt during distillation; policy_last.pt is always saved") args = ap.parse_args()
torch.manual_seed(args.seed) dev = "cuda" if torch.cuda.is_available() else "cpu" out = Path(args.out); out.mkdir(parents=True, exist_ok=True) d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode=args.reward_mode, norm_pool=args.norm_pool) enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) args.d_z = cfg["d_z"] qstud = qenc = None if args.qf_ckpt: from model import Encoder as _Enc from rsm_main import QStudent _ck = torch.load(args.qf_ckpt, map_location=dev, weights_only=False) _c = _ck["config"] qenc = _Enc(d.feat_dim, _c["d_z"], _c["enc_width"]).to(dev) qenc.load_state_dict(_ck["enc"]); qenc.eval() qstud = QStudent(_c["d_z"], _ck["d_act"], d.n_task).to(dev) qstud.load_state_dict(_ck["qf"]); qstud.eval() print(f"[parl] ranking with the SUPERVISED student Q " f"(arrival AUC {_ck.get('arrival_auc', float('nan')):.4f})", flush=True) pfeat, d_pol = policy_features(args, enc, d, cfg, dev) hop = None if args.depth > 1: if not args.hop_policy: raise SystemExit("--depth > 1 needs --hop-policy") _hk = torch.load(args.hop_policy, map_location=dev, weights_only=False) class _HA: pass _ha = _HA(); [setattr(_ha, k, v) for k, v in _hk["config"].items()] hop = make_policy(_ha, d, dev, d_z=cfg["d_z"]); hop.load_state_dict(_hk["pol"]); hop.eval() print(f"[parl] hop policy loaded for depth {args.depth}", flush=True)
pk = torch.load(args.proposal, map_location=dev, weights_only=False) # the distilled head inherits the proposal's architecture (width/depth) args.pol_width = int(pk["config"].get("pol_width", 1024) or 1024) args.pol_depth = int(pk["config"].get("pol_depth", 4) or 4) base = make_policy(args, d, dev, d_z=d_pol) base.load_state_dict(pk["pol"]); base.eval()
rng = np.random.default_rng(args.seed + 31) std_a, std_data = proposal_diversity(base, pfeat, d, rng, dev, temp=args.proposal_temp, sde=args.proposal_sde) print(f"[parl] proposal action std {std_a:.5f} vs data action std {std_data:.5f} " f"(ratio {std_a / max(std_data, 1e-9):.3f})", flush=True) if std_a < 0.02 * std_data: print("[parl] WARNING: the proposal has collapsed to the mean; ranking " "N copies of one action cannot improve anything", flush=True)
ok = {"demos": d.ep_demo, "succ": d.ep_success, "demos_succ": d.ep_demo | d.ep_success, "all": np.ones(d.n_ep, bool)}[args.select_pool] pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64)
# ---- build the distillation set: argmax_a Q(z, a) over N proposal draws ---- xs, acts, tasks, margins = [], [], [], [] got, bs = 0, 256 sel = np.random.default_rng(args.seed + 41) t_report = 0 while got < args.distill_states: w = d.ep_len[pool].astype(np.float64); w /= w.sum() e = sel.choice(pool, size=bs, p=w) t = d.ep_from[e] + (sel.random(bs) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) x = torch.from_numpy(d._feat(t)).to(dev) tk = torch.from_numpy(d.ep_task[e]).long().to(dev) with torch.no_grad(): zc = enc(x) # critic latent for scoring zp = pfeat(x) # policy features for proposing cand = torch.stack([base.sample(zp, tk, temp=args.proposal_temp, sde=args.proposal_sde, sde_anneal=bool(args.proposal_sde_anneal)) for _ in range(args.n_actions)]) N, B, A = cand.shape qs = [] zq = qenc(x) if qstud is not None else None _seed_i = int(args.seed * 1000003 + got) for i in range(N): if args.crn: torch.manual_seed(_seed_i) # same MC noise for every candidate of this batch if qstud is not None: q = qstud(zq, cand[i], tk) else: q, _ = q_recursive(zc, cand[i], tk, rew=rew, flow=flow, rms=rms, pol=hop, wend=None, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=False, pessimism=args.q_pessimism) qs.append(q) Q = torch.stack(qs) # [N, B] k = max(1, min(args.num_keep, Q.shape[0])) if args.rank == "random": topk = torch.stack([torch.randperm(N, device=dev)[:k] for _ in range(B)], 1) # [k, B] else: topk = Q.topk(k, dim=0).indices # [k, B] # margin: how far the best candidate stands above the typical one. # Small margin means the value does not separate the candidates here. margin = Q.max(0).values - Q.median(0).values # [B] ar = torch.arange(B, device=dev) for j in range(k): xs.append(x.cpu()); acts.append(cand[topk[j], ar].cpu()) tasks.append(tk.cpu()); margins.append(margin.cpu()) got += bs if got - t_report >= 25600: t_report = got print(f"[parl] selected {got}/{args.distill_states}", flush=True) X = torch.cat(xs); A_ = torch.cat(acts); T = torch.cat(tasks) Mg = torch.cat(margins) if args.margin_quantile > 0: thr = torch.quantile(Mg, args.margin_quantile) keep = Mg >= thr print(f"[parl] margin gate q={args.margin_quantile} thr={float(thr):.4f} " f"keeps {int(keep.sum())}/{len(keep)}", flush=True) X, A_, T = X[keep], A_[keep], T[keep] n_sel = len(X) if args.include_demos: # the anchor: raw (state, LOGGED action) pairs from demonstrations dm = np.array([e for e in d.train_eps if d.ep_demo[e]], dtype=np.int64) ax, aa, at = [], [], [] need, dr = max(n_sel, 1), np.random.default_rng(args.seed + 51) while sum(len(t) for t in ax) < need: w = d.ep_len[dm].astype(np.float64); w /= w.sum() e = dr.choice(dm, size=1024, p=w) t = d.ep_from[e] + (dr.random(1024) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) ax.append(torch.from_numpy(d._feat(t))) aa.append(torch.from_numpy(d._chunk_at(t, e))) at.append(torch.from_numpy(d.ep_task[e]).long()) X = torch.cat([X] + ax); A_ = torch.cat([A_] + aa); T = torch.cat([T] + at) print(f"[parl] demo anchor: {len(X) - n_sel} demo pairs + {n_sel} selected " f"= {len(X)} ({100.0 * (len(X) - n_sel) / len(X):.1f}% demo share)", flush=True) print(f"[parl] distillation set {tuple(X.shape)} from {args.select_pool}", flush=True)
# ---- distill a FRESH head onto the selected actions ---- new = make_policy(args, d, dev, d_z=d_pol) opt = torch.optim.Adam(new.parameters(), lr=args.lr) ev = np.random.default_rng(args.seed + 77) best_mse, best_sd, best_step = float("inf"), None, 0 for step in range(1, args.distill_steps + 1): idx = torch.randint(0, len(X), (args.batch,)) xb = X[idx].to(dev); ab = A_[idx].to(dev); tb = T[idx].to(dev) loss = policy_nll(new, pfeat(xb), tb, ab) opt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_(new.parameters(), 1.0); opt.step() if step % max(1, args.distill_steps // 20) == 0 or step == args.distill_steps: new.eval() m = sampled_action_mse(new, d, pfeat, ev, dev, ok) new.train() tag = "" if m == m and m < best_mse: best_mse, best_step = m, step best_sd = {k: v.detach().clone() for k, v in new.state_dict().items()} tag = " <- best" print(f"[parl] distill {step} loss={float(loss):.4f} " f"sampled_mse_vs_LOGGED={m:.5f}{tag}", flush=True) if args.save_every and step % args.save_every == 0: torch.save({"pol": new.state_dict(), "round": 1, "step": step, "config": vars(args), "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")}, out / f"policy_s{step}.pt") # The LAST distilled head is the deployable one: the logged-action MSE proxy selects # AGAINST the Q-preferred actions PARL is supposed to move toward (and picked a # checkpoint 0.10 SR below the last one for plain BC). policy_r1.pt keeps the # proxy-best for comparison; select between them on validation inits. torch.save({"pol": new.state_dict(), "round": 1, "step": args.distill_steps, "config": vars(args), "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch"), "note": "LAST distilled checkpoint"}, out / "policy_last.pt") if best_sd is not None: new.load_state_dict(best_sd) new.eval()
torch.save({"pol": new.state_dict(), "round": 1, "config": vars(args), "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")}, out / "policy_r1.pt") sc = offline_score(d, enc, new, np.random.default_rng(args.seed + 23), dev, pfeat=pfeat) sc["proposal_action_std"] = std_a sc["data_action_std"] = std_data # NOTE: sampled_mse against the LOGGED action is not the objective here -- a # working PARL run should move AWAY from the logged action toward the # Q-preferred one, so a higher value is expected and is not a failure. (out / "parl.json").write_text(json.dumps( {"config": vars(args), "score": sc, "best_distill_step": best_step}, indent=2)) print(f"[parl] {sc}", flush=True) print("[parl] DONE", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425"""Pool paired McNemar counts across seeds. Each seed is an independent draw of500 initial conditions on protocol B, so discordant pairs add."""import json, sysfrom math import comb, sqrt, erfcdef counts(pa, pb): def load(p): r=json.load(open(p)); o={} for t,eps in r["episodes_detail"].items(): for e in eps: o[(t,e["episode"])]=bool(e["success"]) return o, r["pooled_SR"] A,sa=load(pa); B,sb=load(pb); sh=set(A)&set(B) return (sum(1 for k in sh if A[k] and not B[k]), sum(1 for k in sh if B[k] and not A[k]), len(sh), sa, sb)B=C=N=0; srs=[]for i in range(1,len(sys.argv),2): b,c,n,sa,sb = counts(sys.argv[i], sys.argv[i+1]) B+=b; C+=c; N+=n; srs.append((sa,sb)) print(f" seed pair {i//2}: SR {sa:.3f} vs {sb:.3f} b={b} c={c} diff {sa-sb:+.3f}")z=(B-C)/sqrt(B+C) if B+C else 0.0p=erfc(abs(z)/sqrt(2))msr=sum(a for a,_ in srs)/len(srs); mbs=sum(b for _,b in srs)/len(srs)print(f"\n POOLED over {len(srs)} seeds, {N} paired episodes")print(f" mean SR {msr:.3f} vs {mbs:.3f} diff {msr-mbs:+.3f}")print(f" discordant b={B} c={C} z={z:.2f} p={p:.4f} " f"{'SIGNIFICANT' if p<0.05 else 'NOT significant'} at 0.05")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Which negative does the action-contrast term actually need?
Two candidate negatives for the flow-matching error at a state z: (A) shuffle the ACTION only (s, a_rand, s') <- what we implement (B) shuffle the action AND the target (s, a_rand, s'_rand)
(B) is the intuitive reading, but it confounds two effects. Its error is largepartly because the conditioning action is wrong and partly because the TARGET isan unrelated future. A successor that ignores the action entirely still scoreswell on (B), because predicting the true future from z is easy and predicting anunrelated one is hard -- which is exactly the failure the term exists to prevent.
This measures the decomposition on a trained critic: e_pos true action, true target e_act shuffled action, TRUE target -> isolates the action e_both shuffled action, shuffled target -> action + target confounded e_tgt TRUE action, shuffled target -> isolates the targetIf (e_both - e_pos) is dominated by (e_tgt - e_pos), then (B) is mostly atarget-mismatch test and says little about action sensitivity."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparseimport numpy as npimport torch
from data import LiberoRSMDatafrom is_ope import load_critic
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--critic", required=True) ap.add_argument("--chunk", type=int, default=10) ap.add_argument("--beta", type=float, default=0.90) ap.add_argument("--batch", type=int, default=4096) ap.add_argument("--reps", type=int, default=8) ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--seed", type=int, default=0) args = ap.parse_args() torch.manual_seed(args.seed) dev = "cuda" d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode="dense", norm_pool=args.norm_pool) enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) rng = np.random.default_rng(args.seed + 13) acc = {k: 0.0 for k in ("pos", "act", "both", "tgt")} with torch.no_grad(): for _ in range(args.reps): b = d.sample(args.batch, rng, args.beta, args.beta, "val", dev) z = enc(b["x_now"]); zf = enc(b["x_fut"]) y = (zf - z) / rms # true normalised residual k = torch.rand(args.batch, device=dev) noise = torch.randn_like(y) x_k = (1 - k)[:, None] * y + k[:, None] * noise u = y - noise p = torch.randperm(args.batch, device=dev) a_t, a_r = b["a_now"], b["a_now"][p] # shuffled TARGET: rebuild the path from the permuted residual y_r = y[p]; n_r = noise[p] x_k_r = (1 - k)[:, None] * y_r + k[:, None] * n_r u_r = y_r - n_r
def err(a, xk, tgt): return (flow(z, a, b["task"], b["beta"], xk, k) - tgt).pow(2).mean(-1).mean() acc["pos"] += float(err(a_t, x_k, u)) acc["act"] += float(err(a_r, x_k, u)) # action only acc["both"] += float(err(a_r, x_k_r, u_r)) # action + target acc["tgt"] += float(err(a_t, x_k_r, u_r)) # target only for kk in acc: acc[kk] /= args.reps print(f"\n{'negative':<34s} {'flow-matching error':>20s} {'gap vs true':>13s}") print(f"{'(true action, true target)':<34s} {acc['pos']:20.5f} {0.0:13.5f}") print(f"{'A: shuffled ACTION, true target':<34s} {acc['act']:20.5f} " f"{acc['act'] - acc['pos']:+13.5f}") print(f"{' true action, shuffled target':<34s} {acc['tgt']:20.5f} " f"{acc['tgt'] - acc['pos']:+13.5f}") print(f"{'B: shuffled action AND target':<34s} {acc['both']:20.5f} " f"{acc['both'] - acc['pos']:+13.5f}") ga, gb = acc["act"] - acc["pos"], acc["both"] - acc["pos"] gt = acc["tgt"] - acc["pos"] print(f"\naction-only gap as a share of the both-shuffled gap: " f"{100.0 * ga / gb:.1f}%" if gb else "") print(f"target-only gap as a share of the both-shuffled gap: " f"{100.0 * gt / gb:.1f}%" if gb else "")
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""Does the ACTION carry outcome information beyond the state, in this corpus?
Everything in this lane hinges on it. The RSM Q takes its action dependence fromthe occupancy model extrapolating to actions never observed at that state, whichis unsupervised in the action direction, and was measured to have arbitrary sign.A directly supervised head has that dependence SUPERVISED by real outcomes.
Two heads, same latent, same data, same budget, held-out AUC against episodesuccess: V(z) state only Q(z, a) state and the logged action chunkIf Q does not beat V, the action carries nothing beyond the state at thisgranularity and NO critic of any kind can rank actions here -- the ceiling is thedata, not the model. If Q does beat V, the action signal exists and the defect isthe occupancy model's extrapolation, which is fixable.
Reported on rollouts (which contain failures); demonstrations alone are almostall successes and cannot answer the question."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparseimport numpy as npimport torchimport torch.nn.functional as F
from data import LiberoRSMDatafrom is_ope import load_criticfrom model import mlpfrom train_rsm import auc
def train_head(d, enc, dev, use_action, steps, batch, lr, seed, tag): torch.manual_seed(seed) d_act = d.chunk * d.adim din = 264 + (d_act if use_action else 0) net = mlp([din, 1024, 1024, 1], norm=True).to(dev) emb = torch.nn.Embedding(d.n_task, 0).to(dev) # task enters via the latent opt = torch.optim.Adam(net.parameters(), lr=lr) rng = np.random.default_rng(seed + 3) for step in range(1, steps + 1): b = d.sample_frames(batch, rng, "train", dev) with torch.no_grad(): z = enc(b["x"]) x = torch.cat([z, b["a"]], -1) if use_action else z loss = F.binary_cross_entropy_with_logits(net(x).squeeze(-1), b["succ"]) opt.zero_grad(); loss.backward(); opt.step() if step % max(1, steps // 5) == 0: print(f" [{tag}] {step} bce={float(loss):.4f}", flush=True) # held-out AUC against EPISODE success net.eval() ev = np.random.default_rng(seed + 77) P, Y = [], [] with torch.no_grad(): for _ in range(8): b = d.sample_frames(2048, ev, "val", dev) z = enc(b["x"]) x = torch.cat([z, b["a"]], -1) if use_action else z P.append(torch.sigmoid(net(x).squeeze(-1)).cpu().numpy()) Y.append(b["succ"].cpu().numpy()) return float(auc(np.concatenate(P), np.concatenate(Y)))
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--critic", required=True) ap.add_argument("--chunk", type=int, default=10) ap.add_argument("--steps", type=int, default=20000) ap.add_argument("--batch", type=int, default=1024) ap.add_argument("--lr", type=float, default=3e-4) ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--seed", type=int, default=0) args = ap.parse_args() dev = "cuda" d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode="dense", norm_pool=args.norm_pool) enc, _r, _f, _rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) print(f"[probe] corpus success rate {float(d.ep_success.mean()):.3f}", flush=True) a_v = train_head(d, enc, dev, False, args.steps, args.batch, args.lr, args.seed, "V(z)") a_q = train_head(d, enc, dev, True, args.steps, args.batch, args.lr, args.seed, "Q(z,a)") print(f"\nheld-out AUC vs episode success") print(f" V(z) state only {a_v:.4f}") print(f" Q(z,a) state and action {a_q:.4f}") print(f" delta {a_q - a_v:+.4f}") print("\ndelta ~ 0 means the action adds nothing beyond the state at this " "granularity, and no critic can rank actions on this corpus.", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""Is Q blind to the action, or is its ESTIMATOR too noisy to see the action?
q_recursive draws fresh flow noise on every call, so comparing Q(a1) with Q(a2)compares two noisy Monte-Carlo estimates. If the per-call noise is larger than theeffect an action has, the comparison is pure coin-flip -- which is exactly whatprobe_perturb saw (expert wins 0.483-0.508, mean Q moving 1% when the action isdestroyed). That is equally consistent with "Q ignores the action" and with "theestimator cannot resolve the action".
This separates them: repeat noise |Q(a) - Q'(a)| same action, INDEPENDENT noise paired effect |Q(a) - Q(a+e)| different action, COMMON noise (CRN)If the paired effect is comparable to or larger than the repeat noise, the signalis there and was being drowned; common random numbers recover it. If the pairedeffect is ~0 under CRN, the model genuinely ignores the action."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparseimport numpy as npimport torch
from data import LiberoRSMDatafrom is_ope import load_criticfrom train_rsm import sample_future
def q_fixed_noise(enc_z, a, tk, *, rew, flow, rms, beta, gamma, n_particles, flow_steps, noise): """Q with the flow's initial noise SUPPLIED, so candidates share it.""" B, D = enc_z.shape z = enc_z.repeat_interleave(n_particles, 0) aa = a.repeat_interleave(n_particles, 0) t = tk.repeat_interleave(n_particles, 0) bq = torch.full((z.shape[0],), beta, device=z.device) x = noise.clone() for s in range(flow_steps): k = torch.full((z.shape[0],), 1.0 - s / flow_steps, device=z.device) x = x + flow(z, aa, t, bq, x, k) / flow_steps z_end = z + x * rms r = torch.sigmoid(rew(z_end, t)).view(B, n_particles) return r.mean(1) / (1 - gamma)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--critic", required=True) ap.add_argument("--chunk", type=int, default=10) ap.add_argument("--beta-q", type=float, default=0.90) ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--particles", type=int, default=16) ap.add_argument("--flow-steps", type=int, default=8) ap.add_argument("--n", type=int, default=1024) ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--seed", type=int, default=0) args = ap.parse_args()
torch.manual_seed(args.seed) dev = "cuda" d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode="dense", norm_pool=args.norm_pool) enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) pool = np.array([e for e in d.val_eps if d.ep_demo[e]], dtype=np.int64) if not len(pool): pool = np.array([e for e in d.train_eps if d.ep_demo[e]], dtype=np.int64) rng = np.random.default_rng(args.seed + 9) w = d.ep_len[pool].astype(np.float64); w /= w.sum() e = rng.choice(pool, size=args.n, p=w) t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) x = torch.from_numpy(d._feat(t)).to(dev) a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) tk = torch.from_numpy(d.ep_task[e]).long().to(dev)
with torch.no_grad(): z = enc(x) D = z.shape[1] kw = dict(rew=rew, flow=flow, rms=rms, beta=args.beta_q, gamma=args.gamma, n_particles=args.particles, flow_steps=args.flow_steps) n1 = torch.randn(args.n * args.particles, D, device=dev) n2 = torch.randn(args.n * args.particles, D, device=dev) q_a = q_fixed_noise(z, a0, tk, noise=n1, **kw) q_b = q_fixed_noise(z, a0, tk, noise=n2, **kw) repeat = (q_a - q_b).abs().mean() print(f"repeat noise, same action different noise : {float(repeat):.5f}") print(f"{'noise':>7s} {'|dQ| CRN':>10s} {'expert wins CRN':>16s} " f"{'|dQ|/repeat':>12s}") for sig in (0.1, 0.2, 0.4, 0.8): q_p = q_fixed_noise(z, a0 + sig * torch.randn_like(a0), tk, noise=n1, **kw) # COMMON noise dq = (q_a - q_p) win = float((dq > 0).float().mean()) print(f"{sig:7.2f} {float(dq.abs().mean()):10.5f} {win:16.3f} " f"{float(dq.abs().mean() / repeat.clamp_min(1e-9)):12.2f}", flush=True) print("\nexpert wins CRN > 0.5 means the model DOES prefer the expert action " "once the shared noise is removed.", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Characterise the two initial-condition distributions the evaluator can use.
Protocol A replays LIBERO's 50 stored init states; protocol B lets the task's BDDLplacement region resample. Both are full sim-state vectors, so they are directlycomparable. Reports, per task, how much each distribution actually spreads andwhether A's 50 states are a subset of B's support."""import os, sys, numpy as npsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from libero.libero import benchmark, get_libero_pathfrom libero.libero.envs import OffScreenRenderEnvfrom pathlib import Path
bench = benchmark.get_benchmark_dict()["libero_10"]()rows = []for tid in range(10): task = bench.get_task(tid) env = OffScreenRenderEnv( bddl_file_name=str(Path(get_libero_path("bddl_files")) / task.problem_folder / task.bddl_file), camera_heights=128, camera_widths=128) inits = np.asarray(bench.get_task_init_states(tid)) # protocol A fresh = [] for k in range(50): # protocol B, eval seeds env.seed(0 * 100003 + tid * 1009 + k) env.reset() fresh.append(np.asarray(env.env.sim.get_state().flatten())) fresh = np.stack(fresh) n = min(inits.shape[1], fresh.shape[1]) A, B = inits[:, :n], fresh[:, :n] # dims that actually vary in either protocol = the randomised object DoF var = (A.std(0) > 1e-6) | (B.std(0) > 1e-6) sa, sb = A[:, var].std(0), B[:, var].std(0) # is every stock state inside the fresh support? lo, hi = B[:, var].min(0), B[:, var].max(0) inside = ((A[:, var] >= lo - 1e-6) & (A[:, var] <= hi + 1e-6)).all(1).mean() rows.append((tid, task.name[:34], int(var.sum()), sa.mean(), sb.mean(), inside)) print(f"t{tid} {task.name[:34]:34s} varying_dof={int(var.sum()):3d} " f"std_stock={sa.mean():.4f} std_fresh={sb.mean():.4f} " f"stock_inside_fresh_support={inside:.2f}", flush=True) env.close()print()print(f"MEAN std_stock={np.mean([r[3] for r in rows]):.4f} " f"std_fresh={np.mean([r[4] for r in rows]):.4f} " f"ratio={np.mean([r[4] for r in rows])/max(np.mean([r[3] for r in rows]),1e-9):.2f}x " f"stock_inside={np.mean([r[5] for r in rows]):.2f}")123456789101112131415161718192021222324252627282930313233343536373839"""Exactly what each protocol randomises: per-DoF comparison + the sampler ranges."""import os, sys, numpy as npsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from libero.libero import benchmark, get_libero_pathfrom libero.libero.envs import OffScreenRenderEnvfrom pathlib import Path
bench = benchmark.get_benchmark_dict()["libero_10"]()for tid in [0, 3]: task = bench.get_task(tid) env = OffScreenRenderEnv( bddl_file_name=str(Path(get_libero_path("bddl_files")) / task.problem_folder / task.bddl_file), camera_heights=128, camera_widths=128) print(f"\n===== t{tid} {task.name} =====") pi = env.env.placement_initializer for smp in getattr(pi, "samplers", {}).values() if hasattr(pi, "samplers") else []: xr = getattr(smp, "x_range", None); yr = getattr(smp, "y_range", None) rot = getattr(smp, "rotation", None) if xr is None: continue xs = float(np.ptp(np.asarray(xr))); ys = float(np.ptp(np.asarray(yr))) print(f" sampler {smp.name[:38]:38s} x-span {xs*100:6.2f} cm y-span {ys*100:6.2f} cm rot {rot}") inits = np.asarray(bench.get_task_init_states(tid)) fresh = [] for k in range(50): env.seed(tid*1009 + k); env.reset() fresh.append(np.asarray(env.env.sim.get_state().flatten())) fresh = np.stack(fresh) n = min(inits.shape[1], fresh.shape[1]); A, B = inits[:, :n], fresh[:, :n] va, vb = A.std(0) > 1e-6, B.std(0) > 1e-6 both, only_a, only_b = va & vb, va & ~vb, vb & ~va print(f" DoF varying in BOTH: {both.sum():3d} stdA {A[:,both].std(0).mean():.4f} " f"stdB {B[:,both].std(0).mean():.4f}") print(f" DoF varying in STOCK ONLY (A randomises, B holds fixed): {only_a.sum():3d}" f" stdA {A[:,only_a].std(0).mean() if only_a.any() else 0:.4f}") print(f" DoF varying in FRESH ONLY: {only_b.sum():3d}") nq = env.env.sim.model.nq print(f" (nq={nq}; robot joints are the first ~7-9 dims, objects are free joints after)") env.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Does Q prefer the EXPERT action over noisy perturbations of it?
This is the question PARL actually asks, and it has unambiguous ground truth: ona demonstration frame the logged chunk IS the good action, and adding noise canonly make it worse. The earlier action-gap probe compared the logged actionagainst a DIFFERENT episode's action, which is dominated by on-support versusoff-support and says little about ranking candidates near the mode.
Reports, per noise scale: the fraction of states where Q ranks the expert actionabove the perturbed one, and mean Q as a function of noise. If mean Q RISES withnoise the critic is inverted, and the fix is a sign, not more training."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparseimport numpy as npimport torch
from data import LiberoRSMDatafrom is_ope import load_critic, q_recursive
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--critic", required=True) ap.add_argument("--chunk", type=int, default=10) ap.add_argument("--beta-q", type=float, default=0.90) ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--depth", type=int, default=1) ap.add_argument("--particles", type=int, default=16) ap.add_argument("--n", type=int, default=1024) ap.add_argument("--pool", default="demos", choices=["demos", "succ", "all"]) ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) ap.add_argument("--pessimism", type=float, default=0.0) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--seed", type=int, default=0) args = ap.parse_args()
torch.manual_seed(args.seed) dev = "cuda" d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode="dense", norm_pool=args.norm_pool) enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) ok = {"demos": d.ep_demo, "succ": d.ep_success, "all": np.ones(d.n_ep, bool)}[args.pool] pool = np.array([e for e in d.val_eps if ok[e]], dtype=np.int64) if not len(pool): pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) rng = np.random.default_rng(args.seed + 9) w = d.ep_len[pool].astype(np.float64); w /= w.sum() e = rng.choice(pool, size=args.n, p=w) t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) x = torch.from_numpy(d._feat(t)).to(dev) a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) tk = torch.from_numpy(d.ep_task[e]).long().to(dev)
def Q(a): q, _ = q_recursive(enc(x), a, tk, rew=rew, flow=flow, rms=rms, pol=None, wend=None, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=False, pessimism=args.pessimism) return q
with torch.no_grad(): q0 = Q(a0) print(f"expert action: mean Q {float(q0.mean()):+.5f}", flush=True) print(f"{'noise':>7s} {'mean Q':>10s} {'expert wins':>12s}") for sig in (0.05, 0.1, 0.2, 0.4, 0.8): qn = Q(a0 + sig * torch.randn_like(a0)) win = float((q0 > qn).float().mean()) print(f"{sig:7.2f} {float(qn.mean()):+10.5f} {win:12.3f}", flush=True) print("\nexpert wins > 0.5 = the critic prefers the expert action.", flush=True) print("mean Q RISING with noise = the critic is inverted.", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Does a disagreement penalty fix the critic's inverted action ranking?
Measures the held-out action win rate -- how often Q ranks the action actuallytaken above a different action taken in the SAME task -- as a function of thepessimism coefficient. Within-task negatives on purpose: cross-task negativesmeasure support violation, not preference."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparseimport numpy as npimport torch
from data import LiberoRSMDatafrom is_ope import load_critic, q_recursive, train_bc, policy_features
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--critic", required=True) ap.add_argument("--chunk", type=int, default=10) ap.add_argument("--beta-q", type=float, default=0.90) ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--depth", type=int, default=3) ap.add_argument("--particles", type=int, default=16) ap.add_argument("--n", type=int, default=1024) ap.add_argument("--batch", type=int, default=256) ap.add_argument("--bc-steps", type=int, default=4000) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--policy-family", default="concat") args = ap.parse_args() torch.manual_seed(args.seed) dev = "cuda" d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode="dense") enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) args.d_z = cfg["d_z"] # continuation policy in the critic's latent space, as the recursion needs cont = train_bc(d, enc, args, dev, only_success=True, steps=args.bc_steps)
rng = np.random.default_rng(args.seed + 5) b = d.sample_frames(args.n, rng, "val", dev) # within-task negative: another frame's action chunk from the SAME task task = b["task"].cpu().numpy() perm = np.arange(len(task)) for t in np.unique(task): idx = np.where(task == t)[0] perm[idx] = rng.permutation(idx) a_neg = b["a"][torch.from_numpy(perm).to(dev)]
with torch.no_grad(): z = enc(b["x"]) print(f"{'pessimism':>10s} {'win rate':>9s} {'gap':>10s}") for pe in (0.0, 0.5, 1.0, 2.0, 4.0): qp, _ = q_recursive(z, b["a"], b["task"], rew=rew, flow=flow, rms=rms, pol=cont, wend=None, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=False, pessimism=pe) qn, _ = q_recursive(z, a_neg, b["task"], rew=rew, flow=flow, rms=rms, pol=cont, wend=None, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=False, pessimism=pe) win = float((qp > qn).float().mean()) print(f"{pe:10.1f} {win:9.3f} {float((qp - qn).mean()):+10.5f}", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""Does main's SUPERVISED student Q rank actions where our counterfactual Q cannot?
Same test as probe_perturb/probe_crn, applied to qf(z,a) from rsm_main.py. qf isfit by regression onto r + gamma(1-done)V(s') using the REAL logged s', so itsaction dependence is supervised rather than extrapolated. It is alsodeterministic, so there is no sampling noise to cancel -- the comparison is exact.
expert wins > 0.5 means it prefers the expert chunk over a perturbation of it."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparseimport numpy as npimport torch
from data import LiberoRSMDatafrom model import Encoderfrom rsm_main import QStudent
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--ckpt", required=True) ap.add_argument("--n", type=int, default=2048) ap.add_argument("--pool", default="demos", choices=["demos", "succ", "all"]) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--seed", type=int, default=0) args = ap.parse_args() dev = "cuda" ck = torch.load(args.ckpt, map_location=dev, weights_only=False) c = ck["config"] d = LiberoRSMData(args.cache, chunk=c["chunk"], k_success=c["k_success"], seed=args.seed, in_ram=bool(args.in_ram), reward_mode="terminal", norm_pool=c["norm_pool"]) enc = Encoder(d.feat_dim, c["d_z"], c["enc_width"]).to(dev) enc.load_state_dict(ck["enc"]); enc.eval() qf = QStudent(c["d_z"], ck["d_act"], d.n_task).to(dev) qf.load_state_dict(ck["qf"]); qf.eval()
ok = {"demos": d.ep_demo, "succ": d.ep_success, "all": np.ones(d.n_ep, bool)}[args.pool] pool = np.array([e for e in d.val_eps if ok[e]], dtype=np.int64) if not len(pool): pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) rng = np.random.default_rng(args.seed + 9) w = d.ep_len[pool].astype(np.float64); w /= w.sum() e = rng.choice(pool, size=args.n, p=w) t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) x = torch.from_numpy(d._feat(t)).to(dev) a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) tk = torch.from_numpy(d.ep_task[e]).long().to(dev)
with torch.no_grad(): z = enc(x) q0 = qf(z, a0, tk) print(f"expert chunk: mean Q {float(q0.mean()):+.4f} sd {float(q0.std()):.4f}") print(f"{'noise':>7s} {'mean Q':>10s} {'expert wins':>12s} {'mean dQ':>10s}") for sig in (0.05, 0.1, 0.2, 0.4, 0.8): qn = qf(z, a0 + sig * torch.randn_like(a0), tk) print(f"{sig:7.2f} {float(qn.mean()):+10.4f} " f"{float((q0 > qn).float().mean()):12.3f} " f"{float((q0 - qn).mean()):+10.4f}", flush=True) # in-support control: a real chunk from a DIFFERENT frame of the same task tt = tk.cpu().numpy(); perm = np.arange(len(tt)) for task in np.unique(tt): idx = np.where(tt == task)[0] perm[idx] = rng.permutation(idx) qo = qf(z, a0[torch.from_numpy(perm).to(dev)], tk) print(f"\nwithin-task other real chunk: expert wins " f"{float((q0 > qo).float().mean()):.3f}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""Does the critic prefer one PROPOSER's action style regardless of state?
At held-out frames, grouped by where they come from (demo episodes, successfulrollouts, failed rollouts), draw N chunks from the BC-demos policy and N from theBC-successes policy and score every chunk with the same recursive Q the closed-loopmixed arms use. Reports, per frame source: mean Q by proposer, how often thearg-max over the 2N pool lands on a successes chunk, and the Q of the logged action.
A critic that evaluates ACTIONS should prefer neither proposer on the demo frames(where the demos policy is at home) in particular. A critic that identifies thePOLICY from the action style prefers the successes proposer everywhere, because thedemos are <1% of the frames it was fit on.
usage: proposer_bias_diag.py --cache ... --critic ... --hop-policy ... --pol1 <BCdemo> --pol2 <BCsucc> [--n 8 --frames 512 --beta 0.95 --depth 3 --particles 16]"""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, jsonimport numpy as npimport torchfrom data import LiberoRSMDatafrom is_ope import load_critic, make_policy, policy_features, q_recursive
def load_pol(path, d, dev, d_pol): pk = torch.load(path, map_location=dev, weights_only=False) class _A: pass a = _A(); [setattr(a, k, v) for k, v in pk["config"].items()] a.pol_width = int(pk["config"].get("pol_width", 1024) or 1024) a.pol_depth = int(pk["config"].get("pol_depth", 4) or 4) pol = make_policy(a, d, dev, d_z=d_pol); pol.load_state_dict(pk["pol"]); pol.eval() return pol
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) ap.add_argument("--hop-policy", default=""); ap.add_argument("--pol1", required=True) ap.add_argument("--pol2", required=True); ap.add_argument("--out", required=True) ap.add_argument("--n", type=int, default=8); ap.add_argument("--frames", type=int, default=512) ap.add_argument("--beta", type=float, default=0.95); ap.add_argument("--gamma", type=float, default=0.98) ap.add_argument("--depth", type=int, default=3); ap.add_argument("--particles", type=int, default=16) ap.add_argument("--norm-pool", default="all"); ap.add_argument("--reward-mode", default="dense") ap.add_argument("--seed", type=int, default=0) args = ap.parse_args() torch.manual_seed(args.seed) dev = "cuda" d = LiberoRSMData(args.cache, chunk=10, seed=0, in_ram=False, reward_mode=args.reward_mode, norm_pool=args.norm_pool) enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) enc.eval() class _P: pass _p = _P(); _p.policy_features = "raw" pfeat, d_pol = policy_features(_p, enc, d, cfg, dev) hop = None if args.hop_policy: hop = load_pol(args.hop_policy, d, dev, cfg["d_z"]) pol1 = load_pol(args.pol1, d, dev, d_pol); pol2 = load_pol(args.pol2, d, dev, d_pol) rng = np.random.default_rng(args.seed) val = d.val_eps groups = {"demo": val[d.ep_demo[val]], "roll_succ": val[d.ep_success[val] & ~d.ep_demo[val]], "roll_fail": val[~d.ep_success[val] & ~d.ep_demo[val]]} res = {} for g, eps in groups.items(): if len(eps) == 0: continue e = rng.choice(eps, size=args.frames, replace=True) t = d.ep_from[e] + (rng.random(args.frames) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64) x = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev) a_log = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(args.frames, -1) with torch.no_grad(): zc = enc(x); zp = pfeat(x) c1 = torch.stack([pol1.sample(zp, tk) for _ in range(args.n)]) c2 = torch.stack([pol2.sample(zp, tk) for _ in range(args.n)]) cand = torch.cat([c1, c2, a_log[None]], 0) # [2N+1, B, A] qs = [] for i in range(cand.shape[0]): torch.manual_seed(args.seed * 7919 + 1) # CRN across candidates q, _ = q_recursive(zc, cand[i], tk, rew=rew, flow=flow, rms=rms, pol=hop, wend=None, beta=args.beta, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=False, pessimism=0.0) qs.append(q) Q = torch.stack(qs).cpu().numpy() # [2N+1, B] q1, q2, ql = Q[:args.n], Q[args.n:2 * args.n], Q[-1] am = Q[:2 * args.n].argmax(0) # action-style distance: how far each proposer's chunks sit from the logged one d1 = (c1 - a_log[None]).pow(2).mean(-1).sqrt().mean().item() d2 = (c2 - a_log[None]).pow(2).mean(-1).sqrt().mean().item() r = {"frames": int(args.frames), "mean_q_demoBC": float(q1.mean()), "mean_q_succBC": float(q2.mean()), "mean_q_logged": float(ql.mean()), "argmax_is_succBC": float((am >= args.n).mean()), "frac_frames_succ_mean_higher": float((q2.mean(0) > q1.mean(0)).mean()), "within_demoBC_std": float(q1.std(0).mean()), "within_succBC_std": float(q2.std(0).mean()), "rms_dist_to_logged_demoBC": d1, "rms_dist_to_logged_succBC": d2, "mean_r_at_frame": float(d.r[t].mean())} res[g] = r print(f"[bias] {g:10s} " + " ".join(f"{k}={v:.3f}" for k, v in r.items() if isinstance(v, float)), flush=True) json.dump({"args": vars(args), "res": res}, open(args.out, "w"), indent=1) print("[bias] DONE", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Policy-evaluation quality of the critics on HELD-OUT logged (state, action) pairs:Spearman / Pearson between each estimated Q(s,a) and the logged discounted return G_t. G_sub = (1-g) * sum_k g^k r_{t+k} r = per-frame BDDL subgoal fraction (dense) G_succ = g^(steps to success) if the episode succeeds else 0 (sparse, terminal)Arms: RSM restart-Q at depth 1 and 3 (16 particles, shared noise), RSM depth 1 with 256particles, the IQL Q trained on the same latent, the reward head alone r_hat(z_t) (nofuture), and the per-task constant (the null every pooled correlation has to beat).Pooled AND within-task (mean of per-task Spearman) are reported: pooled rank correlationis dominated by task identity (tasks differ in mean subgoal fraction).usage: q_vs_return_diag.py --cache C --critic ckpt --subgoal-dir D --mask M [--iql iql_q.pt] [--hop hop.pt]"""import argparse, os, sys, numpy as np, torchsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from data import LiberoRSMDatafrom is_ope import load_critic, q_recursive, make_policyfrom scipy.stats import spearmanr, pearsonr
ap = argparse.ArgumentParser()ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True)ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="")ap.add_argument("--iql", default=""); ap.add_argument("--hop", default="")ap.add_argument("--n", type=int, default=6000); ap.add_argument("--gamma", type=float, default=0.99)ap.add_argument("--beta", type=float, default=0.98)a = ap.parse_args()dev = "cuda" if torch.cuda.is_available() else "cpu"d = LiberoRSMData(a.cache, chunk=10, seed=0, in_ram=False, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, success_mask=a.mask, norm_pool="demos")enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d)hop = Noneif a.hop: hk = torch.load(a.hop, map_location=dev, weights_only=False) class _A: pass ha = _A(); [setattr(ha, k, v) for k, v in hk["config"].items()] hop = make_policy(ha, d, dev, d_z=cfg["d_z"]); hop.load_state_dict(hk["pol"]); hop.eval()qnet = Noneif a.iql: from iql import QNet ck = torch.load(a.iql, map_location=dev, weights_only=False) qnet = QNet(ck["d_z"], ck["d_act"], ck["n_task"]).to(dev); qnet.load_state_dict(ck["q"]); qnet.eval()rng = np.random.default_rng(0)g = a.gamma# ---- sample held-out frames with their logged action chunk and compute logged returnseps = d.val_eps; w = d.ep_len[eps].astype(np.float64); w /= w.sum()e = rng.choice(eps, size=a.n, p=w)t = d.ep_from[e] + (rng.random(a.n) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64)G_sub = np.zeros(a.n); G_succ = np.zeros(a.n); to_end = np.zeros(a.n)for i in range(a.n): lo, hi = int(t[i]), int(d.ep_to[e[i]]) rr = np.asarray(d.r[lo:hi], np.float64); k = np.arange(len(rr)) G_sub[i] = (1 - g) * float((g ** k * rr).sum()) G_succ[i] = (g ** (hi - lo)) if bool(d.ep_success[e[i]]) else 0.0 to_end[i] = hi - lox = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev)act = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(a.n, -1)res = {}with torch.no_grad(): z = enc(x) res["reward head r_hat(z_t) (no future)"] = torch.sigmoid(rew(z, tk)).cpu().numpy() def rsm(depth, part, crn=True): out = [] for i in range(0, a.n, 256): q, _ = q_recursive(z[i:i+256], act[i:i+256], tk[i:i+256], rew=rew, flow=flow, rms=rms, pol=hop, wend=None, beta=a.beta, gamma=g, depth=depth, n_particles=part, use_is=False, crn=crn) out.append(q.cpu()) return torch.cat(out).numpy() res["RSM depth 1, 16 particles"] = rsm(1, 16) res["RSM depth 1, 256 particles"] = rsm(1, 256) if hop is not None: res["RSM depth 3, 16 particles"] = rsm(3, 16) res["RSM depth 3, 256 particles"] = rsm(3, 256) if qnet is not None: res["IQL Q(z,a)"] = qnet(z, act, tk).squeeze(-1).cpu().numpy()tk_np = tk.cpu().numpy()res["per-task constant (null)"] = np.array([G_sub[tk_np == tt].mean() for tt in tk_np])def report(name, q): rows = [] for gname, G in (("G_sub", G_sub), ("G_succ", G_succ)): sp = spearmanr(q, G).correlation; pe = pearsonr(q, G)[0] wt = [spearmanr(q[tk_np == tt], G[tk_np == tt]).correlation for tt in range(d.n_task) if (tk_np == tt).sum() > 30] wt = [v for v in wt if v == v] rows.append(f"{gname}: spearman {sp:+.3f} pearson {pe:+.3f} within-task spearman {np.mean(wt):+.3f}") print(f"{name:36} | " + " | ".join(rows), flush=True)print(f"held-out frames n={a.n} from {len(eps)} val episodes; mean G_sub={G_sub.mean():.3f} mean G_succ={G_succ.mean():.3f}")for k, v in res.items(): report(k, np.asarray(v, np.float64))print("[diag] DONE")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""Was the ROLLOUT cache built with the same image preprocessing as the evaluator?
Hypothesis 2 of williamd4112/gen_q#251. The demo cache and the rollout cache havedifferent producers, and demo frames sit 48.7-61.5 from the nearest rollout frameagainst 7.5-9.2 within the rollout cloud. `to224`'s own docstring records that uint8quantisation alone moves the latent 3 sigma on the dimensions that matter and cost aworking policy 0.46 -> 0/50, with cosine similarity 0.999898 hiding it completely.
So: take a rollout episode's OWN raw frames (the parquets carry `image` and`wrist_image`), push them through the EVALUATOR's exact path, and compare against thatframe's cached latent. Agreement means the rollout cache matches the evaluator and thesupport gap is real scene difference. Disagreement means every rollout latent is in aspace the evaluator never produces, and no policy or critic trained on them can be readonline.
Reports L2 in z-scored feature units, so the numbers are directly comparable to the48.7-61.5 / 7.5-9.2 gap measured in #251 -- cosine similarity is deliberately NOT theheadline for the reason above."""from __future__ import annotationsimport argparse, importlib.util, io, os, re, sysfrom pathlib import Pathimport numpy as npimport torch
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from eval_closed_loop import to224, BUILDER
_spec = importlib.util.spec_from_file_location("ogpo_rc", BUILDER)ogpo = importlib.util.module_from_spec(_spec)sys.modules["ogpo_rc"] = ogpo_spec.loader.exec_module(ogpo)
PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$")PQ_ROOT = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1"
def decode(cell): """Parquet image cell -> HxWx3 uint8. LeRobot stores either raw bytes (PNG/JPEG) or a nested list; handle both rather than guessing.""" v = cell.as_py() if hasattr(cell, "as_py") else cell if isinstance(v, dict) and "bytes" in v: v = v["bytes"] if isinstance(v, (bytes, bytearray)): from PIL import Image return np.asarray(Image.open(io.BytesIO(v)).convert("RGB"), np.uint8) a = np.asarray(v) if a.dtype != np.uint8: a = (a * 255).round().clip(0, 255).astype(np.uint8) if a.max() <= 1.001 else a.astype(np.uint8) if a.ndim == 1: n = int(round((a.size / 3) ** 0.5)); a = a.reshape(n, n, 3) if a.ndim == 3 and a.shape[0] == 3: a = a.transpose(1, 2, 0) return a
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--n-ep", type=int, default=6) ap.add_argument("--frames", type=int, default=4, help="frames checked per episode") ap.add_argument("--pool", default="rollsucc", choices=["rollsucc", "demos"], help="demos re-encodes from the LIBERO hdf5 (agentview_rgb / " "eye_in_hand_rgb); the demo cache's npz holds no images") ap.add_argument("--src-res", type=int, default=0, help="resize the source image to this square resolution BEFORE " "to224, emulating a camera that renders at that size. The " "rollout parquets are 256x256; the evaluator renders at 128.") ap.add_argument("--flips", default="both,none,ud,lr", help="flip conventions to try; the evaluator uses img[::-1,::-1] = both") args = ap.parse_args()
import pyarrow.parquet as pq dev = "cuda" if torch.cuda.is_available() else "cpu" print(f"[rc] device {dev}", flush=True) tower = ogpo.build_paligemma(dev) from libero.libero import benchmark bench = benchmark.get_benchmark_dict()["libero_10"]()
C = Path(args.cache) m = np.load(C / "meta.npz", allow_pickle=True) fr, to = m["ep_from"].astype(int), m["ep_to"].astype(int) dem = m["ep_demo"].astype(bool); suc = m["ep_success"].astype(bool) tk = m["ep_task"]; dim = int(m["dim"]) Z = np.load(C / "z.f16.npy", mmap_mode="r").reshape(-1, dim) st = np.load(C / "feat_stats_demos.npz") sd_vis = st["sd"][:dim] # visual block only
flips = {"both": (slice(None, None, -1), slice(None, None, -1)), "none": (slice(None), slice(None)), "ud": (slice(None, None, -1), slice(None)), "lr": (slice(None), slice(None, None, -1))} want = [f for f in args.flips.split(",") if f in flips]
def frames_of(e): """(n_frames, getter(r) -> (agentview, wrist)) for episode e, from the raw image source that produced its cached latents.""" if args.pool == "rollsucc": g = PAT.search(str(m["ep_src"][e])) t, b, i, idx = g.groups() p = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") if not os.path.exists(p): return 0, None tb = pq.read_table(p, columns=["image", "wrist_image"]) return tb.num_rows, (lambda r: (decode(tb["image"][int(r)]), decode(tb["wrist_image"][int(r)]))) import h5py sp = str(m["ep_src"][e]) # .../<task>_demo/demo_7.npz tdir = Path(sp).parent.name # <task>_demo k = Path(sp).stem # demo_7 H = h5py.File(f"/data/pulkitag/users/rli14/libero_datasets/libero_10/{tdir}.hdf5", "r") ob = H["data"][k]["obs"] return ob["agentview_rgb"].shape[0], (lambda r: (np.asarray(ob["agentview_rgb"][int(r)]), np.asarray(ob["eye_in_hand_rgb"][int(r)])))
eps = np.where((suc & ~dem) if args.pool == "rollsucc" else dem)[0][:args.n_ep] print(f"[rc] pool={args.pool}: {len(eps)} episodes, {args.frames} frames each\n", flush=True) agg = {f: [] for f in want} for e in eps: t = int(tk[e]) n_src, get = frames_of(e) if get is None: print(f" ep {e}: source missing"); continue ids = ogpo.tokenize_prompt(bench.get_task(t).language) n = min(n_src, int(to[e] - fr[e])) rows = np.linspace(0, n - 1, args.frames).astype(int) for r in rows: im0, im1 = get(r) if args.src_res and im0.shape[0] != args.src_res: from PIL import Image _rs = lambda a: np.asarray(Image.fromarray(a).resize( (args.src_res, args.src_res), Image.BILINEAR), np.uint8) im0, im1 = _rs(im0), _rs(im1) z_cache = np.asarray(Z[fr[e] + int(r)], np.float32) for f in want: a, bb = flips[f] cams = [to224(im0[a, bb])[None], to224(im1[a, bb])[None]] z = np.concatenate( [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0] # L2 in z-scored units: comparable to the #251 support-gap numbers agg[f].append(float(np.linalg.norm((z - z_cache) / sd_vis))) print(f" ep {e} t{t} done " + " ".join( f"{f}={np.mean(agg[f][-args.frames:]):.2f}" for f in want), flush=True)
print(f"\n=== pool={args.pool}: re-encode vs cached latent, L2 in z-scored units ===") print("(reference from #251: rollout->nearest rollout 7.5-9.2, demo->nearest rollout 48.7-61.5)") for f in want: v = np.array(agg[f]) print(f" flip={f:<5} n={len(v):<4} mean={v.mean():>8.2f} min={v.min():>8.2f} max={v.max():>8.2f}") best = min(want, key=lambda f: np.mean(agg[f])) print(f"\nbest convention: {best} (evaluator uses 'both')")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121"""Re-encode the rollout corpus at the resolution the evaluator actually renders.
Finding (williamd4112/gen_q#251): the rollout latents in `pi05_lib10_ogpo_fl15_v1`were encoded from the collector's 256x256 renders. The closed-loop evaluator rendersat 128x128 (`camera_heights=128`), and so does the demo hdf5. Re-encoding a rolloutframe through the evaluator's own path puts it 74.97 z-scored units from its cachedlatent (within-cloud scale 7.5-9.2; demo cache re-encoded the same way: 4.27). Everyrollout latent is therefore off the manifold the evaluator produces -- which is whyBC on rollout successes is 0/500 with held-out action MSE 0.0008, and why a critictrained on a 90%-rollout corpus is read off-support online.
This rebuilds the rollout npz tree with latents from: parquet image (256, storedupright) -> 128 (PIL bilinear, emulating the 128 camera) -> 224 (PIL bilinear, thebuilder's own step) -> the SAME encoder. No flip: the parquet images are already inthe serving orientation (verified visually and by L2: flip=none matches at 4.26).proprio / actions / success / prompt / task_index are copied from the original npz,which are bit-identical to the parquet fields.
Output tree mirrors the input so pack.py runs unchanged with --src <out>."""from __future__ import annotationsimport argparse, importlib.util, io, os, re, sys, timefrom pathlib import Pathimport numpy as npimport torch
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from eval_closed_loop import BUILDERfrom recheck_encoding import decode, PAT, PQ_ROOT
_spec = importlib.util.spec_from_file_location("ogpo_re", BUILDER)ogpo = importlib.util.module_from_spec(_spec)sys.modules["ogpo_re"] = ogpo_spec.loader.exec_module(ogpo)
def prep(img, cam_res): """uint8 HxWx3 (upright) -> uint8 224x224x3 via the camera resolution.""" from PIL import Image im = Image.fromarray(img) if im.size != (cam_res, cam_res): im = im.resize((cam_res, cam_res), Image.BILINEAR) if im.size != (224, 224): im = im.resize((224, 224), Image.BILINEAR) # builder's own step return np.asarray(im, np.uint8)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--src", default="/data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1") ap.add_argument("--out", required=True) ap.add_argument("--cam-res", type=int, default=128) ap.add_argument("--shard", type=int, default=0) ap.add_argument("--num-shards", type=int, default=1) ap.add_argument("--only-cache", default="", help="meta.npz of a cache: re-encode only the episodes it uses " "(the 4,500-rollout subset first, the full corpus after)") ap.add_argument("--batch", type=int, default=128) ap.add_argument("--limit", type=int, default=0, help="smoke: stop after N episodes") args = ap.parse_args()
import pyarrow.parquet as pq dev = "cuda" if torch.cuda.is_available() else "cpu" tower = ogpo.build_paligemma(dev)
if args.only_cache: m = np.load(args.only_cache, allow_pickle=True) srcs = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] else: srcs = sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) srcs = srcs[args.shard::args.num_shards] if args.limit: srcs = srcs[:args.limit] print(f"[re] shard {args.shard}/{args.num_shards}: {len(srcs)} episodes -> {args.out} " f"(cam_res={args.cam_res}, device={dev})", flush=True)
t0 = time.time(); n_done = n_skip = 0 for k, sp in enumerate(srcs): rel = Path(sp).relative_to(args.src) op = Path(args.out) / rel if op.exists(): n_skip += 1; continue g = PAT.search(sp) t, b, i, idx = g.groups() pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") if not os.path.exists(pp): print(f"[re] MISSING parquet for {rel}", flush=True); continue z0 = np.load(sp, allow_pickle=True) T = int(z0["z"].shape[0]) tb = pq.read_table(pp, columns=["image", "wrist_image"]) if tb.num_rows < T: print(f"[re] {rel}: parquet has {tb.num_rows} rows < npz {T}; truncating", flush=True); T = tb.num_rows ids = ogpo.tokenize_prompt(str(z0["prompt"])) zs = [] for cam in ("image", "wrist_image"): frames = np.stack([prep(decode(tb[cam][j]), args.cam_res) for j in range(T)]) outs = [] for s in range(0, T, args.batch): outs.append(ogpo.encode_frames(tower, frames[s:s + args.batch], ids, dev, args.batch)) zs.append(np.concatenate(outs, 0)) z = np.concatenate(zs, 1).astype(np.float16) # [T, 4096] base||wrist assert z.shape == (T, z0["z"].shape[1]), (z.shape, z0["z"].shape) op.parent.mkdir(parents=True, exist_ok=True) tmp = str(op) + ".tmp.npz" np.savez(tmp, z=z, proprio=z0["proprio"][:T], actions=z0["actions"][:T], success=z0["success"], prompt=z0["prompt"], task_index=z0["task_index"]) os.replace(tmp, op) n_done += 1 if n_done % 25 == 0: el = time.time() - t0 print(f"[re] {k+1}/{len(srcs)} done={n_done} skip={n_skip} " f"{el/n_done:.1f}s/ep eta {(len(srcs)-k-1)*el/n_done/60:.0f} min", flush=True) print(f"[re] DONE shard {args.shard}: {n_done} written, {n_skip} existed", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Collect run artifacts into one honest table.
Reports what was actually measured and labels what was NOT. In particular theoffline metrics here are NOT closed-loop LIBERO success, so they cannot bythemselves support a claim of beating behaviour cloning; that requires the lane'sper-task closed-loop eval. This script prints the distinction rather than hiding it."""from __future__ import annotationsimport argparse, jsonfrom pathlib import Path
def row(k, v, w=34): print(f" {k:<{w}} {v}")
def winrate_ci(win, n, z=1.96): """Wilson interval for a win rate. The action gap is a heavy-tailed mean and swings between evals (+0.045 / +0.063 / +0.018 on consecutive checkpoints); the win rate over the same pairs is the stable statistic, so report it with an interval rather than quoting a point estimate.""" if not n: return (float("nan"), float("nan")) p = win d = 1 + z * z / n c = (p + z * z / (2 * n)) / d h = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / d return (c - h, c + h)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--critic", default="") ap.add_argument("--ope-signal", default="") ap.add_argument("--ope-null", default="") ap.add_argument("--awr", default="") a = ap.parse_args()
if a.critic: h = json.loads((Path(a.critic) / "history.json").read_text()) last, best = h[-1], max(h, key=lambda r: r["q_action_gap"]) print("\n== CRITIC (occupancy + reward latent) ==") row("reward AUC (held-out)", f"{last['reward_auc']:.4f}") row("occupancy CFM val loss", f"{last['cfm_val']:.4f}") row("latent std min (collapse guard)", f"{last['latent_std_min']:.4f}") lo, hi = winrate_ci(last["q_action_winrate"], 1024) row("ACTION gap (headline)", f"{last['q_action_gap']:+.5f} " f"(win {last['q_action_winrate']:.3f}, 95% CI [{lo:.3f},{hi:.3f}])") bh = last.get("by_horizon", {}) for k, v in bh.items(): blo, bhi = winrate_ci(v["action_winrate"], v["n"]) sig = "" if blo <= 0.5 <= bhi else " <-- excludes chance" row(f" frames-to-end {k}", f"gap {v['action_gap']:+.5f} win {v['action_winrate']:.3f} " f"[{blo:.3f},{bhi:.3f}] n={v['n']}{sig}") row(" best over training", f"{best['q_action_gap']:+.5f} @ step {best['step']}") row("state success AUC", f"{last['q_success_auc']:.4f}") print(" NOTE action gap is the metric that matters: COLLAPSE_ANALYSIS shows a") print(" state-ranking value with a flat action gap dies in closed loop.")
for tag, path in (("SIGNAL pi=BC(successes)", a.ope_signal), ("NULL pi=BC(all)~mu", a.ope_null)): if not path: continue r = json.loads((Path(path) / "report.json").read_text()) c, v = r["calibration"], r["value"] print(f"\n== OPE GATE :: {tag} ==") row("E_mu[w] after calibration", f"{c['E_mu[w_endpoint]']:.4f} (target 1.000)") row("calibration factor applied", f"{c['calib_scale']:.3f}") row("E_mu[W] raw chunk product", f"{c['E_mu[W_chunk]']:.4f} (target 1.000)") row("corr(endpoint w, chunk W)", f"{c['corr_w_vs_W']:.4f}") row("weight ESS fraction", f"{c['ess_frac']:.3f}") row("particle ESS fraction", f"{v['ess_particles']:.3f}") row("success AUC with IS", f"{v['auc_success_IS']:.4f}") row("success AUC without IS", f"{v['auc_success_noIS']:.4f}") row("relative |dQ| from IS", f"{v['rel_shift_IS_vs_noIS']:.4f}") row("expectation", v["gate_expectation"])
if a.awr: L = json.loads((Path(a.awr) / "loop.json").read_text()) print("\n== AWR LOOP ==") row("pi_0 offline score", json.dumps(L["pi_0"])) for r in L["rounds"]: adv = r["awr"][-1] if r["awr"] else {} row(f"round {r['round']} mean|adv|", f"{adv.get('mean_abs_adv', float('nan')):.4f} " f"(smolvla null result was 0.0190)") row(f"round {r['round']} score", json.dumps(r["score"]))
print("\nNOT MEASURED HERE: closed-loop LIBERO success. Every number above is") print("offline. Beating BC on demos (0.584 +- 0.025 step-matched in this lane)") print("requires the per-task closed-loop harness and is not claimed by this table.")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""The headline table: closed-loop LIBERO-10 success and throughput, four arms.
Throughput = pooled_SR * max_steps / mean_steps, reported two ways because theyanswer different questions: succ : mean steps over SUCCESSFUL episodes -- how fast it is when it works all : mean steps over ALL episodes -- a failure burns the full horizon, so this penalises failing twice (once in SR, once in wasted time)
Success rates are pooled over all task-episodes and carry a Wilson interval.Arms are compared against A_bc_demos, the BC-on-demonstrations bar an RSM recipehas to clear; a difference is only called a win when the intervals separate."""from __future__ import annotationsimport argparse, jsonfrom pathlib import Path
ARMS = [("LANE_CONTROL", "lane bcdemos (reference bar)"), ("A_bc_demos", "BC on demos, our pipeline"), ("B_bc_succ", "behaviour-policy extraction"), ("C_iql", "IQL critic + AWR"), ("D_rsm", "RSM critic + AWR (ours)")]
def wilson(k, n, z=1.96): if not n: return float("nan"), float("nan") p = k / n d = 1 + z * z / n c = (p + z * z / (2 * n)) / d h = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / d return c - h, c + h
def main(): ap = argparse.ArgumentParser() ap.add_argument("--eval-dir", default="/data/pulkitag/users/rli14/rsm_libero_runs/eval") a = ap.parse_args() d = Path(a.eval_dir)
got = {} for tag, _ in ARMS: f = d / f"{tag}.json" if f.exists(): got[tag] = json.loads(f.read_text())
print("\n== CLOSED-LOOP LIBERO-10 (10 tasks x 10 inits, max 520 steps) ==") print(f" {'arm':<12} {'what it is':<30} {'succ/n':>9} {'pooled SR':>10} " f"{'95% CI':>16} {'thr_succ':>9} {'thr_all':>8}") for tag, what in ARMS: r = got.get(tag) if r is None: print(f" {tag:<12} {what:<30} {'--':>9} {'not yet run':>10}") continue k, n = r["successes"], r["episodes"] lo, hi = wilson(k, n) print(f" {tag:<12} {what:<30} {f'{k}/{n}':>9} {r['pooled_SR']:>10.3f} " f"{f'[{lo:.3f},{hi:.3f}]':>16} {r['throughput_succ']:>9.3f} " f"{r['throughput_all']:>8.3f}")
# The bar is the REFERENCE policy when we have it: comparing our arms # against our own broken BC would let a 0.02 arm look like a "win". base = got.get("LANE_CONTROL") or got.get("A_bc_demos") if base: blo, bhi = wilson(base["successes"], base["episodes"]) print(f"\n== vs the BC-on-demos bar ({base['pooled_SR']:.3f}) ==") for tag, what in ARMS: if got.get(tag) is base: continue r = got.get(tag) if r is None: continue lo, hi = wilson(r["successes"], r["episodes"]) if lo > bhi: v = "WIN (intervals separate)" elif hi < blo: v = "LOSS (intervals separate)" else: v = "no separation at 95%" print(f" {tag:<12} {r['pooled_SR'] - base['pooled_SR']:+.3f} {v}")
if got: print("\n== per-task pooled SR ==") tasks = sorted({t for r in got.values() for t in r["per_task"]}) print(f" {'task':<52}" + "".join(f"{t:>12}" for t, _ in ARMS if t in got)) for tk in tasks: print(f" {tk[:50]:<52}" + "".join(f"{got[t]['per_task'].get(tk, float('nan')):>12.2f}" for t, _ in ARMS if t in got)) missing = [t for t, _ in ARMS if t not in got] if missing: print(f"\n NOT YET MEASURED: {', '.join(missing)} -- the table above is incomplete.")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318"""Re-render every rollout frame INSIDE the evaluator's environment, then encode.
Why not resize the collector's 256x256 pixels (reencode_rollouts.py)? Measured: a256->128 bilinear downsample lands in a THIRD region -- 63.7 from the live evaluatorfeature, 71.5 from the demo cloud, 81.5 from the old rollout cloud -- no closer to theevaluator than the cache it was meant to fix. SigLIP features do not survive anapproximate raster (to224's docstring: uint8 rounding alone is 3 sigma).
So do the only thing that is evaluator-consistent BY CONSTRUCTION: the parquets log`sim_state` for every frame; set it in the evaluator's own OffScreenRenderEnv(camera_heights=128, EGL), read both cameras exactly as eval_closed_loop does([::-1, ::-1], to224), encode with the evaluator's encoder. This is the admissibilityrule applied to features: a latent is admissible only if the eval environment canproduce it.
Built-in validation (--validate-demos N): the demo hdf5 stores `states`; re-renderingthose through this path must land ~4 z-scored units from the demo cache (which wasbuilt from the hdf5's own recorded images). If it does not, the path is wrong and norollout output should be trusted.
Output mirrors the input npz tree so pack.py runs unchanged. Idempotent (skipsexisting), atomic writes, requeue-safe."""from __future__ import annotationsimport argparse, importlib.util, os, re, sys, timefrom pathlib import Pathimport numpy as npimport torch
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from eval_closed_loop import BUILDER, to224, _eef_orifrom recheck_encoding import PAT, PQ_ROOT
_spec = importlib.util.spec_from_file_location("ogpo_rr", BUILDER)ogpo = importlib.util.module_from_spec(_spec)sys.modules["ogpo_rr"] = ogpo_spec.loader.exec_module(ogpo)
DEMO_H5 = os.environ.get("RSM_DEMO_H5", "/data/pulkitag/users/rli14/libero_datasets/libero_10")
class Renderer: """One evaluator env per task, reused across episodes.""" def __init__(self, cam_res=128): self.cam_res = cam_res from libero.libero import benchmark, get_libero_path from libero.libero.envs import OffScreenRenderEnv self.bench = benchmark.get_benchmark_dict()["libero_10"]() self.get_libero_path = get_libero_path; self.Env = OffScreenRenderEnv self.envs, self.ids = {}, {}
def env(self, tid): # ONE live env at a time. robosuite's offscreen EGL context is shared across # OffScreenRenderEnv instances in a process: with several alive, a render can # come from whichever model last touched the context (measured: a task-0 state # rendered as task-4's mugs and plates; one frame came back black). The # evaluator builds one env per task and closes it; do the same. if tid not in self.envs: for _k in list(self.envs): try: self.envs[_k].close() except Exception: pass self.envs.pop(_k, None) t = self.bench.get_task(tid) e = self.Env(bddl_file_name=str(Path(self.get_libero_path("bddl_files")) / t.problem_folder / t.bddl_file), camera_heights=self.cam_res, camera_widths=self.cam_res) e.reset(); e.step(np.zeros(7)) self.envs[tid] = e; self.ids[tid] = ogpo.tokenize_prompt(t.language) return self.envs[tid], self.ids[tid]
def frames(self, tid, states): """states [T, nq+nv] -> (agent [T,224,224,3], wrist [T,224,224,3], proprio [T,8])""" env, _ = self.env(tid) sim = env.env.sim A, W, P = [], [], [] for st in states: sim.set_state_from_flattened(np.asarray(st, np.float64)); sim.forward() # Python-side visuals are NOT in the MuJoCo state: the stove burner is a # site_rgba alpha in sim.model toggled by set_visualization() from # turn_on(qpos), which the env runs inside step() via _check_success -> # _post_process. Replay that update or a mid-episode kitchen frame renders # with the burner off while the logged image has it on (measured: kitchen # tasks drift 10-37, living-room tasks 3-4). try: env.env._check_success() except Exception: pass if hasattr(env.env, "set_visualization"): env.env.set_visualization() sim.forward() obs = env.env._get_observations(force_update=True) A.append(to224(obs["agentview_image"][::-1, ::-1])) W.append(to224(obs["robot0_eye_in_hand_image"][::-1, ::-1])) P.append(np.concatenate([obs["robot0_eef_pos"], _eef_ori(obs), obs["robot0_gripper_qpos"]]).astype(np.float32)) return np.stack(A), np.stack(W), np.stack(P)
def encode(tower, ids, A, W, dev, bs): za = ogpo.encode_frames(tower, A, ids, dev, bs) zw = ogpo.encode_frames(tower, W, ids, dev, bs) return np.concatenate([za, zw], 1).astype(np.float16)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--src", default="/data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1") ap.add_argument("--out", required=True) ap.add_argument("--shard", type=int, default=0) ap.add_argument("--num-shards", type=int, default=1) ap.add_argument("--only-cache", default="") ap.add_argument("--limit", type=int, default=0) ap.add_argument("--batch", type=int, default=128) ap.add_argument("--cam-res", type=int, default=256, help="256 = RLinf libero_10 env (lane evaluator + collector); 128 = demo hdf5") ap.add_argument("--pool", default="rollouts", choices=["rollouts", "demos", "demos_replay"], help="demos: re-render the 500 demo episodes from hdf5 `states` into a " "new demo cache tree (<out>/<task>_demo/demo_k.npz)") ap.add_argument("--validate-rollouts", type=int, default=0, help="re-render N rollout episodes (4 frames each) and report L2 to the " "CACHED rollout latent. ~4 at --cam-res 256 means our evaluator at 256 " "reproduces the collector, and the 43k latents are on-manifold as-is.") ap.add_argument("--validate-demos", type=int, default=0, help="re-render N demo episodes' hdf5 states and report L2 to the " "demo cache (z-scored, demo stats). Run BEFORE trusting output.") ap.add_argument("--demo-cache", default="/data/pulkitag/users/rli14/libero10_demo_ogpo_cache_cam128") ap.add_argument("--stats", default="/data/pulkitag/users/rli14/rsm_libero_cache/full_demo_cam256/feat_stats_demos.npz") args = ap.parse_args()
dev = "cuda" if torch.cuda.is_available() else "cpu" tower = ogpo.build_paligemma(dev) R = Renderer(args.cam_res) print(f"[rr] cam_res={args.cam_res} pool={args.pool}", flush=True)
if args.validate_demos: import h5py, glob st = np.load(args.stats); mu, sd = st["mu"][:4096], st["sd"][:4096] dists = [] h5s = sorted(glob.glob(f"{DEMO_H5}/*.hdf5")) for tid, h5 in enumerate(h5s[:args.validate_demos]): tname = Path(h5).stem[:-5] # strip _demo tids = [i for i in range(10) if R.bench.get_task(i).name == tname] if not tids: print(f"[rr] validate: no task for {tname}"); continue tid = tids[0] with h5py.File(h5, "r") as H: states = np.asarray(H["data"]["demo_0"]["states"][:]) rows = np.linspace(0, len(states) - 1, 4).astype(int) A, W, _ = R.frames(tid, states[rows]) _, ids = R.env(tid) z = encode(tower, ids, A, W, dev, args.batch).astype(np.float32) zc = np.load(f"{args.demo_cache}/{tname}_demo/demo_0.npz")["z"][rows].astype(np.float32) print(f"[rr] validate demo task {tid}: comparing against {args.demo_cache}", flush=True) dd = np.linalg.norm((z - zc) / sd, axis=1) dists += dd.tolist() print(f"[rr] validate demo task {tid} ({tname[:30]}): L2 to demo cache " f"{np.round(dd, 2).tolist()}", flush=True) print(f"[rr] VALIDATE demos: mean {np.mean(dists):.2f} max {np.max(dists):.2f} " f"(demo cache re-encoded from its own hdf5 images: 3.7-4.3; " f"anything >10 means this path is NOT the evaluator's)", flush=True)
import pyarrow.parquet as pq if args.validate_rollouts: st = np.load(args.stats); sd = st["sd"][:4096] m = np.load(args.only_cache, allow_pickle=True) if args.only_cache else None cand = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] if m is not None \ else sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) dists = [] for sp in cand[:args.validate_rollouts]: g = PAT.search(sp); t, b, i, idx = g.groups() pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") z0 = np.load(sp, allow_pickle=True); T = int(z0["z"].shape[0]) tb = pq.read_table(pp, columns=["sim_state"]) rows = np.linspace(0, min(T, tb.num_rows) - 1, 4).astype(int) states = np.stack([np.asarray(tb["sim_state"][int(r)].as_py(), np.float64) for r in rows]) tid = int(t) # from the FILENAME: the npz task_index field is wrong in the raw corpus (#234) A, W, P = R.frames(tid, states); _, ids = R.env(tid) z = encode(tower, ids, A, W, dev, args.batch).astype(np.float32) dd = np.linalg.norm((z - z0["z"][rows].astype(np.float32)) / sd, axis=1) dists += dd.tolist() # Is the LOGGED image the same scene as the LOGGED sim_state? Compare the # re-rendered proprio to the logged proprio (consistency of sim_state with # state/actions), and save frame-0 side by side for the eye. dp = float(np.abs(P - z0["proprio"][rows]).mean()) print(f"[rr] validate rollout t{t} {Path(sp).name}: L2 to cached " f"{np.round(dd, 2).tolist()} |rerendered proprio - logged| = {dp:.4f}", flush=True) try: from PIL import Image from recheck_encoding import decode tbi = pq.read_table(pp, columns=["image"]) logged = Image.fromarray(decode(tbi["image"][int(rows[0])])).resize((224, 224)) pair = Image.new("RGB", (448, 224)); pair.paste(logged, (0, 0)); pair.paste(Image.fromarray(A[0]), (224, 0)) od = Path(args.out) / "validate_pairs"; od.mkdir(parents=True, exist_ok=True) pair.save(od / f"{Path(sp).stem}_L2_{dd[0]:.0f}.png") except Exception as e: print(f"[rr] (pair save failed: {e})", flush=True) print(f"[rr] VALIDATE rollouts @{args.cam_res}: mean {np.mean(dists):.2f} " f"max {np.max(dists):.2f} (cache re-encoded from its own 256 pixels: 4.0-4.3)", flush=True)
if args.pool == "demos_replay": # REPLAY the demonstration's logged actions live in the evaluator env from its # logged initial state, recording what the env actually renders. Re-rendering # from per-frame sim_state cannot reproduce a live render on the kitchen/study # scenes (two fresh renders of the same state differ by 10-37 z-scored units; # living rooms 3-4), so the only demo frames that are guaranteed to be in the # evaluator's space are ones the evaluator itself produced along a trajectory. # A demo whose replay does not end in success is inadmissible (same rule as # rollouts) and is written with success=False so pack/BC can drop it. import h5py, glob n_done = n_ok = 0 for h5 in sorted(glob.glob(f"{DEMO_H5}/*.hdf5")): tname = Path(h5).stem[:-5] tids = [i for i in range(10) if R.bench.get_task(i).name == tname] if not tids: print(f"[rr] no task for {tname}"); continue tid = tids[0]; env, ids = R.env(tid) src_npz = sorted(glob.glob(f"{args.demo_cache}/{tname}_demo/demo_*.npz")) with h5py.File(h5, "r") as H: for sp in src_npz: k = Path(sp).stem; op = Path(args.out) / f"{tname}_demo" / f"{k}.npz" if op.exists(): continue z0 = np.load(sp, allow_pickle=True) acts = np.asarray(H["data"][k]["actions"][:], np.float32) st0 = np.asarray(H["data"][k]["states"][0], np.float64) env.reset(); env.env.sim.set_state_from_flattened(st0); env.env.sim.forward() obs, _, _, _ = env.step(np.zeros(7)) A, W, P = [], [], []; done = False for a in acts: A.append(to224(obs["agentview_image"][::-1, ::-1])) W.append(to224(obs["robot0_eye_in_hand_image"][::-1, ::-1])) P.append(np.concatenate([obs["robot0_eef_pos"], _eef_ori(obs), obs["robot0_gripper_qpos"]]).astype(np.float32)) obs, _, done, _ = env.step(a) if done: break T = len(A) z = encode(tower, ids, np.stack(A), np.stack(W), dev, args.batch) op.parent.mkdir(parents=True, exist_ok=True) tmp = str(op) + ".tmp.npz" np.savez(tmp, z=z, proprio=np.stack(P), actions=acts[:T], prompt=z0["prompt"], success=bool(done), replayed=True) os.replace(tmp, op); n_done += 1; n_ok += int(bool(done)) print(f"[rr] demos_replay task {tid}: {len(src_npz)} episodes, replay success so far " f"{n_ok}/{n_done}", flush=True) print(f"[rr] DONE demos_replay: {n_done} episodes, {n_ok} reproduce success " f"({n_ok / max(n_done, 1):.3f}) at cam_res={args.cam_res}", flush=True) return
if args.pool == "demos": import h5py, glob n_done = 0 for h5 in sorted(glob.glob(f"{DEMO_H5}/*.hdf5")): tname = Path(h5).stem[:-5] tids = [i for i in range(10) if R.bench.get_task(i).name == tname] if not tids: print(f"[rr] no task for {tname}"); continue tid = tids[0]; _, ids = R.env(tid) src_npz = sorted(glob.glob(f"{args.demo_cache}/{tname}_demo/demo_*.npz")) with h5py.File(h5, "r") as H: for sp in src_npz: k = Path(sp).stem; op = Path(args.out) / f"{tname}_demo" / f"{k}.npz" if op.exists(): continue z0 = np.load(sp, allow_pickle=True) states = np.asarray(H["data"][k]["states"][:]) T = min(len(states), int(z0["z"].shape[0])) A, W, P = R.frames(tid, states[:T]) z = encode(tower, ids, A, W, dev, args.batch) op.parent.mkdir(parents=True, exist_ok=True) tmp = str(op) + ".tmp.npz" np.savez(tmp, z=z, proprio=P, actions=z0["actions"][:T], prompt=z0["prompt"]) os.replace(tmp, op); n_done += 1 print(f"[rr] demos task {tid}: {len(src_npz)} episodes -> {args.out}/{tname}_demo " f"(total written {n_done})", flush=True) print(f"[rr] DONE demos: {n_done} episodes at cam_res={args.cam_res}", flush=True) return
if args.only_cache: m = np.load(args.only_cache, allow_pickle=True) srcs = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] else: srcs = sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) srcs = srcs[args.shard::args.num_shards] if args.limit: srcs = srcs[:args.limit] print(f"[rr] shard {args.shard}/{args.num_shards}: {len(srcs)} episodes -> {args.out}", flush=True)
t0 = time.time(); n_done = n_skip = 0 for k, sp in enumerate(srcs): rel = Path(sp).relative_to(args.src); op = Path(args.out) / rel if op.exists(): n_skip += 1; continue g = PAT.search(sp); t, b, i, idx = g.groups() pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" f"/data/chunk-000/episode_{int(idx):06d}.parquet") if not os.path.exists(pp): print(f"[rr] MISSING parquet {rel}", flush=True); continue z0 = np.load(sp, allow_pickle=True); T = int(z0["z"].shape[0]) tb = pq.read_table(pp, columns=["sim_state"]) T = min(T, tb.num_rows) states = np.stack([np.asarray(tb["sim_state"][j].as_py(), np.float64) for j in range(T)]) tid = int(t) # from the FILENAME: the npz task_index field is wrong in the raw corpus (#234) A, W, P = R.frames(tid, states) _, ids = R.env(tid) z = encode(tower, ids, A, W, dev, args.batch) # proprio: the re-rendered observation, which is what the evaluator would feed; # agrees with the logged `state` to float precision (checked: mean |d| = 0.0) op.parent.mkdir(parents=True, exist_ok=True) tmp = str(op) + ".tmp.npz" np.savez(tmp, z=z, proprio=P, actions=z0["actions"][:T], success=z0["success"], prompt=z0["prompt"], task_index=z0["task_index"]) os.replace(tmp, op); n_done += 1 if n_done % 25 == 0: el = time.time() - t0 print(f"[rr] {k+1}/{len(srcs)} done={n_done} skip={n_skip} {el/n_done:.1f}s/ep " f"eta {(len(srcs)-k-1)*el/n_done/60:.0f} min", flush=True) print(f"[rr] DONE shard {args.shard}: {n_done} written, {n_skip} existed", flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""How good is the RSM reward head, really? Held-out (val-split) frames, per task, plus thetwo failure modes that matter for ranking: (a) goal-mismatch (right state, wrong task id),(b) imagined endpoints (flow samples) vs. the true future subgoal fraction.usage: reward_diag.py --cache C --critic ckpt [--subgoal-dir D] [--mask M]"""import argparse, os, sys, numpy as np, torchsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from data import LiberoRSMDatafrom is_ope import load_criticfrom train_rsm import sample_future, auc
ap = argparse.ArgumentParser()ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True)ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="")ap.add_argument("--n", type=int, default=20000); ap.add_argument("--beta", type=float, default=0.98)a = ap.parse_args()dev = "cuda" if torch.cuda.is_available() else "cpu"d = LiberoRSMData(a.cache, chunk=10, seed=0, in_ram=False, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, success_mask=a.mask, norm_pool="demos")enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d)lat = enc # load_critic already wraps the encoder with the proprio append (same as the evaluator)rng = np.random.default_rng(0)with torch.no_grad(): fb = d.sample_frames(a.n, rng, "val", dev) x, tk, r = fb["x"], fb["task"], fb["r"].float() z = lat(x); rh = torch.sigmoid(rew(z, tk)) e = (rh - r); print(f"VAL frames n={a.n}: MSE={float(e.pow(2).mean()):.4f} (const-null MSE={float((r-r.mean()).pow(2).mean()):.4f}) " f"Pearson={float(np.corrcoef(rh.cpu(), r.cpu())[0,1]):.3f} mean r={float(r.mean()):.3f} mean r_hat={float(rh.mean()):.3f}") print(f" AUC(all subgoals satisfied, r==1): {auc(rh.cpu().numpy(), (r.cpu().numpy()>=0.999).astype(float)):.3f} " f"AUC(any progress, r>0): {auc(rh.cpu().numpy(), (r.cpu().numpy()>0.001).astype(float)):.3f}") # calibration by true fraction for lo, hi in ((0, 0.001), (0.001, 0.4), (0.4, 0.7), (0.7, 0.999), (0.999, 1.01)): m = (r >= lo) & (r < hi) if m.any(): print(f" true r in [{lo:.2f},{hi:.2f}): n={int(m.sum()):6d} mean r_hat={float(rh[m].mean()):.3f} std={float(rh[m].std()):.3f}") # per task for t in range(d.n_task): m = tk == t if m.sum() > 50: print(f" task {t}: n={int(m.sum()):5d} Pearson={float(np.corrcoef(rh[m].cpu(), r[m].cpu())[0,1]):.3f} MSE={float(e[m].pow(2).mean()):.4f} mean r={float(r[m].mean()):.3f}") # (a) goal mismatch: same latent, wrong task id tk2 = (tk + torch.randint(1, d.n_task, tk.shape, device=dev)) % d.n_task rh2 = torch.sigmoid(rew(z, tk2)) print(f"GOAL-MISMATCH (wrong task id): mean r_hat={float(rh2.mean()):.3f} vs correct-task {float(rh.mean()):.3f}; " f"fraction where wrong-task r_hat > correct-task r_hat: {float((rh2 > rh).float().mean()):.3f}") # (b) imagined endpoints: flow sample at beta vs true future subgoal fraction vb = d.sample(min(a.n, 8192), rng, a.beta, a.beta, "val", dev) zc = lat(vb["x_now"]); zf_true = lat(vb["x_fut"]) zf_imag = sample_future(flow, zc, vb["a_now"], vb["task"], vb["beta"], rms, 8, n=1) r_true_fut = torch.sigmoid(rew(zf_true, vb["task"])) r_imag = torch.sigmoid(rew(zf_imag, vb["task"])) print(f"IMAGINED ENDPOINTS (beta={a.beta}): r_hat(true future latent) mean={float(r_true_fut.mean()):.3f}, r_hat(flow sample) mean={float(r_imag.mean()):.3f}, " f"Pearson(imagined, true-future r_hat)={float(np.corrcoef(r_imag.cpu(), r_true_fut.cpu())[0,1]):.3f}, " f"Pearson(imagined, TRUE future subgoal fraction)={float(np.corrcoef(r_imag.cpu(), vb['r_fut'].float().cpu())[0,1]) if 'r_fut' in vb else float('nan'):.3f}") # (c) random latents: gaussian noise in latent space -> base-rate drift? zr = torch.randn_like(z) * z.std(0, keepdim=True) + z.mean(0, keepdim=True) print(f"RANDOM LATENTS (matched moments): mean r_hat={float(torch.sigmoid(rew(zr, tk)).mean()):.3f}")print("[diag] DONE")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325"""origin/main's MIMICGEN RSM port, applied to the LIBERO-10 latent corpus.
SCOPE CORRECTION. This file ports mimicgen_rsm/rsm_mimicgen/rsm.py, which isONE variant on main and not the main RSM recipe. The headline recipe inogbench_unified_rsm IS action-conditioned: its flow trains on (s, a, g) ->s_{t+K} pairs and hop 1 uses the queried action. Only the mimicgen port dropsthat, stating "NOT goal-conditioned ... d_beta(s'|s), reward(s), qf(s,a)".Both are worth running here; do not read this file as "what main does".
Our own recipe differs from main's in four ways that matter, and this file adoptsall four. See notes/rsm_formula_comparison.pdf for the derivation side.
1. REWARD IS AN ARRIVAL DETECTOR, NOT AN OUTCOME PREDICTOR. main: a classifier with a CALIBRATED threshold, hard-thresholded to r_hat(s) = 1[logit > thr] - 1 in {0, -1}; the threshold is fit on held-out episodes because "the classifier's scores are well ordered but not centred on 0". ours (until now): r = 1 on EVERY frame of a successful episode, i.e. P(this episode succeeds | s). Measured consequence of ours: a directly supervised Q(z,a) beats a state-only V(z) by AUC 0.9550 vs 0.9539, delta +0.0012 -- the action adds nothing, because whether an episode succeeds is a property of the state, not of the next 10 frames.
2. THE OCCUPANCY IS STATE-ONLY in THIS port: d_beta(s'|s). The ogbench recipe conditions on the action instead; that variant is the action-conditioned critic this lane already has.
3. THE ACTION ENTERS BY SUPERVISED REGRESSION, NOT BY CONDITIONING A GENERATIVE MODEL ON A COUNTERFACTUAL. main distils a student qf(s,a) <- r + gamma * (1-done) * V(s'), s' the REAL logged next state, with V from the frozen occupancy and, in their words, "no TD bootstrap off qf". Ours conditioned the flow on a candidate action, which is unsupervised in the action direction; probe_crn measured the result to have the right magnitude and an arbitrary sign.
4. ARRIVAL ABSORBS AND STOPPING IS GEOMETRIC OVER MANY HOPS. p_stop = beta(1-gamma)/(gamma(1-beta)); a rollout stops on the coin OR on reaching the goal, over max_hops (expected ~11 at beta=0.9, gamma=0.99). Ours read the reward once at a fixed depth of 2-3. The reduction is an optimistic hop-weighted expectile, not a plain mean."""from __future__ import annotationsimport sys as _sys, os as _os_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))import argparse, jsonfrom pathlib import Pathimport numpy as npimport torchimport torch.nn.functional as F
from data import LiberoRSMDatafrom model import Encoder, RewardHead, OccFlow, mlp, ema_updatefrom train_rsm import auc
# --------------------------------------------------------------------------- #def p_stop_of(beta: float, gamma: float) -> float: """main's geometric stopping probability. beta <= gamma is required.""" assert beta <= gamma, f"need beta <= gamma, got {beta} > {gamma}" return beta * (1.0 - gamma) / (gamma * (1.0 - beta)) if beta < gamma else 1.0
def hop_weighted_value(r, absorb_hop, tau, rho, gamma, gain=1.0): """main's speed-weighted upper expectile over per-rollout returns in {0,-1}.""" A = 1.0 / (2.0 * (1.0 - tau)) is_goal = r == 0.0 w = torch.where(is_goal, 1.0 + (A - 1.0) * gain * rho ** (absorb_hop.clamp_min(1) - 1).float(), torch.ones_like(r)) return ((w * r).sum(1) / w.sum(1).clamp_min(1e-12)) / (1.0 - gamma)
def value_from_at_goal_prob(q, tau, gamma): if tau == 0.5: m = q - 1.0 else: num = (1.0 - tau) * (1.0 - q) den = tau * q + (1.0 - tau) * (1.0 - q) m = -num / den.clamp_min(1e-12) return m / (1.0 - gamma)
class MainRSM(torch.nn.Module): """State-only occupancy + thresholded arrival reward + geometric-stop value."""
def __init__(self, d_lat, n_task, width=1024, depth=4): super().__init__() # d_act=1 with a zero action: the occupancy is state-only by construction, # while reusing the same FiLM/Fourier successor the rest of the lane uses. self.flow = OccFlow(d_lat, 1, n_task, width=width, depth=depth) self.rew = RewardHead(d_lat, n_task) self.register_buffer("rms", torch.ones(d_lat)) self.threshold = 0.0
def flow_v(self, z, task, beta, x_k, k): a0 = torch.zeros(z.shape[0], 1, device=z.device) return self.flow(z, a0, task, beta, x_k, k)
@torch.no_grad() def hop(self, z, task, beta, steps=8): x = torch.randn_like(z) for s in range(steps): k = torch.full((z.shape[0],), 1.0 - s / steps, device=z.device) x = x + self.flow_v(z, task, beta, x, k) / steps return z + x * self.rms
@torch.no_grad() def r_hat(self, z, task): """Hard arrival reward in {0, -1} at the CALIBRATED threshold.""" return (self.rew(z, task) > self.threshold).float() - 1.0
@torch.no_grad() def estimate_value(self, z, task, *, beta, gamma, n_samples=16, max_hops=20, tau=0.5, rho=0.9, gain=1.0, mode="hop", flow_steps=8): B = z.shape[0] p_stop = p_stop_of(beta, gamma) s = z.repeat_interleave(n_samples, 0) tk = task.repeat_interleave(n_samples, 0) bq = torch.full((s.shape[0],), beta, device=z.device) M = s.shape[0] active = torch.ones(M, dtype=torch.bool, device=z.device) stopped = s.clone() absorb = torch.zeros(M, dtype=torch.long, device=z.device) for h in range(1, max_hops + 1): s_next = self.hop(s, tk, bq, steps=flow_steps) s = torch.where(active.unsqueeze(-1), s_next, s) at_goal = self.r_hat(s, tk) == 0.0 coin = torch.rand(M, device=z.device) < p_stop just = active & (coin | at_goal) absorb = torch.where(just & at_goal, torch.full_like(absorb, h), absorb) stopped = torch.where(just.unsqueeze(-1), s, stopped) active = active & ~just if not active.any(): break stopped = torch.where(active.unsqueeze(-1), s, stopped) r = self.r_hat(stopped, tk).reshape(B, n_samples) ah = absorb.reshape(B, n_samples) if mode == "hop": return hop_weighted_value(r, ah, tau, rho, gamma, gain) q = (r == 0.0).float().mean(1) return value_from_at_goal_prob(q, tau, gamma)
class QStudent(torch.nn.Module): def __init__(self, d_lat, d_act, n_task, d_task=64, width=1024, depth=3): super().__init__() self.task = torch.nn.Embedding(n_task, d_task) self.net = mlp([d_lat + d_act + d_task] + [width] * depth + [1], norm=True)
def forward(self, z, a, task): return self.net(torch.cat([z, a, self.task(task)], -1)).squeeze(-1)
def calibrate_threshold(model, d, enc, dev, rng, n=8192): """Fit the cutoff on HELD-OUT frames, as main does.
Chosen to match the positive base rate rather than at logit 0: main's note is that the scores are well ordered but not centred, and estimate_value thresholds hard, so an uncentred cutoff silently changes the arrival rate. """ P, Y = [], [] with torch.no_grad(): for _ in range(max(1, n // 2048)): b = d.sample_frames(2048, rng, "val", dev) z = enc(b["x"]) P.append(model.rew(z, b["task"]).cpu().numpy()) Y.append(b["r"].cpu().numpy()) P = np.concatenate(P); Y = np.concatenate(Y) pos = float(Y.mean()) thr = float(np.quantile(P, 1.0 - pos)) if 0 < pos < 1 else 0.0 a = auc(P, Y) at_rate = float((P > thr).mean()) return thr, a, pos, at_rate
# --------------------------------------------------------------------------- #def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--out", required=True) ap.add_argument("--chunk", type=int, default=10) ap.add_argument("--d-z", type=int, default=256) ap.add_argument("--enc-width", type=int, default=1024) ap.add_argument("--flow-width", type=int, default=1024) ap.add_argument("--flow-depth", type=int, default=4) ap.add_argument("--beta", type=float, default=0.90) ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--k-success", type=int, default=10, help="frames at the END of a successful episode counted as " "AT GOAL. This is main's arrival convention; the dense " "whole-episode label is an outcome predictor and was " "measured to carry no action information.") ap.add_argument("--n-value-samples", type=int, default=16) ap.add_argument("--max-hops", type=int, default=20) ap.add_argument("--value-expectile", type=float, default=0.7) ap.add_argument("--expectile-mode", default="hop", choices=["hop", "reward"]) ap.add_argument("--hop-rho", type=float, default=0.9) ap.add_argument("--occ-steps", type=int, default=20000) ap.add_argument("--qf-steps", type=int, default=40000) ap.add_argument("--distill-states", type=int, default=153600, help="transitions in the distillation buffer; V is " "computed once per transition, not per batch") ap.add_argument("--batch", type=int, default=512) ap.add_argument("--qf-batch", type=int, default=256) ap.add_argument("--lr", type=float, default=3e-4) ap.add_argument("--ema", type=float, default=0.005) ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--seed", type=int, default=0) args = ap.parse_args()
torch.manual_seed(args.seed) dev = "cuda" if torch.cuda.is_available() else "cpu" out = Path(args.out); out.mkdir(parents=True, exist_ok=True) # ARRIVAL labels, not outcome labels d = LiberoRSMData(args.cache, chunk=args.chunk, k_success=args.k_success, seed=args.seed, in_ram=bool(args.in_ram), reward_mode="terminal", norm_pool=args.norm_pool) print(f"[main-rsm] {d.n_ep} eps, at-goal frames {float(d.r.mean()):.4f} " f"(main's arrival convention), p_stop " f"{p_stop_of(args.beta, args.gamma):.4f}, E[hops] " f"{1.0 / max(p_stop_of(args.beta, args.gamma), 1e-9):.1f}", flush=True)
enc = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) enc_t = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) enc_t.load_state_dict(enc.state_dict()) for p in enc_t.parameters(): p.requires_grad_(False) m = MainRSM(args.d_z, d.n_task, args.flow_width, args.flow_depth).to(dev) opt = torch.optim.AdamW(list(enc.parameters()) + list(m.flow.parameters()) + list(m.rew.parameters()), lr=args.lr, weight_decay=0.01) rng = np.random.default_rng(args.seed) pos_w = torch.tensor(max((1 - d.r.mean()) / max(d.r.mean(), 1e-6), 1.0), device=dev)
# ---- stage 1: state-only occupancy + arrival classifier ---- for step in range(1, args.occ_steps + 1): b = d.sample(args.batch, rng, args.beta, args.beta, "train", dev) z = enc(b["x_now"]) with torch.no_grad(): z_fut = enc_t(b["x_fut"]) l_rew = F.binary_cross_entropy_with_logits( m.rew(z, b["task"]), b["r_now"], pos_weight=pos_w) delta = z_fut - (z.detach() if step <= 2000 else z) with torch.no_grad(): m.rms.mul_(0.99).add_(delta.pow(2).mean(0).sqrt().clamp_min(1e-3), alpha=0.01) y = delta / m.rms k = torch.rand(args.batch, device=dev) noise = torch.randn_like(y) x_k = (1 - k)[:, None] * y + k[:, None] * noise v = m.flow_v(z if step > 2000 else z.detach(), b["task"], b["beta"], x_k, k) l_cfm = (v - (y - noise)).pow(2).mean() std = z.std(0) loss = l_rew + l_cfm + 10.0 * F.relu(0.1 - std).mean() opt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_( list(enc.parameters()) + list(m.flow.parameters()) + list(m.rew.parameters()), 1.0) opt.step(); ema_update(enc_t, enc, args.ema) if step % 2000 == 0: print(f"[occ] {step} rew={float(l_rew):.4f} cfm={float(l_cfm):.4f}", flush=True)
enc.eval(); m.eval() torch.save({"enc": enc.state_dict(), "flow": m.flow.state_dict(), "rew": m.rew.state_dict(), "rms": m.rms.cpu(), "config": vars(args)}, out / "stage1.pt") thr, a_r, pos, at_rate = calibrate_threshold(m, d, enc, dev, np.random.default_rng(args.seed + 5)) m.threshold = thr print(f"[main-rsm] arrival classifier AUC {a_r:.4f}; threshold {thr:+.3f} " f"calibrated to base rate {pos:.4f} (at-goal rate {at_rate:.4f})", flush=True)
# ---- stage 2: distil qf(z,a) <- r + gamma (1-done) V(z'), REAL z' ---- # Build the distillation BUFFER once. Recomputing V per batch means a fresh # 16-rollout, 20-hop expansion every step (<1.7 steps/s measured); the target # does not change during stage 2, so it is computed once and regressed on. rq = np.random.default_rng(args.seed + 11) Z, ZA, TK, TG = [], [], [], [] got, bs = 0, 512 while got < args.distill_states: b = d.sample_frames(bs, rq, "train", dev) t_next = np.minimum(b["t_idx"] + d.chunk, d.ep_to[b["ep"]] - 1) done = torch.from_numpy( (t_next >= d.ep_to[b["ep"]] - 1).astype(np.float32)).to(dev) with torch.no_grad(): z = enc(b["x"]) zn = enc(torch.from_numpy(d._feat(t_next)).to(dev)) r_now = m.r_hat(z, b["task"]) v_next = m.estimate_value( zn, b["task"], beta=args.beta, gamma=args.gamma, n_samples=args.n_value_samples, max_hops=args.max_hops, tau=args.value_expectile, rho=args.hop_rho, mode=args.expectile_mode) target = r_now + args.gamma * (1 - done) * v_next Z.append(z.cpu()); ZA.append(b["a"].cpu()) TK.append(b["task"].cpu()); TG.append(target.cpu()) got += bs if got % 25600 == 0: print(f"[buf] {got}/{args.distill_states} " f"target_mean={float(target.mean()):.3f}", flush=True) Z = torch.cat(Z); ZA = torch.cat(ZA); TK = torch.cat(TK); TG = torch.cat(TG) print(f"[buf] done {tuple(Z.shape)} target mean {float(TG.mean()):.3f} " f"sd {float(TG.std()):.3f}", flush=True)
qf = QStudent(args.d_z, d.chunk * d.adim, d.n_task).to(dev) qopt = torch.optim.Adam(qf.parameters(), lr=args.lr) for step in range(1, args.qf_steps + 1): idx = torch.randint(0, len(Z), (args.qf_batch,)) loss = F.mse_loss(qf(Z[idx].to(dev), ZA[idx].to(dev), TK[idx].to(dev)), TG[idx].to(dev)) qopt.zero_grad(); loss.backward() torch.nn.utils.clip_grad_norm_(qf.parameters(), 1.0); qopt.step() if step % 4000 == 0: print(f"[qf] {step} loss={float(loss):.4f}", flush=True)
torch.save({"enc": enc.state_dict(), "flow": m.flow.state_dict(), "rew": m.rew.state_dict(), "rms": m.rms.cpu(), "threshold": thr, "qf": qf.state_dict(), "config": vars(args), "d_act": d.chunk * d.adim, "tasks": d.tasks, "arrival_auc": a_r}, out / "main_rsm.pt") print("[main-rsm] DONE", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Driver: pi_0 -> ratio -> endpoint weight -> IS-corrected Q, with the gate.
Order of operations is deliberate. The IS machinery is validated BEFORE anypolicy is trained on it, because a critic that is never checked is how thesmolvla line shipped an advantage of 0.019 and a null AWR result."""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, train_bc, train_ratio, train_endpoint_ratio, train_likelihood_ratio, q_recursive, precompute_decision_logratio, chunk_logW_fast, effective_horizon)from train_rsm import auc
def main(): ap = argparse.ArgumentParser() ap.add_argument("--cache", required=True) ap.add_argument("--critic", required=True) ap.add_argument("--out", required=True) ap.add_argument("--batch", type=int, default=512) ap.add_argument("--beta-q", type=float, default=0.98) ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--depth", type=int, default=2) ap.add_argument("--particles", type=int, default=16) ap.add_argument("--bc-steps", type=int, default=8000) ap.add_argument("--ratio-steps", type=int, default=6000) ap.add_argument("--wend-steps", type=int, default=6000) ap.add_argument("--pi-mode", default="succ", choices=["succ", "all"], help="succ = BC on successful rollouts (a genuinely better " "target policy); all = BC on everything, which approximates " "the behaviour policy and is the NULL control: with pi ~= mu " "the weights must be ~1 and IS must not move Q.") ap.add_argument("--chunk", type=int, default=10, help="MUST match the critic's training chunk; the action\n dim is chunk*7 and a mismatch silently breaks loading") ap.add_argument("--ratio-mode", default="classifier", choices=["classifier", "likelihood"], help="classifier = discriminative density ratio (SHOWN BROKEN: " "an identity control puts two same-data policies at 0.945-" "0.977 separability, so the logit reads network identity). " "likelihood = genuine pi/mu_hat with tractable Gaussians.") ap.add_argument("--ratio-chunk", type=int, default=0, help="action length the IS ratio scores; 0 = same as --chunk. " "Set to the BEHAVIOUR POLICY decision period (10 for pi0.5). " "The occupancy may condition on a much longer window; the " "ratio is a product over DECISIONS and must not.") ap.add_argument("--reward-mode", default="dense", choices=["dense","terminal"], help="dense = P(task succeeds|z), every frame of a success is a " "positive (~50%%). terminal = last k frames only (~0.5%%), which " "leaves Q near-constant in the action.") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--in-ram", type=int, default=1) ap.add_argument("--policy-family", default="flow", choices=["flow", "gauss"]) ap.add_argument("--ratio-smooth", type=float, default=0.0, help="Gaussian kernel width applied to BOTH action classes before " "the ratio classifier; buys overlap at the cost of a blurred ratio") args = ap.parse_args()
# Seed torch too, not just numpy: the policy head init and the # flow-matching noise are torch RNG. Without this two arms meant to # differ in ONE flag start from different policies -- observed as # pi_0 separation gaps of 0.0170 (IS on) vs 0.0089 (IS off). torch.manual_seed(args.seed) dev = "cuda" if torch.cuda.is_available() else "cpu" out = Path(args.out); out.mkdir(parents=True, exist_ok=True) d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, in_ram=bool(args.in_ram), reward_mode=args.reward_mode) enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) args.d_z = cfg["d_z"] rng = np.random.default_rng(args.seed + 7) report = {"config": vars(args)}
only_succ = (args.pi_mode == "succ") print(f"=== pi_0: behaviour cloning ({'successes only' if only_succ else 'ALL data (null control)'}) ===", flush=True) pol = train_bc(d, enc, args, dev, only_success=only_succ, steps=args.bc_steps)
print("=== step 1: per-decision density ratio by classification ===", flush=True) rc = args.ratio_chunk or d.chunk if args.ratio_mode == "likelihood": ratio, pol_dec = train_likelihood_ratio( d, enc, args, dev, steps=args.ratio_steps, only_success=only_succ, chunk_len=rc) elif rc != d.chunk: print(f"=== fitting a DECISION-level policy (chunk {rc}) for the ratio ===", flush=True) print(f"=== fitting a DECISION-level policy (chunk {rc}) for the ratio ===", flush=True) pol_dec = train_bc(d, enc, args, dev, only_success=only_succ, steps=args.bc_steps, chunk_len=rc) ratio = train_ratio(d, enc, pol_dec, args, dev, steps=args.ratio_steps) else: pol_dec = pol ratio = train_ratio(d, enc, pol_dec, args, dev, steps=args.ratio_steps)
print("=== step 2/3: endpoint weight (Rao-Blackwellized) ===", flush=True) wend = train_endpoint_ratio(d, enc, ratio, args, dev, steps=args.wend_steps)
# ---------------- calibration: E_mu[w] should be ~1 ---------------- b = d.sample(4096, rng, args.beta_q, args.beta_q, "val", dev) with torch.no_grad(): z = enc(b["x_now"]); zf = enc(b["x_fut"]) w = wend(z, b["a_now"], zf, b["task"]) * getattr(wend, "calib", 1.0) pre = precompute_decision_logratio(d, enc, ratio, dev, rc=rc) W = torch.from_numpy(chunk_logW_fast(pre, b["t_idx"], b["fut_idx"])).to(dev) W = W.clamp(-4, 4).exp() ess = float((w.sum() ** 2) / (w.pow(2).sum() * len(w))) report["calibration"] = { "calib_scale": float(getattr(wend, "calib", 1.0)), "E_mu[W_chunk]": float(W.mean()), "E_mu[w_endpoint]": float(w.mean()), "w_p05": float(w.quantile(0.05)), "w_p50": float(w.quantile(0.5)), "w_p95": float(w.quantile(0.95)), "ess_frac": ess, "corr_w_vs_W": float(np.corrcoef(w.cpu().numpy(), W.cpu().numpy())[0, 1]), } print(f"[gate] E_mu[w]={w.mean():.3f} (target 1.0) ESS={ess:.3f} " f"corr(what,W)={report['calibration']['corr_w_vs_W']:.3f}", flush=True)
# ---------------- the falsifiable gate ---------------- # pi_synth := mu restricted to successful episodes. Its occupancy is directly # estimable, so the IS-corrected value can be checked against a reference # rather than merely asserted. fb = d.sample_frames(2048, rng, "val", dev) with torch.no_grad(): zq = enc(fb["x"]) q_is, ess_q = q_recursive(zq, fb["a"], fb["task"], rew=rew, flow=flow, rms=rms, pol=pol, wend=wend, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=True) q_no, _ = q_recursive(zq, fb["a"], fb["task"], rew=rew, flow=flow, rms=rms, pol=pol, wend=wend, beta=args.beta_q, gamma=args.gamma, depth=args.depth, n_particles=args.particles, use_is=False) succ = fb["succ"].cpu().numpy() dq = float((q_is - q_no).abs().mean() / q_no.abs().mean().clamp_min(1e-6)) report["horizon"] = effective_horizon(args.beta_q, args.gamma, args.depth) print(f"[horizon] depth={args.depth} -> {report['horizon']['mean_hops']:.2f} hops, " f"~{report['horizon']['effective_frames']:.0f} frames, " f"gamma_eff={report['horizon']['gamma_effective']:.4f} " f"(nominal {args.gamma}); truncated mass " f"{report['horizon']['truncation_mass']:.3f}", flush=True) report["value"] = { "pi_mode": args.pi_mode, "rel_shift_IS_vs_noIS": dq, "gate_expectation": ("null: weights ~1 and rel_shift should be SMALL" if args.pi_mode == "all" else "signal: pi is better than mu, Q should move UP"), "auc_success_IS": auc(q_is.cpu().numpy(), succ), "auc_success_noIS": auc(q_no.cpu().numpy(), succ), "q_mean_IS": float(q_is.mean()), "q_mean_noIS": float(q_no.mean()), "ess_particles": float(ess_q.mean()), "depth": args.depth, "beta": args.beta_q, "gamma": args.gamma, } print(f"[gate] pi_mode={args.pi_mode} success-AUC IS={report['value']['auc_success_IS']:.4f} " f"noIS={report['value']['auc_success_noIS']:.4f} " f"rel|dQ|={dq:.4f} particle ESS={float(ess_q.mean()):.3f}", flush=True)
torch.save({"pol": pol.state_dict(), "ratio": ratio.state_dict(), "wend": wend.state_dict(), "config": vars(args)}, out / "is_stack.pt") (out / "report.json").write_text(json.dumps(report, indent=2)) print(json.dumps(report, indent=2), flush=True)
if __name__ == "__main__": main()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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""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")12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287"""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 D = getattr(flow, "d_out", D) # V7_NONMARKOV: enc_z may be the history H(t); flow state = first D dims 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[:, :D] + 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("--val-eps-json", default="", help="split json with episodes[i]['split']=='valid' held out (e.g. data/derived/\n" "cooking_v6_split.json); overrides the seeded split. Default off.") ap.add_argument("--start-weight-npy", default="", help="float [n_frames] start-row sampling weights for TRAINING batches (V6_SCORER tier c " "junction oversampling). Default off = episode-uniform sampler, bit-identical.") ap.add_argument("--aug-group-npy", default="", help="int [n_frames] group id; with --start-weight-npy, aug pairs at up-weighted anchors " "whose neighbour has the same group are dropped. Default off.") ap.add_argument("--flow-x-noise", type=float, default=0.0, help="extra Gaussian noise on the state seen ONLY by the action-conditioned flow (not the " "reward head), applied per row with prob --flow-x-noise-p. 0 = off (no RNG drawn).") ap.add_argument("--flow-x-noise-p", type=float, default=0.5) 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("--hist-index", default="", help="V7_NONMARKOV: int64 [N,2] npy of history rows (t-D, t-2D). Set = the conditioning " "state is H(t)=[x_t|x_t-x_{t-D}|x_t-x_{t-2D}]; the flow still predicts x_{t+k}. '' = off.") ap.add_argument("--x-noise", type=float, default=0.0, help="Gaussian noise (z-scored units) added to the CONDITIONING state x_now seen by " "the flow and reward head during training (targets stay clean). Regulariser " "against memorising episode identity: mug M generalised only within the " "same-episode radius (NN dist 0.39) while other episodes sit at ~0.6, so val " "velocities exploded (cfm_val 112 vs 0.95 train at step 5000). 0 = off.") ap.add_argument("--flow-expectile", type=float, default=0.5, help="expectile tau for the flow-matching (occupancy) loss. 0.5 = OFF and takes the " "exact old code path (plain mean squared error on the velocity residual). With " "tau > 0.5 the loss is 2*|tau - 1(u<0)|*u^2 with u = target - prediction, so " "UNDER-prediction of the velocity toward the successor state is penalised more " "than over-prediction: an optimistic successor/value estimate in the sense of " "IQL-style expectile regression. tau < 0.5 is the pessimistic direction. The " "factor 2 makes tau=0.5 numerically identical to the mse, so the tau knob does " "not change the effective flow-loss weight.") ap.add_argument("--append-proprio", type=int, default=0, help="append normalised proprio to the LATENT, not just the " "encoder input. Feeding it as 8 of 4104 input dims did " "nothing: the encoder is trained by a reward loss that " "does not depend on joint state, so it drops them. " "Appending forces the successor to PREDICT the " "action-sensitive channel (action-proprio |r| 0.98 vs " "action-latent 0.49).") # ---- TD-Flow occupancy target (gen_q#268) ---- ap.add_argument("--occupancy-target", default="mc", choices=["mc", "td"], help="mc (DEFAULT, unchanged): the occupancy target is the logged future " "s_{t+k}, k ~ Geom(1-beta) truncated at the episode end -- Monte Carlo, no " "bootstrap. td: the Bellman right-hand side sampled off an EMA target " "field, (1-beta) delta_{s'} + beta psi_1(. | s', a'; theta_bar) " "(Farebrother et al. 2025, arXiv:2503.09817). EVERYTHING else -- velocity " "field, architecture, beta band and its per-anchor truncation cap, reward " "head, chunking, optimiser, steps -- is identical, so an `mc` run and a " "`td` run of the same cell differ in the occupancy target and nothing else.") ap.add_argument("--tdflow-variant", default="td_c", choices=list(TDFLOW_VARIANTS), help="td_c (DEFAULT) = Coupled TD-CFM, eq. 7: the interpolation source IS the " "noise that generated the bootstrap sample. td = TD-CFM, eq. 6: a fresh " "independent source. td2 = TD^2-CFM, eq. 8: the bootstrap term regresses " "the live velocity onto the TARGET FIELD's velocity at a random interior " "time along the target's own ODE path, so the loss FORM changes too.") ap.add_argument("--tdflow-target", default="ema", choices=["ema", "live"], help="which parameters the bootstrap reads. ema (DEFAULT): a target copy of " "the flow, EMA-updated at --tdflow-tau, as Algorithm 1 requires. live: no " "target network -- a diagnosis knob, not a reportable arm.") ap.add_argument("--tdflow-tau", type=float, default=-1.0, help="EMA rate of the target occupancy field; <0 means use --ema (0.995), the " "same rate the encoder target already uses.") ap.add_argument("--tdflow-mc-warmup", type=int, default=0, help="force the (1-beta) one-step branch for the first N updates. OFF by " "default: an arm that uses it is a HYBRID, not a clean TD-Flow baseline, " "and any table row carrying it must say so.") args = ap.parse_args()
torch.manual_seed(args.seed); rng = np.random.default_rng(args.seed) dev = "cuda" if torch.cuda.is_available() else "cpu" out = Path(args.out); out.mkdir(parents=True, exist_ok=True)
# ---- W&B (entity richardrl / project rsm_rise by default; resumable by run id) ---- wb = None if args.wandb_entity and args.wandb_mode != "disabled": try: import wandb, hashlib _rid = hashlib.md5((str(out.resolve()) + args.wandb_id_salt).encode()).hexdigest()[:16] wb = wandb.init(entity=args.wandb_entity, project=args.wandb_project, name=args.wandb_name or out.name, id=_rid, resume="allow", mode=args.wandb_mode, config=vars(args), dir=str(out)) print(f"[rsm] wandb: {wb.url}", flush=True) except Exception as e: # never let logging kill a run print(f"[rsm] wandb disabled: {e}", flush=True) wb = None
# A W&B TRANSPORT ERROR MUST NEVER KILL A TRAINING RUN. Added 2026-09-24 (AUG_SUCC run 39): # job 1900910 lost all four of its 100k cells at step ~35k when the wandb service process died # during the cluster-wide outage and the bare wb.log() raised ConnectionResetError out of main(). # The init above already had this intent ("never let logging kill a run"); the log sites did not. _wb_on = [wb is not None]
def _wb_log(payload, step): if not _wb_on[0]: return try: wb.log(payload, step=step) except Exception as e: _wb_on[0] = False print(f"[rsm] wandb log FAILED ({type(e).__name__}: {e}); W&B off for the rest of this " f"run, training continues", flush=True)
def _flat(prefix, obj, acc): """flatten nested dicts of floats for wandb.log""" if isinstance(obj, dict): for k, v in obj.items(): _flat(f"{prefix}/{k}" if prefix else str(k), v, acc) elif isinstance(obj, (int, float)): acc[prefix] = float(obj) return acc
d = LiberoRSMData(args.cache, chunk=args.chunk, k_success=args.k_success, seed=args.seed, hist_index=args.hist_index, 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, val_eps_json=args.val_eps_json, start_weight_npy=args.start_weight_npy, aug_group_npy=args.aug_group_npy, subgoal_dir=args.subgoal_dir) if args.cache2: # Second pack mixed into TRAINING batches only (validation stays on --cache so the # history is comparable). Use: on-policy rollouts of the proposers the critic has to # rank -- the base corpus is 99% pi0.5 rollouts, so the BC-demos policy's actions are # off-support for a critic fit on it alone (proposer_bias_diag: Q nearly flat over # demo-style chunks, 2x the spread over rollout-style chunks -> the arg-max over a # mixed pool is a winner's curse, not a value judgement). d2 = LiberoRSMData(args.cache2, chunk=args.chunk, k_success=args.k_success, seed=args.seed, stratify_success=bool(args.stratify_success), success_gamma=args.success_gamma, in_ram=bool(args.in_ram), reward_mode=args.reward_mode, subgoal_dir=args.subgoal_dir2, normalize=False) d2.norm_mu, d2.norm_sd = d.norm_mu, d.norm_sd # ONE feature transform assert d2.feat_dim == d.feat_dim and d2.n_task == d.n_task, "cache2 layout differs" print(f"[rsm] cache2: {d2.n_ep} eps, positives={d2.r.mean():.4f}, mixed at {args.mix2:.2f} " f"of every training batch", flush=True)
class _Mix: def __init__(self, a, b, p): self.a, self.b, self.p = a, b, p def __getattr__(self, k): return getattr(self.a, k) def sample(self, batch, rng, lo, hi, split="train", device="cuda", beta_trunc_eps=0.02, with_next=False, augment=True): if split != "train": return self.a.sample(batch, rng, lo, hi, split, device, beta_trunc_eps, with_next, augment) nb = int(round(batch * self.p)); na = batch - nb ba = self.a.sample(na, rng, lo, hi, split, device, beta_trunc_eps, with_next, augment) bb = self.b.sample(nb, rng, lo, hi, split, device, beta_trunc_eps, with_next, augment) out = {} for k in ba: if k not in bb: continue # one side augmented, the other not if k == "aug_frac": # a scalar diagnostic, not a row field out[k] = (na * ba[k] + nb * bb[k]) / max(batch, 1); continue if torch.is_tensor(ba[k]): out[k] = torch.cat([ba[k], bb[k]], 0) elif k == "aug_mask": out[k] = np.concatenate([ba[k], bb[k]]) else: out[k] = np.concatenate([ba[k], bb[k] + (self.a.n_ep if k == "ep" else self.a.ep_to[-1])]) return out d = _Mix(d, d2, args.mix2) print(f"[rsm] {d.n_ep} eps ({len(d.train_eps)} train / {len(d.val_eps)} val), " f"{d.n_task} tasks, dim={d.feat_dim}, positives={d.r.mean():.4f}", flush=True)
@torch.no_grad() def minmse_eval(lat_fn, flow_, enc_, enc_t_, rms_, split, n_samp, rows=2048, chunk_rows=256): """--eval-minmse-n: per-row min over N sampled futures of the per-dim MSE to the real logged x_{t+K}, in the latent the flow predicts in (identity: z-scored state).""" b = d.sample(rows, rng, args.beta_lo, args.beta_hi, split, dev, args.beta_trunc_eps, augment=False) # the training gate must stay on LOGGED pairs (see data.py) z_now = lat_fn(b["x_now"], enc_); z_fut = lat_fn(b["x_fut"], enc_t_) back = getattr(enc_, "back", None) # PCA: map samples back to the full state space mins, means, mins_f, means_f = [], [], [], [] for i in range(0, rows, chunk_rows): sl = slice(i, i + chunk_rows) xs = sample_future(flow_, z_now[sl], b["a_now"][sl], b["task"][sl], b["beta"][sl], rms_, args.flow_steps, n=n_samp) if args.sample_clip > 0 and back is None: xs = xs.clamp(-args.sample_clip, args.sample_clip) err = (xs.view(-1, n_samp, xs.shape[-1]) - z_fut[sl][:, None]).pow(2).mean(-1) # [rows, N] mins.append(err.min(1).values); means.append(err.mean(1)) if back is not None: xf = back(xs) if args.sample_clip > 0: xf = xf.clamp(-args.sample_clip, args.sample_clip) errf = (xf.view(-1, n_samp, xf.shape[-1]) - b["x_fut"][sl][:, None]).pow(2).mean(-1) mins_f.append(errf.min(1).values); means_f.append(errf.mean(1)) out = {"minmse": float(torch.cat(mins).mean()), "meanmse": float(torch.cat(means).mean()), "staymse": float((z_now[:, :z_fut.shape[1]] - 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, :dimf].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[:, :dx], 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) # V7_NONMARKOV: dx = width of the flowed state; the conditioning z may be wider (history) dx = d_lat d_cond = d.cond_dim if d.hist is not None else 0 assert d.hist is None or (args.enc == "identity" and n_pr == 0 and args.occupancy_target == "mc" and args.w_invdyn == 0 and args.w_rrank == 0 and not args.cache2), \ "--hist-index is only implemented for the identity-encoder MC recipe" 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, d_cond_z=d_cond).to(dev) # TD-Flow's theta_bar: the SAME module class and constructor arguments as the online field, so # the only difference between the two is how their weights got there. Built only for # --occupancy-target td, so the MC path allocates nothing extra and its step cost is unchanged. flow_t, tdf_tau = None, (args.ema if args.tdflow_tau < 0 else args.tdflow_tau) if args.occupancy_target == "td": flow_t = OccFlow(d_lat, d_act, d.n_task, width=args.flow_width, depth=args.flow_depth, norm=bool(args.flow_norm), dropout=args.flow_dropout).to(dev) flow_t.load_state_dict(flow.state_dict()) for _p in flow_t.parameters(): _p.requires_grad_(False) flow_t.eval() # dropout/norm in inference mode: theta_bar is only ever sampled from print(f"[rsm] OCCUPANCY TARGET = TD-Flow ({args.tdflow_variant}), target params " f"{args.tdflow_target} (tau={tdf_tau}), flow_steps={args.flow_steps}, " f"mc_warmup={args.tdflow_mc_warmup}", flush=True)
def lat(x, enc_fn): z = enc_fn(x) if not n_pr: return z return torch.cat([z, (x[:, -n_pr:] - pr_mu) / pr_sd], -1) invdyn = mlp([2 * d_lat, 1024, 1024, d_act], norm=True).to(dev) _trainable = (list(enc.parameters()) + list(rew.parameters()) + list(flow.parameters()) + list(invdyn.parameters())) opt = torch.optim.AdamW(_trainable, lr=args.lr, weight_decay=args.wd)
# running per-dimension RMS of the residual (the RECIPE normalisation) rms = torch.ones(d_lat, device=dev) hist = [] best_win = -1.0 t0 = time.time()
start_step = 0 _ck = out / "ckpt.pt" if args.resume and _ck.exists(): _c = torch.load(_ck, map_location=dev, weights_only=False) enc.load_state_dict(_c["enc"]); enc_t.load_state_dict(_c["enc_t"]) rew.load_state_dict(_c["rew"]); flow.load_state_dict(_c["flow"]) if flow_t is not None: # Without theta_bar a restart bootstraps off the ONLINE field for the first ~1/(1-tau) # steps, which is the one configuration Algorithm 1 forbids. Older TD blobs (or an # mc->td switch) have no flow_t; fall back to the online weights and say so. if "flow_t" in _c: flow_t.load_state_dict(_c["flow_t"]) else: flow_t.load_state_dict(flow.state_dict()) print("[rsm] resume: checkpoint carries no flow_t; theta_bar reinitialised from " "the online field", flush=True) if "invdyn" in _c: invdyn.load_state_dict(_c["invdyn"]) if "opt" in _c: opt.load_state_dict(_c["opt"]) rms = _c["rms"].to(dev) best_win = _c.get("best_win", -1.0) hist = _c.get("hist", []) start_step = int(_c["step"]) # decorrelate the stream from the pre-restart draws rng = np.random.default_rng(args.seed + 9973 * start_step) print(f"[rsm] RESUMED at step {start_step}/{args.steps} " f"(best action winrate {best_win:.3f})", flush=True) if start_step >= args.steps: print("[rsm] already complete; nothing to do", flush=True) return
# AUG_SUCC (gen_q#279): aug_frac goes to W&B, but a preempted+resumed run makes W&B DROP every # scalar below the pre-restart high-water step ("steps must be monotonically increasing"), so the # starvation curve the brief asks for develops holes exactly when the run gets preempted. Keep a # running mean on the side and persist it into history.json, which is resume-proof. _augf_sum, _augf_n = 0.0, 0
for step in range(start_step + 1, args.steps + 1): # with_next = the TD path only: it adds s_{t+1} and the logged chunk there to the batch and # draws NOTHING from `rng`, so the MC path's draws are bit-for-bit what they always were. b = d.sample(args.batch, rng, args.beta_lo, args.beta_hi, "train", dev, args.beta_trunc_eps, args.occupancy_target == "td") z = lat(b["x_now"], enc) with torch.no_grad(): z_fut_t = lat(b["x_fut"], enc_t) z_clean = z if args.x_noise > 0: # perturb what the networks CONDITION on; the residual target below is built from the # clean state so the flow still integrates to real futures at sampling time z = z + args.x_noise * torch.randn_like(z) # ---- reward head (class-balanced: positives are ~0.5% of frames) ---- logit = rew(z[:, :dx], 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()
# flow-only state noise (V6_SCORER tier c "actdrop"): the reward head above saw z; the # action-conditioned flow sees z_fl. Off -> z_fl IS z and no RNG is drawn. z_fl = z if args.flow_x_noise > 0: _m = (torch.rand(z.shape[0], 1, device=dev) < args.flow_x_noise_p).to(z.dtype) z_fl = z + _m * args.flow_x_noise * torch.randn_like(z)
# ---- 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[:, :dx].detach()) if step <= args.warmup_reward else (z_tgt - z_clean[:, :dx]) # 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_fl if step > args.warmup_reward else z_fl.detach(), b["a_now"], b["task"], b["beta"], x_k, k) if args.occupancy_target == "td" and args.tdflow_variant == "td2": # ell_td2 = (1-beta) || v_theta(X_t | s,a) - (Delta - X0) ||^2 # + beta || v_theta(Xc_t | s,a) - v_thetabar(Xc'_t | s', a') ||^2 # with Xc'_t = psi_tau(X0 | s', a'; theta_bar) the target's own path stopped at a random # tau, and Xc_t the same point expressed in THIS state's flow frame (a translation by # (z' - z)/rms, see the frame note on tdflow_occupancy_target). The weights are the # per-row Bellman mixture, not a batch mean, so a low-beta row still regresses mostly # on ground truth. --flow-expectile does not apply to this variant: the loss form # itself is the paper's, and an asymmetric weight on top of it would be a third method. _u_row = (v - (y - noise)).pow(2).mean(-1) tau_t = torch.rand(args.batch, device=dev) with torch.no_grad(): xc_p = _euler_to_tau(flow_b, z_next_t, b["a_next"], b["task"], b["beta"], noise, tau_t, args.flow_steps) xc_p = torch.nan_to_num(xc_p, nan=0.0, posinf=0.0, neginf=0.0) v_tgt = torch.nan_to_num( flow_b(z_next_t, b["a_next"], b["task"], b["beta"], xc_p, 1.0 - tau_t), nan=0.0, posinf=0.0, neginf=0.0) xc = xc_p + (z_next_t - z_clean.detach()) / rms v_live = flow(z if step > args.warmup_reward else z.detach(), b["a_now"], b["task"], b["beta"], xc, 1.0 - tau_t) l_cfm = ((1.0 - b["beta"]) * _u_row + b["beta"] * (v_live - v_tgt).pow(2).mean(-1)).mean() elif args.flow_expectile == 0.5: l_cfm = (v - (y - noise)).pow(2).mean() else: # expectile regression on the velocity residual (u = target - prediction); # tau > 0.5 up-weights u > 0, i.e. the model predicting too little motion. _tau = args.flow_expectile _u = (y - noise) - v _w = torch.where(_u >= 0, _tau, 1.0 - _tau) l_cfm = (2.0 * _w * _u.pow(2)).mean()
# Action-contrastive: the velocity conditioned on the TRUE chunk must # explain the true target better than one conditioned on another chunk # from the batch. Without this the successor can ignore A entirely, which # yields a value that ranks states but not actions. l_ac = torch.zeros((), device=dev) if args.w_actcon > 0: u = y - noise perm = torch.randperm(args.batch, device=dev) v_neg = flow(z_fl if step > args.warmup_reward else z_fl.detach(), b["a_now"][perm], b["task"], b["beta"], x_k, k) e_pos = (v - u).pow(2).mean(-1) e_neg = (v_neg - u).pow(2).mean(-1) l_ac = F.softplus(e_pos - e_neg).mean()
# ---- variance floor: stops the latent collapsing under the EMA target ---- std = z.std(0) l_var = F.relu(args.var_floor - std).mean()
# ---- read-out ranking on sampled hops (port: reward_rank_weight=2.0) ---- l_rr = torch.zeros((), device=dev) if args.w_rrank > 0: with torch.no_grad(): perm = torch.randperm(b["a"].shape[0], device=dev) a_shuf = b["a"][perm] hop_d = sample_future(flow, z.detach(), b["a"], b["task"], b["beta"], rms, args.flow_steps, n=1) hop_r = sample_future(flow, z.detach(), a_shuf, b["task"], b["beta"], rms, args.flow_steps, n=1) logit_d = rew(hop_d, b["task"]) logit_r = rew(hop_r, b["task"]) l_rr = -F.logsigmoid((logit_d - logit_r) / max(args.rrank_tau, 1e-6)).mean()
loss = (args.w_reward * l_rew + l_cfm + 10.0 * l_var + args.w_actcon * l_ac + args.w_invdyn * l_inv + args.w_rrank * l_rr) opt.zero_grad(); loss.backward() # total grad norm BEFORE clipping (clip_grad_norm_ returns it), plus per-module norms gn_total = float(torch.nn.utils.clip_grad_norm_(_trainable, 1.0)) opt.step() ema_update(enc_t, enc, args.ema) if flow_t is not None: # theta_bar <- tau theta_bar + (1-tau) theta, the same rule and the same rate the # encoder target uses. Stepped AFTER opt.step() so theta_bar always lags the online # field by exactly one update, as Algorithm 1 has it. ema_update(flow_t, flow, tdf_tau)
if args.action_augment > 0: _augf_sum += float(b.get("aug_frac", 0.0)); _augf_n += 1 if step % 500 == 0: print(f"[rsm] {step} rew={float(l_rew):.4f} cfm={float(l_cfm):.4f} " f"ac={float(l_ac):.4f} gradnorm={gn_total:.3f} " f"std_min={float(std.min()):.3f} ({step/(time.time()-t0):.1f} it/s)" + (f" aug={float(b.get('aug_frac', 0.0)):.3f}" if args.action_augment > 0 else "") + ("".join(f" td_{_k}={_v:.4g}" for _k, _v in td_diag.items()) if td_diag else ""), flush=True) if wb is not None and (step % args.log_every == 0 or step == 1): def _mod_gn(m): sq = [p.grad.detach().float().pow(2).sum() for p in m.parameters() if p.grad is not None] return float(torch.stack(sq).sum().sqrt()) if sq else 0.0 _log = {"train/loss": float(loss), "train/l_rew": float(l_rew), "train/l_cfm": float(l_cfm), "train/l_var": float(l_var), "train/l_actcon": float(l_ac), "train/l_invdyn": float(l_inv), "train/l_rrank": float(l_rr), "train/gradnorm": gn_total, "train/gradnorm_clipped": min(gn_total, 1.0), "train/gradnorm_enc": _mod_gn(enc), "train/gradnorm_rew": _mod_gn(rew), "train/gradnorm_flow": _mod_gn(flow), # THE STARVATION CHECK. A threshold that admits almost no pairs is visible in # this curve from step 1 rather than discovered after the run. "train/aug_frac": float(b.get("aug_frac", 0.0)), "train/latent_std_min": float(std.min()), "train/rms_mean": float(rms.mean()), "train/lr": opt.param_groups[0]["lr"], "train/it_per_s": step / max(time.time() - t0, 1e-6)} # TD-Flow diagnostics; empty dict (and so no extra keys) on the MC path. _log.update({f"train/td_{_k}": _v for _k, _v in td_diag.items()}) _wb_log(_log, step)
if step % args.eval_every == 0 or step == args.steps: enc.eval(); rew.eval(); flow.eval() with torch.no_grad(): vb = d.sample(2048, rng, args.beta_lo, args.beta_hi, "val", dev, args.beta_trunc_eps) zv = lat(vb["x_now"], enc) r_auc = auc(rew(zv[:, :dx], vb["task"]).cpu().numpy(), vb["r_now"].cpu().numpy()) zf = lat(vb["x_fut"], enc_t) yv = (zf - zv[:, :dx]) / 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), **({"d_cond": int(d_cond), "hist_index": args.hist_index} if d_cond else {})} # 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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187#!/usr/bin/env python"""V7_NONMARKOV: RSM HISTORY-successor Q on the FROZEN tests C / A / B / STITCH (+ V7_STOVE TUNE ranking + the pre-registeredstovehist test), written as Q caches for the unchanged scorers' 'cached' route (rsm_real / pairtest scorers untouched).
Port of reward2/rsm_scorer_ar.q_chain_value_ar (CHALLENGER read-out: 64 particles, beta .99, gamma .995, tail 1e-3, coin chain,goal read with a hop-head action, value clamp [-1, 10]) with the pre-registered generated-state history rule (status run 1): node j state g_j; its history input H_j = [g_j | g_j - g_{j-1} | g_j - g_{j-2}], g_0 = x_t, g_{-1} = x_{t-D}, g_{-2} = x_{t-2D} (real, from the episode's history-index array, first-frame padded). At each hop: g_{j+1} = flow sample(H_j, a_j) (1546-d; flow conditions on H_j), a_{j+1} = hop(H_{j+1}, eps_k). Goal read: g_* = flow sample(H_J, a_J), a_* = hop(H_*, eps_goal), value = head(H_*, a_*) for the space-A history c50 head (d_x 4638) / head(g_*, a_*) for the space-C JOINT head (d_x 1546). Since H_j carries g_{j-1} = g_j - H_j[D:2D], the update needs no extra buffer.CRN: one fixed draw set (seed --seed, default 0) of flow noise / hop eps / coins / goal eps indexed by particle, shared byEVERY row and candidate (the stock path draws them per scorer call from the global RNG; documented difference).--hist none reads a no-history successor exactly as the stock chain does (used for the span-0 equivalence check).usage: rsm_nm_qall.py --space A|C --succ CK --hop CK --head CK --name NAME --split tune|cv0..3 [--stove OUT] [--no-tests] [--no-stovehist] (TEST refused)"""import argparse, math, os, sys, timefrom pathlib import Pathimport numpy as np, torchR = Path("/proj/dmfexp/zwhong/rsm_rise")NMD = R / "scripts/real/v7/nonmarkov/rsm_libero_nm"sys.path.insert(0, str(NMD)); sys.path.insert(0, str(R / "scripts/real/v7/reward2")); sys.path.insert(0, str(R / "scripts/real/v7/iqlmatch"))import model as NMMimport rsm_scorer_ar as ARimport common as C
OUT = R / "runs/pairtest"; SH = R / "runs/v7_nonmarkov/stovehist"TESTS = ["A_logged", "A_end", "A_hold", "B_logged", "B_syn"]; FAMS = ["S_02f", "S_02s", "S_01f", "S_26", "S_1end"]ap = argparse.ArgumentParser()ap.add_argument("--space", required=True, choices=["A", "C"]); ap.add_argument("--succ", required=True)ap.add_argument("--hop", required=True); ap.add_argument("--head", required=True)ap.add_argument("--hist", default="auto", help="auto = the successor ckpt's hist_index; 'none' = no history")ap.add_argument("--split", default="tune"); ap.add_argument("--name", required=True)ap.add_argument("--np", type=int, default=64); ap.add_argument("--beta", type=float, default=0.99)ap.add_argument("--gamma", type=float, default=0.995); ap.add_argument("--tail", type=float, default=1e-3)ap.add_argument("--flow-steps", type=int, default=8); ap.add_argument("--seed", type=int, default=0)ap.add_argument("--bs", type=int, default=256, help="candidate rows per chain call (x np particles)")ap.add_argument("--stove", default=""); ap.add_argument("--no-tests", action="store_true"); ap.add_argument("--no-stovehist", action="store_true")a = ap.parse_args()assert a.split == "tune" or a.split in ("cv0", "cv1", "cv2", "cv3"), "TEST is closed"torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", "16")))dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")ef, et = C.meta(); row_ep = np.repeat(np.arange(len(ef)), et - ef)act_raw = np.load(C.CACHE_A / "act.f32.npy", mmap_mode="r")X0 = C.states(a.space); D = X0.shape[1]; assert D == 1546
# ---- successorck = torch.load(a.succ, map_location="cpu", weights_only=False); cfg = ck["config"]assert ck.get("enc_kind", cfg.get("enc")) == "identity" and int(ck.get("n_pr", 0) or 0) == 0hist = (ck.get("hist_index") or cfg.get("hist_index") or "") if a.hist == "auto" else ("" if a.hist == "none" else a.hist)assert (cfg.get("hist_index") or "") == hist, ("history of the successor != requested", cfg.get("hist_index"), hist)cache_ok = {"A": "real_cooking_v7", "C": "real_cooking_v7_dinoproj"}[a.space]assert str(cfg["cache"]).rstrip("/").endswith(cache_ok), (cfg["cache"], a.space)d_cond = 3 * D if hist else 0flow = NMM.OccFlow(D, int(ck["d_act"]), 1, width=cfg["flow_width"], depth=cfg["flow_depth"], norm=bool(cfg.get("flow_norm", 0)), dropout=float(cfg.get("flow_dropout", 0.0) or 0.0), d_cond_z=d_cond)flow.load_state_dict(ck["flow"]); flow = flow.to(dev).eval(); rms = ck["rms"].float().to(dev)for p in flow.parameters(): p.requires_grad_(False)DC = 3 * D if hist else Dif hist: HI = np.load(hist).astype(np.int64); assert HI.shape == (len(X0), 2)
# ---- hop (bc_arm gauss head on the conditioning state)hk = torch.load(a.hop, map_location="cpu", weights_only=False); hc = hk["config"]assert hc.get("policy_family") == "gauss" and hc.get("feat_scale", "zscore") == "zscore" and int(hc.get("chunk", 50)) == 50assert (hc.get("hist_index") or "") == hist, ("hop history mismatch", hc.get("hist_index"), hist)pol = NMM.BCHead(DC, hk["pol"]["mu.weight"].shape[0], 1); pol.load_state_dict(hk["pol"]); pol = pol.to(dev).eval()for p in pol.parameters(): p.requires_grad_(False)d_act = int(hk["pol"]["mu.weight"].shape[0]); assert d_act == int(ck["d_act"]) == 500
# ---- headhead = AR.ActRewardHead(a.head, device=dev); HX = int(head.arch["d_x"]); assert HX in (D, DC), (HX, D, DC)
# ---- chain constants + fixed CRN draws (== stock order: x0s[L+1], epss[L], coins, eps_goal)p_cont = (a.gamma - a.beta) / (a.gamma * (1.0 - a.beta)); L = int(math.ceil(math.log(a.tail) / math.log(p_cont)))g = torch.Generator(device="cpu"); g.manual_seed(a.seed); n = a.npx0s = torch.randn(L + 1, n, D, generator=g).to(dev); epss = torch.randn(L, n, d_act, generator=g).to(dev)coins = torch.rand(L, n, generator=g).to(dev); eps_goal = torch.randn(n, d_act, generator=g).to(dev)
def sample_future(Hc, act, x0): # == rsm_libero_nm/train_rsm.sample_future (n=1): absolute next state, 1546-d tk = torch.zeros(len(Hc), dtype=torch.long, device=dev); bq = torch.full((len(Hc),), a.beta, device=dev) x = x0 for s in range(a.flow_steps): k = torch.full((len(Hc),), 1.0 - s / a.flow_steps, device=dev) x = x + flow(Hc, act, tk, bq, x, k) / a.flow_steps return Hc[:, :D] + x * rms
def push(Hc, gnew): # H_{j+1} from H_j and g_{j+1} if not hist: return gnew gcur = Hc[:, :D]; gprev = gcur - Hc[:, D:2 * D] return torch.cat([gnew, gnew - gcur, gnew - gprev], 1)
def cond_rows(rows): x = X0[rows] if not hist: return x return np.concatenate([x, x - X0[HI[rows, 0]], x - X0[HI[rows, 1]]], 1)
@torch.no_grad()def q_of(rows, A_raw): """rows [B], A_raw [B,500] raw chunks -> Q [B] (mean over n particles of the clamped head read).""" B = len(rows); Rr = B * n Hc = torch.from_numpy(cond_rows(np.asarray(rows))).float().to(dev).repeat_interleave(n, 0) act = torch.from_numpy(np.asarray(A_raw, np.float32)).to(dev).repeat_interleave(n, 0) tk = torch.zeros(Rr, dtype=torch.long, device=dev); pid = torch.arange(n, device=dev).repeat(B) alive = torch.ones(Rr, dtype=torch.bool, device=dev) for k in range(L): cont = alive & (coins[k][pid] < p_cont); idx = cont.nonzero(as_tuple=True)[0]; alive = cont if idx.numel() == 0: break sub = pid[idx] gn = sample_future(Hc[idx], act[idx], x0s[k][sub]); Hn = push(Hc[idx], gn) an = pol.sample_eps(Hn, tk[idx], epss[k][sub]) Hc = Hc.index_copy(0, idx, Hn); act = act.index_copy(0, idx, an) gg = sample_future(Hc, act, x0s[L][pid]); Hg = push(Hc, gg) ag = pol.sample_eps(Hg, tk, eps_goal[pid]) v = head(Hg if HX == DC else Hg[:, :D], ag).float().clamp(-1.0, 10.0) return torch.nan_to_num(v, nan=0.0).view(B, n).mean(1).cpu().numpy()
def chunk(rows): rows = np.asarray(rows); fr = np.minimum(rows[:, None] + np.arange(50)[None], et[row_ep[rows]][:, None] - 1) return np.asarray(act_raw[fr.ravel()], np.float32).reshape(len(rows), -1)
def run(rows, A, bs=None): bs = bs or a.bs return np.concatenate([q_of(rows[i:i + bs], A[i:i + bs]) for i in range(0, len(rows), bs)]) if len(rows) else np.zeros(0)
print(f"[rsmnm] {a.name} {a.split} space {a.space} hist '{hist}' L {L} p_cont {p_cont:.4f} np {n} head d_x {HX} dev {dev}", flush=True)t0 = time.time(); nreq = 0if not a.no_tests: jobs = [] P_ = dict(np.load(OUT / f"pairs_v3_{a.split}.npz")) if (OUT / f"pairs_v3_{a.split}_ctrl.npz").exists(): P_.update(dict(np.load(OUT / f"pairs_v3_{a.split}_ctrl.npz"))) anc = P_["anc_row"]; cols = {"g": (anc, chunk(anc))} for c in ("BAD", "NOTPROG", "GOODNB"): if f"{c}_row" in P_: cols[c] = (anc, chunk(P_[f"{c}_row"])) jobs.append(("C", lambda nm: OUT / f"q_v3_{a.split}_{nm}.npz", cols)) for tn in TESTS: Tz = dict(np.load(OUT / "errmode" / f"{tn}_{a.split}.npz")); idx = np.flatnonzero(Tz["keep"]); r = Tz["anc"][idx] jobs.append((tn, (lambda nm, tn=tn: OUT / "errmode" / f"q_{tn}_{a.split}_{nm}.npz"), {"qg": (r, Tz["prog"][idx].astype(np.float32)), "qa": (r, Tz["alt"][idx].astype(np.float32))})) for fam in FAMS: Tz = dict(np.load(OUT / "stitch" / f"{fam}_{a.split}.npz")); r = Tz["anc"] if len(r) == 0: continue jobs.append((fam, (lambda nm, fam=fam: OUT / "stitch" / f"q_{fam}_{a.split}_{nm}.npz"), {"qg": (r, Tz["prog"].astype(np.float32)), "qa": (r, Tz["alt"].astype(np.float32))})) for nm, path, cc in jobs: Dd = {} for col, (rows, A) in cc.items(): Dd[col] = run(rows, A); nreq += len(rows) assert not any(np.isnan(v).any() for v in Dd.values()), nm if nm == "C": Dd = {**Dd, **{c + "_w": np.zeros(len(anc)) for c in list(Dd) if c != "g"}} np.savez(path(a.name), **Dd) print(f"[rsmnm] {a.name} {a.split} {nm}: " + " ".join(f"{k} {np.mean(v):.3f}" for k, v in Dd.items() if not k.endswith('_w')), flush=True)if not a.no_stovehist: Z = dict(np.load(SH / f"pairs_{a.split}.npz")); r = Z["anchor_row"] if len(r): qg, qb = run(r, chunk(r)), run(r, chunk(Z["partner_row"])); nreq += 2 * len(r) np.savez(SH / f"q_{a.split}_{a.name}.npz", qg=qg, qb=qb, cls=Z["cls"], anchor_row=r) print(f"[rsmnm] {a.name} {a.split} stovehist: {len(r)} pairs, frac qg>qb {np.mean(qg > qb):.3f}", flush=True)if a.stove: STV = R / "runs/v7_stove"; An = dict(np.load(STV / "anchors.npz")); idx = np.flatnonzero(An["split"] == "tune") Sm = np.zeros((len(An["anchor_row"]), 128, 50, 10), np.float16); have = np.zeros(len(Sm), bool) for k in range(8): z = np.load(STV / f"samples.part{k}.npz"); Sm[z["idx"]] = z["samples"]; have[z["idx"]] = True assert have[idx].all() rows = np.repeat(An["anchor_row"][idx], 128); A = Sm[idx].astype(np.float32).reshape(-1, 500) q = run(rows, A); assert not np.isnan(q).any() Path(a.stove).parent.mkdir(parents=True, exist_ok=True) np.savez(a.stove, idx=idx, q=q.reshape(len(idx), 128)); nreq += len(rows) print(f"[rsmnm] stove {len(idx)} TUNE anchors x 128 -> {a.stove}", flush=True)print(f"[rsmnm] {a.name} {a.split}: {nreq} (row, chunk) reads in {time.time()-t0:.0f}s", flush=True)1234567891011121314151617181920212223242526272829303132333435#!/usr/bin/env bash#SBATCH --partition=cpu#SBATCH --account=grp_runtime#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16#SBATCH --mem=64G#SBATCH --time=12:00:00#SBATCH --requeue --open-mode=append#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.out#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.err# V7_NONMARKOV: history read-out (dw_nm_qall.py; Ap c50 head / Cp joint head) of every checkpoint of one DINO-WM history run -> frozen scorers via 'cached'# (TUNE + cv0..3) + stove (TUNE). Per-model json in runs/v7_nonmarkov/eval/<name>/. TEST never. Resumable (done_* markers).# usage: RUN=<run dir> NAME=<prefix> [SPLITS=tune,cv0,...] sbatch -J rr_cpu_nm_ev_<x> run_eval_dw.sh (model = <prefix>_s<step>)set -uo pipefailexport PAIRTEST_VERSION=pairtest_v3cd /proj/dmfexp/zwhong/rsm_risePY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest; D=scripts/real/v7/nonmarkovSPLITS=${SPLITS:-tune,cv0,cv1,cv2,cv3}; EV=runs/v7_nonmarkov/evalecho "[nm_dw_eval] $RUN $NAME $(hostname) ${SLURM_JOB_ID:-} $(date -u)"for ck in $(ls $RUN/ckpt_s*.pt | sort -V); do st=$(basename $ck .pt); st=${st#ckpt_s}; n=${NAME}_s${st} [ -f $EV/$n/done_all_${SPLITS//,/_} ] && continue export PT_MODEL_JSON_DIR=$EV/$n; mkdir -p $PT_MODEL_JSON_DIR if [ ! -f $PT_MODEL_JSON_DIR/done_stove ]; then $PY $D/dw_nm_qall.py --no-tests --no-stovehist --name $n --ckpt $ck --stove runs/v7_nonmarkov/stove/q_${n}_tune.npz || exit 3 touch $PT_MODEL_JSON_DIR/done_stove; fi for sp in ${SPLITS//,/ }; do [ -f $PT_MODEL_JSON_DIR/done_$sp ] && continue $PY $D/dw_nm_qall.py --split $sp --name $n --ckpt $ck || exit 2 $PY $S/pairtest.py --stage score --split $sp --model $n=cached > /dev/null || exit 4 $PY $S/errmode_test.py --stage score --split $sp --model $n=cached > /dev/null || exit 5 $PY $S/stitch_test.py --stage score --split $sp --model $n=cached > /dev/null || exit 6 touch $PT_MODEL_JSON_DIR/done_$sp done touch $PT_MODEL_JSON_DIR/done_all_${SPLITS//,/_}; echo "[nm_dw_eval] scored $n $(date -u)"doneecho "[nm_dw_eval] done $(date -u)"123456789101112131415161718192021222324252627282930313233#!/usr/bin/env bash#SBATCH --partition=cpu#SBATCH --account=grp_runtime#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16#SBATCH --mem=96G#SBATCH --time=08:00:00#SBATCH --requeue --open-mode=append#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.out#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.err# V7_NONMARKOV IQL-history eval of every checkpoint of one run (copy of iqlmatch/run_eval.sh): score_iql_nm.py caches -> frozen scorers via "cached"# (TUNE + cv0..3; per-model json copies in runs/v7_nonmarkov/eval/<name>/). TEST never.# usage: RUN=runs/v7_nonmarkov/[C/]iql/<span>/<run> SPACE=<A|C> sbatch -J rr_cpu_nm_ev_<x> run_eval_iql_nm.sh (TEST never)set -uo pipefailexport PAIRTEST_VERSION=pairtest_v3cd /proj/dmfexp/zwhong/rsm_risePY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest; H=scripts/real/v7/iqlmatchSPLITS=${SPLITS:-tune,cv0,cv1,cv2,cv3}; R=$(basename $RUN)M=(); N=()for ck in $(ls $RUN/ckpt_s*.pt | sort -V); do st=$(basename $ck .pt); st=${st#ckpt_s}; n=${R}_s$st [ -f runs/v7_nonmarkov/eval/$n/done_all_${SPLITS//,/_} ] && continue; M+=(--model $n=$ck); N+=($n); done[ ${#N[@]} -eq 0 ] && { echo "[nm_iql_eval] nothing to do"; exit 0; }echo "[nm_iql_eval] $RUN ${N[*]} $(hostname) ${SLURM_JOB_ID:-} $(date -u)"$PY scripts/real/v7/nonmarkov/score_iql_nm.py --space $SPACE --splits $SPLITS "${M[@]}" ${NOSTOVE:+--no-stove} || exit 2for n in "${N[@]}"; do export PT_MODEL_JSON_DIR=runs/v7_nonmarkov/eval/$n for sp in ${SPLITS//,/ }; do $PY $S/pairtest.py --stage score --split $sp --model $n=cached > /dev/null || exit 4 $PY $S/errmode_test.py --stage score --split $sp --model $n=cached > /dev/null || exit 5 $PY $S/stitch_test.py --stage score --split $sp --model $n=cached > /dev/null || exit 6 done touch $PT_MODEL_JSON_DIR/done_all_${SPLITS//,/_}; echo "[nm_iql_eval] scored $n"doneecho "[nm_iql_eval] done $(date -u)"123456789101112131415161718192021222324252627#!/usr/bin/env bash# V7_NONMARKOV: CHALLENGER-setting history-chain read-out (rsm_nm_qall.py) of ONE RSM history successor ckpt -> frozen scorers via# 'cached' (TUNE + cv0..3) + stove (TUNE) + stovehist. Per-model json in runs/v7_nonmarkov/eval/<name>/. TEST never. Resumable.# usage: bash run_eval_rsm_nm.sh <A|C> <1s|3s> <seed> <step> (model name rsmnm<SP>_<span>_s<seed>_s<step>)set -uo pipefailSP=$1; SPAN=$2; SD=$3; ST=$4export PAIRTEST_VERSION=pairtest_v3R=/proj/dmfexp/zwhong/rsm_rise; cd $RPY=$R/venv_rsm/bin/python; S=scripts/real/v7/pairtest; Q=scripts/real/v7/nonmarkov/rsm_nm_qall.py; SPLITS=tune,cv0,cv1,cv2,cv3if [ $SP = A ]; then B=runs/v7_nonmarkov; SUCC=$B/rsm/$SPAN/nm_rsm_${SPAN}_s$SD/ckpt_s$ST.pt; HEAD=$B/head/$SPAN/c50_bal_adrop02/ckpt_best.ptelse B=runs/v7_nonmarkov/C; SUCC=$B/rsm/$SPAN/nmC_rsm_${SPAN}_s$SD/ckpt_s$ST.pt; HEAD=runs/v7_reward2_dinoproj/joint_v1_c50/ckpt_best.pt; fiHOP=$B/hop/$SPAN/gauss_h50_s1/policy_s120000.ptn=rsmnm${SP}_${SPAN}_s${SD}_s${ST}; EV=runs/v7_nonmarkov/eval/$n; mkdir -p $EV; export PT_MODEL_JSON_DIR=$EV[ -f $EV/done_all_${SPLITS//,/_} ] && { echo "[nm_rsm_eval] $n done already"; exit 0; }for f in $SUCC $HOP $HEAD; do [ -f $f ] || { echo "missing $f"; exit 2; }; doneA="--space $SP --succ $SUCC --hop $HOP --head $HEAD --name $n"echo "[nm_rsm_eval] $n $(hostname) ${SLURM_JOB_ID:-} gpu=${CUDA_VISIBLE_DEVICES:-} $(date -u)"if [ ! -f $EV/done_stove ]; then $PY $Q $A --no-tests --no-stovehist --stove runs/v7_nonmarkov/stove/q_${n}_tune.npz || exit 3; touch $EV/done_stove; fifor sp in ${SPLITS//,/ }; do [ -f $EV/done_$sp ] && continue $PY $Q $A --split $sp || exit 4 $PY $S/pairtest.py --stage score --split $sp --model $n=cached > /dev/null || exit 5 $PY $S/errmode_test.py --stage score --split $sp --model $n=cached > /dev/null || exit 6 $PY $S/stitch_test.py --stage score --split $sp --model $n=cached > /dev/null || exit 7 touch $EV/done_$spdonetouch $EV/done_all_${SPLITS//,/_}; echo "[nm_rsm_eval] scored $n $(date -u)"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105#!/usr/bin/env python"""V7_NONMARKOV copy of scripts/real/v7/iqlmatch/score.py. Changes: the state of each model is H(t) built with themodel's own config["hist_index"] (no hist_index in the config = plain x, i.e. a span-0 reference); stove output ->runs/v7_nonmarkov/stove; plus the pre-registered stovehist test (Q(anchor, own logged chunk) vs Q(anchor, partner logged chunk),written to runs/v7_nonmarkov/stovehist/q_<split>_<name>.npz). Original docstring:V7_IQLMATCH (chunk 50 and CHUNK-8 arms; a chunk-k model scores the FIRST k steps of every 50-step chunk): write Q caches (cached-Q route of pairtest/iql_all.py) for the frozen tests C / A,B errmode / STITCH onTUNE + cv0..cv3, and the V7_STOVE TUNE candidate scores. Pairs/rules are read as-is; Q = min_k Qtarget_k(x(anchor), a_n(chunk)),the FULL 50-step chunk each test gives (C: logged chunks via pairtest.chunk rule; errmode/stitch: prog/alt [500]).usage: score.py --space A|B|C --model NAME=CKPT ... [--splits tune,cv0,cv1,cv2,cv3] (TEST is refused)"""import argparse, sysfrom pathlib import Pathimport numpy as np, torchsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/iqlmatch")import common as C
PT = C.ROOT / "runs/pairtest"; STV = C.ROOT / "runs/v7_stove"; OUTS = C.ROOT / "runs/v7_nonmarkov/stove"; SH = C.ROOT / "runs/v7_nonmarkov/stovehist"TESTS = ["A_logged", "A_end", "A_hold", "B_logged", "B_syn"]; FAMS = ["S_02f", "S_02s", "S_01f", "S_26", "S_1end"]ap = argparse.ArgumentParser(); ap.add_argument("--space", required=True); ap.add_argument("--model", action="append", required=True)ap.add_argument("--splits", default="tune,cv0,cv1,cv2,cv3"); ap.add_argument("--no-stove", action="store_true"); ap.add_argument("--no-stovehist", action="store_true")a = ap.parse_args()assert "test" not in a.splits, "TEST closed"torch.set_num_threads(16)ef, et = C.meta(); row_ep = np.repeat(np.arange(len(ef)), et - ef)X0 = C.states(a.space); an = C.ActNorm(); XS = {"": X0}
def state_for(hi): # H(t) = [x_t | x_t - x_{t-D} | x_t - x_{t-2D}] with the model's own history-index array ("" = no history) if hi not in XS: I = np.load(hi).astype(np.int64); assert I.shape == (len(X0), 2) XS[hi] = np.concatenate([X0, X0 - X0[I[:, 0]], X0 - X0[I[:, 1]]], 1) return XS[hi]
act = np.load(C.CACHE_A / "act.f32.npy")models = []for kv in a.model: n, ck = kv.split("=", 1); q, cfg = C.load_reader(ck); assert cfg["space"] == a.space, (n, cfg["space"]) k = int(cfg.get("chunk", 50)); assert cfg["d_a"] == k * C.AD Xm = state_for(cfg.get("hist_index", "") or ""); assert Xm.shape[1] == cfg["d_s"], (n, Xm.shape, cfg["d_s"]) models.append((n, q, k, Xm)) # CHUNK-k model: first k steps
def Q(rows, A500): rows = np.asarray(rows, np.int64); assert np.shape(A500)[-1] == C.FULL * C.AD out = {}; acs = {k: torch.from_numpy(an(A500, k)) for k in {m[2] for m in models}} with torch.no_grad(): for n, q, k, Xm in models: ac = acs[k]; s = torch.from_numpy(Xm[rows]) out[n] = np.concatenate([q.qmin(s[i:i + 4096], ac[i:i + 4096]).numpy() for i in range(0, len(s), 4096)]).astype(np.float64) return out
def logged(rows): # the 50-step logged chunk (pairtest.chunk rule), independent of the model's chunk length rows = np.asarray(rows, np.int64) ch = np.minimum(rows[:, None] + np.arange(C.FULL)[None], et[row_ep[rows]][:, None] - 1) return act[ch.ravel()].reshape(len(rows), -1)
for S in a.splits.split(","): P = dict(np.load(PT / f"pairs_v3_{S}.npz")) if (PT / f"pairs_v3_{S}_ctrl.npz").exists(): P.update(dict(np.load(PT / f"pairs_v3_{S}_ctrl.npz"))) anc = P["anc_row"]; assert (row_ep[anc] == P["anc_ep"]).all() D = {n: {} for n, *_ in models} for col, rows in [("g", anc)] + [(c, P[f"{c}_row"]) for c in ("BAD", "NOTPROG", "GOODNB") if f"{c}_row" in P]: A = logged(rows); assert np.allclose(A[:, :C.AD], act[rows]) for n, v in Q(anc, A).items(): D[n][col] = v if col != "g": D[n][col + "_w"] = np.zeros(len(anc)) for n in D: np.savez(PT / f"q_v3_{S}_{n}.npz", **D[n]) for tn in TESTS: Tz = dict(np.load(PT / "errmode" / f"{tn}_{S}.npz")); idx = np.flatnonzero(Tz["keep"]); r = Tz["anc"][idx] assert Tz["prog"].shape[1] == 500 and np.allclose(Tz["prog"][idx, :C.AD], act[r], atol=1e-6) qg, qa = Q(r, Tz["prog"][idx]), Q(r, Tz["alt"][idx]) for n, *_ in models: np.savez(PT / "errmode" / f"q_{tn}_{S}_{n}.npz", qg=qg[n], qa=qa[n]) for fam in FAMS: Tz = dict(np.load(PT / "stitch" / f"{fam}_{S}.npz")); r = Tz["anc"] if len(r) == 0: continue qg, qa = Q(r, Tz["prog"]), Q(r, Tz["alt"]) for n, *_ in models: np.savez(PT / "stitch" / f"q_{fam}_{S}_{n}.npz", qg=qg[n], qa=qa[n]) if not a.no_stovehist: # pre-registered targeted test (pairs built model-free before scoring) Z = dict(np.load(SH / f"pairs_{S}.npz")); r = Z["anchor_row"] if len(r): qg, qb = Q(r, logged(r)), Q(r, logged(Z["partner_row"])) for n, *_ in models: np.savez(SH / f"q_{S}_{n}.npz", qg=qg[n], qb=qb[n], cls=Z["cls"], anchor_row=r) print(f"[iqlm-score] {S}: caches written for {len(models)} models ({len(anc)} C anchors)", flush=True)
if not a.no_stove: OUTS.mkdir(parents=True, exist_ok=True) A = dict(np.load(STV / "anchors.npz")); idx = np.flatnonzero(A["split"] == "tune") Sm = np.zeros((len(A["anchor_row"]), 128, 50, 10), np.float16); have = np.zeros(len(Sm), bool) for k in range(8): z = np.load(STV / f"samples.part{k}.npz"); Sm[z["idx"]] = z["samples"]; have[z["idx"]] = True assert have[idx].all() rows = np.repeat(A["anchor_row"][idx], 128); qq = Q(rows, Sm[idx].astype(np.float32).reshape(-1, 500)) for n, *_ in models: np.savez(OUTS / f"q_{n}_tune.npz", idx=idx, q=qq[n].reshape(len(idx), 128)) print(f"[iqlm-score] stove: {len(idx)} TUNE anchors x 128", flush=True)print("[iqlm-score] done", flush=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#!/usr/bin/env bash#SBATCH --partition=cpu#SBATCH --account=grp_runtime#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16#SBATCH --mem=64G#SBATCH --time=01:30:00#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.out#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.err# V7_NONMARKOV smoke: history arrays, default-off regression, tiny RSM / hop / head trainings with history (CPU).set -uo pipefailP=/proj/dmfexp/zwhong/rsm_rise; ROOT=/proj/dmfexp/zwhong/jm/rsm_rise; PY=$P/venv_rsm/bin/python; NM=$P/scripts/real/v7/nonmarkovS=$P/runs/v7_nonmarkov/smoke; rm -rf $S; mkdir -p $Sexport WANDB_MODE=disabledcd $P && $PY $NM/build_hist.py || exit 1echo "=== regression: default off == jm original; history shapes"cd $NM/rsm_libero_nm && $PY - <<'PY' || exit 1import sys, numpy as np, torch, importlib.utilC="/proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7"; SPL="/proj/dmfexp/zwhong/jm/rsm_rise/data/derived/cooking_v7_split.json"def load(path, name): sys.path.insert(0, path); spec = importlib.util.spec_from_file_location(name, path + "/data.py"); m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m); sys.path.pop(0); return mnew = load(".", "data_new"); old = load("/proj/dmfexp/zwhong/jm/gen_q_v7/rsm_libero", "data_old")kw = dict(chunk=50, seed=0, in_ram=False, reward_mode="dense", val_eps_json=SPL)a = old.LiberoRSMData(C, **kw); b = new.LiberoRSMData(C, **kw)for split in ("train", "val"): ra, rb = np.random.default_rng(5), np.random.default_rng(5) sa = a.sample(256, ra, .95, .998, split, "cpu"); sb = b.sample(256, rb, .95, .998, split, "cpu") for k in sa: va, vb = sa[k], sb[k] eq = torch.equal(va, vb) if torch.is_tensor(va) else np.array_equal(va, vb) assert eq, k fa = a.sample_frames(256, np.random.default_rng(3), split, "cpu"); fb = b.sample_frames(256, np.random.default_rng(3), split, "cpu") assert all(torch.equal(fa[k], fb[k]) if torch.is_tensor(fa[k]) else np.array_equal(fa[k], fb[k]) for k in fa)print("REGRESSION OK: sample()/sample_frames() bit-identical with history off; cond_dim", b.cond_dim)for D in ("0.5", "1.5"): h = new.LiberoRSMData(C, hist_index=f"/proj/dmfexp/zwhong/rsm_rise/runs/v7_nonmarkov/hist/hist_D{D}.npy", **kw) s = h.sample(64, np.random.default_rng(5), .95, .998, "train", "cpu"); t = s["t_idx"] x = h._feat(t); H = s["x_now"].numpy() assert H.shape == (64, 3 * h.feat_dim) and np.array_equal(H[:, :h.feat_dim], x) assert np.allclose(H[:, h.feat_dim:2*h.feat_dim], x - h._feat(h.hist[t, 0])) print("HIST OK D", D, H.shape, "lag rows sample", (t - h.hist[t, 0])[:8], (t - h.hist[t, 1])[:8], "|H_diff| mean", float(np.abs(H[:, h.feat_dim:]).mean()))import model as Mf0 = M.OccFlow(1546, 500, 1, width=64, depth=2, norm=True); f1 = M.OccFlow(1546, 500, 1, width=64, depth=2, norm=True, d_cond_z=0)assert [p.shape for p in f0.parameters()] == [p.shape for p in f1.parameters()]print("OccFlow default unchanged")PYHI=$P/runs/v7_nonmarkov/hist/hist_D1.5.npyecho "=== tiny RSM with history"cd $NM/rsm_libero_nm && $PY train_rsm.py --cache $ROOT/cache/real_cooking_v7 --out $S/rsm \ --enc identity --append-proprio 0 --reward-mode dense --reward-loss bce --reward-npy $ROOT/cache/real_cooking_v7/reward_progress.f32.npy \ --flow-width 1024 --flow-depth 4 --beta-lo 0.95 --beta-hi 0.998 --beta-q 0.992 --w-actcon 0.5 --var-floor 0 --warmup-reward 0 --batch 128 --lr 3e-4 --ema 0.995 --steps 20 --save-every 10 --eval-every 10 --eval-minmse-n 4 --eval-nnl1-k 4 --eval-nnl1-b 32 --sample-clip 10 --in-ram 1 --chunk 50 --seed 0 \ --flow-norm 1 --x-noise 0.3 --flow-dropout 0.1 --wd 0.1 --val-eps-json $ROOT/data/derived/cooking_v7_split.json --action-augment 0 --wandb-mode disabled --hist-index $HI || exit 1$PY -c "import torch; c=torch.load('$S/rsm/ckpt_s20.pt',map_location='cpu',weights_only=False); print('ckpt d_cond', c.get('d_cond'), c.get('hist_index'), 'cond W', c['flow']['cond.0.weight'].shape, 'out', c['flow']['out.weight'].shape)" || exit 1echo "=== tiny hop with history"$PY bc_arm.py --cache $ROOT/cache/real_cooking_v7 --out $S/hop --pool all --policy-family gauss --chunk 50 --pol-width 1024 --pol-depth 4 --batch 128 --bc-steps 20 --save-every 10 \ --in-ram 1 --seed 1 --wandb-mode disabled --val-eps-json $ROOT/data/derived/cooking_v7_split.json --hist-index $HI || exit 1ls $S/hopecho "=== tiny head with history"cd $P && $PY $NM/train_reward2_nm.py --out $S/head --act chunk50 --chunk 50 --act_drop 0.2 --hist_index $HI --steps 20 --batch 256 --eval_every 10 || exit 1ls $S/headecho "SMOKE ALL OK $(date -u)"123456789101112131415161718192021222324252627282930#!/usr/bin/env bash#SBATCH --partition=cpu#SBATCH --account=grp_runtime#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16#SBATCH --mem=96G#SBATCH --time=01:00:00#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.out#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.err# V7_NONMARKOV smoke 2: DINO-WM history trainer (4 steps + eval incl. history rollout + ckpt) and IQL history trainer (--smoke), both spans.# On success writes payloads/chain_{1s,3s}.sh.READY so pack 1's hop slots start the chain.set -uo pipefailP=/proj/dmfexp/zwhong/rsm_rise; PY=$P/venv_rsm/bin/python; NM=$P/scripts/real/v7/nonmarkov; S=$P/runs/v7_nonmarkov/smoke2; rm -rf $S; mkdir -p $Sexport OMP_NUM_THREADS=8 WANDB_MODE=disabledok=1for D in 0.5 1.5; do cd $NM && $PY -m torch.distributed.run --standalone --nproc_per_node 1 train_dw2_nm.py --space Ap --nhist 3 --out $S/dw2_$D --steps 4 --batch 8 \ --eval_every 4 --n_eval 8 --compile 0 --wandb 0 --save_at 4 --resume_every 2 --log_every 1 --workers 1 --hist_index $P/runs/v7_nonmarkov/hist/hist_D$D.npy || ok=0 $PY - <<PY || ok=0import sys, numpy as np, torchsys.path.insert(0, "$NM"); import nm_dw2 as N; W = N.WM = W.load_meta(); H, L = N.load_hist("$P/runs/v7_nonmarkov/hist/hist_D$D.npy")t = np.array([M["ep_from"][3] + 5, M["ep_from"][3] + 200]); fr, v, ar = N.frame_index_hist(M, t, H, L)print("lags", L, "frames", fr.tolist(), "valid", v.tolist(), "act rows", ar[:, :, 0].tolist())assert (fr[:, 3:] - fr[:, :3] <= 5).all() and v[1].all() and not v[0, 0]c = torch.load("$S/dw2_$D/ckpt_s4.pt", map_location="cpu", weights_only=False); print("arch hist", c["arch"]["hist_index"], c["arch"]["hist_lags"])PY cd $P && $PY $NM/train_iql_nm.py --space A --seed 0 --out $S/iql_$D --smoke --hist_index $P/runs/v7_nonmarkov/hist/hist_D$D.npy || ok=0 $PY -c "import json;print(json.load(open('$S/iql_$D/config.json'))['d_s'])" || ok=0doneif [ $ok = 1 ]; then touch $NM/payloads/chain_1s.sh.READY $NM/payloads/chain_3s.sh.READY; echo "SMOKE2 ALL OK -> READY $(date -u)"; else echo "SMOKE2 FAILED"; fi123456789101112131415161718192021222324252627282930#!/usr/bin/env bash#SBATCH --partition=cpu#SBATCH --account=grp_runtime#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16#SBATCH --mem=96G#SBATCH --time=01:00:00#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.out#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.err# V7_NONMARKOV smoke C: DINO-WM-C history+xnoise trainer (Cp) (4 steps + eval incl. history rollout + ckpt) and IQL history trainer (--smoke), both spans.# On success writes payloads/chain_{1s,3s}.sh.READY so pack 1's hop slots start the chain.set -uo pipefailP=/proj/dmfexp/zwhong/rsm_rise; PY=$P/venv_rsm/bin/python; NM=$P/scripts/real/v7/nonmarkov; S=$P/runs/v7_nonmarkov/smokeC; rm -rf $S; mkdir -p $Sexport OMP_NUM_THREADS=8 WANDB_MODE=disabledok=1for D in 0.5 1.5; do cd $NM && $PY -m torch.distributed.run --standalone --nproc_per_node 1 train_dw2_nmxn.py --space Cp --x-noise 0.3 --nhist 3 --out $S/dw2_$D --steps 4 --batch 8 \ --eval_every 4 --n_eval 8 --compile 0 --wandb 0 --save_at 4 --resume_every 2 --log_every 1 --workers 1 --hist_index $P/runs/v7_nonmarkov/hist/hist_D$D.npy || ok=0 $PY - <<PY || ok=0import sys, numpy as np, torchsys.path.insert(0, "$NM"); import nm_dw2 as N; W = N.WM = W.load_meta(); H, L = N.load_hist("$P/runs/v7_nonmarkov/hist/hist_D$D.npy")t = np.array([M["ep_from"][3] + 5, M["ep_from"][3] + 200]); fr, v, ar = N.frame_index_hist(M, t, H, L)print("lags", L, "frames", fr.tolist(), "valid", v.tolist(), "act rows", ar[:, :, 0].tolist())assert (fr[:, 3:] - fr[:, :3] <= 5).all() and v[1].all() and not v[0, 0]c = torch.load("$S/dw2_$D/ckpt_s4.pt", map_location="cpu", weights_only=False); print("arch hist", c["arch"]["hist_index"], c["arch"]["hist_lags"])PY cd $P && $PY $NM/train_iql_nmxn.py --space C --x-noise 0.3 --seed 0 --out $S/iql_$D --smoke --hist_index $P/runs/v7_nonmarkov/hist/hist_D$D.npy || ok=0 $PY -c "import json;print(json.load(open('$S/iql_$D/config.json'))['d_s'])" || ok=0doneif [ $ok = 1 ]; then touch $NM/payloads/chainC_1s.sh.READY $NM/payloads/chainC_3s.sh.READY; echo "SMOKEC ALL OK -> READY $(date -u)"; else echo "SMOKEC FAILED"; fi1234567891011121314151617181920212223#!/usr/bin/env bash#SBATCH --partition=cpu#SBATCH --account=grp_runtime#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16#SBATCH --mem=64G#SBATCH --time=04:00:00#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.out#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.err# V7_NONMARKOV smoke of rsm_nm_qall.py on TUNE: (1) no-history equivalence vs the stock CHALLENGER read-out of na_noaug_dr03_s0_s120000# (pairtest cached scorer -> C_tune acc compared with runs/v7_noaug/eval/na_noaug_dr03_s0_s120000/C_tune.json), (2) one history successor.set -uo pipefailexport PAIRTEST_VERSION=pairtest_v3 OMP_NUM_THREADS=16cd /proj/dmfexp/zwhong/rsm_risePY=venv_rsm/bin/python; NMS=scripts/real/v7/nonmarkov; S=scripts/real/v7/pairtest$PY $NMS/rsm_nm_qall.py --space A --hist none --split tune --name nmchk_dr03_s0_s120000 --no-stovehist \ --succ runs/real_cooking_v7/rsm_noaug/progress_noaug_dr03_h50_ps_s0/ckpt_s120000.pt \ --hop /proj/dmfexp/zwhong/jm/rsm_rise/export/v7/hop/gauss_h50_ps_s1/policy_s120000.pt --head runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt || exit 2export PT_MODEL_JSON_DIR=runs/v7_nonmarkov/eval/smoke_rsmnm$PY $S/pairtest.py --stage score --split tune --model nmchk_dr03_s0_s120000=cached > /dev/null || exit 3$PY $NMS/rsm_nm_qall.py --space A --split tune --name nmchk_rsm_1s_s0_s120000 --no-tests \ --succ runs/v7_nonmarkov/rsm/1s/nm_rsm_1s_s0/ckpt_s120000.pt --hop runs/v7_nonmarkov/hop/1s/gauss_h50_s1/policy_s120000.pt \ --head runs/v7_nonmarkov/head/1s/c50_bal_adrop02/ckpt_best.pt || exit 4echo "[smoke_rsmnm] OK $(date -u)"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122#!/usr/bin/env python"""V7_NONMARKOV table (json/npz only; login-node safe). Same pre-registered score as V7_NOAUG / V7_DINOWM2 / V7_IQLMATCH /V7_FAIRC: mean of {TUNE, CV-mean(cv0-3)} x {C BAD_primary, A_hold, B_logged, STITCH} + TUNE bestP>bestS + (1 - TUNE top-1 STOVE).Step per run = best score (ties within .005 -> earlier step). Arm = seed mean of the per-run picks over the PRE-REGISTERED seeds(s0, s1); RSM extra seed s2 (pack filler) shown as a 3-seed mean in a separate column. stovehist = frac Q(own chunk) > Q(partnerchunk) (ties .5) pooled over cv0-3 (+ TUNE n shown), at the picked step, per class P / T.Span-0 references = the existing runs (not re-run). Writes status/real/v7_nonmarkov_table.md + runs/v7_nonmarkov/select.json."""import json, refrom pathlib import Pathimport numpy as npR = Path("/proj/dmfexp/zwhong/rsm_rise"); ST = R / "status/real"; NM = R / "runs/v7_nonmarkov"SPL = ["tune", "cv0", "cv1", "cv2", "cv3"]COLS = [("C", "C", "BAD_primary"), ("A_log", "AB", "A_logged"), ("A_end", "AB", "A_end"), ("A_hold", "AB", "A_hold"), ("B_log", "AB", "B_logged"), ("B_syn", "AB", "B_syn"), ("STITCH", "ST", "STITCH")]PRIM = ["C", "A_hold", "B_log", "STITCH"]SO = R / "runs/v7_stove"; AN = dict(np.load(SO / "anchors.npz")); lab = np.load(SO / "cand_labels.npz")["lab"]NE, NS = NM / "eval", NM / "stove"# (model, space, span) -> (eval dir, stove dir, run prefix, model-name suffix, seeds)DWC = "dwnmCwu" if (NM / "C/dinowm_wu5k/SELECTED").exists() else "dwnmCc1"FAM = {}for sp in ("A", "C"): FAM[("RSM", sp, "0")] = ((R / "runs/v7_noaug/eval", R / "runs/v7_noaug/stove", "na_noaug_dr03", "", (0, 1)) if sp == "A" else (R / "runs/v7_learnproj/evalC", R / "runs/v7_learnproj/stove", "dp_noaug_dr03_jh", "", (0, 1))) FAM[("DINO-WM", sp, "0")] = ((R / "runs/real_cooking_v7/dinowm_v2/eval", R / "runs/real_cooking_v7/dinowm_v2/stove", "dw2_A_pooled_h3", "", (0, 1)) if sp == "A" else (R / "runs/v7_fairc/eval", R / "runs/v7_fairc/stove", "fc_dwCxnwu_pool_h3" if DWC == "dwnmCwu" else "fc_dwCxnc1_pool_h3", "_jh", (0, 1))) FAM[("IQL", sp, "0")] = ((R / "runs/v7_iqlmatch/eval", R / "runs/v7_iqlmatch/stove", "iqlm_A", "", (0, 1)) if sp == "A" else (R / "runs/v7_fairc/eval", R / "runs/v7_fairc/stove", "fc_iqlxn_C", "", (0, 1))) for span in ("1s", "3s"): FAM[("RSM", sp, span)] = (NE, NS, f"rsmnm{sp}_{span}", "", (0, 1, 2)) FAM[("DINO-WM", sp, span)] = (NE, NS, (f"dwnmAc1_{span}" if sp == "A" else f"{DWC}_{span}"), "", (0, 1)) FAM[("IQL", sp, span)] = (NE, NS, (f"iqlnm_{span}" if sp == "A" else f"iqlnmC_{span}"), "", (0, 1))
def stove(f): # = iqlmatch/table.py stove() if not f.exists(): return None z = np.load(f); idx, q = z["idx"], z["q"]; sel = np.flatnonzero(AN["cls"][idx] == 1); ii = idx[sel]; Q = q[sel]; x = lab[ii] top = x[np.arange(len(ii)), Q.argmax(1)]; both = (x == 1).any(1) & (x == 2).any(1) bp = np.where(x == 1, Q, -np.inf).max(1); bs = np.where(x == 2, Q, -np.inf).max(1); g = (bp - bs)[both] return float((top == 1).mean()), float((top == 2).mean()), float(np.where(g > 0, 1, np.where(g == 0, .5, 0)).mean())
SHJ = {"C": "rsm_pairtest_v3_{}.json", "AB": "rsm_errmode_{}.json", "ST": "rsm_stitch_{}.json"}_SH = {}
def shared(src, s): # fallback: the shared status/real results json (older streams kept only C per-model copies) if (src, s) not in _SH: f = ST / SHJ[src].format(s); _SH[(src, s)] = json.load(open(f)).get("models", {}) if f.exists() else {} return _SH[(src, s)]
def acc(ev, m, src, s, key): f = ev / m / f"{src}_{s}.json" M = json.load(open(f)) if f.exists() else shared(src, s).get(m, {}) M = M.get(key, {}) if isinstance(M, dict) else {} return M.get("acc") if isinstance(M, dict) else None
def row(ev, sv_dir, m): out = {} for c, src, key in COLS: tu = acc(ev, m, src, "tune", key); cv = [acc(ev, m, src, s, key) for s in SPL[1:]] out[c] = (tu, float(np.mean(cv)) if all(v is not None for v in cv) else None) sv = stove(sv_dir / f"q_{m}_tune.npz"); out["stove"] = sv nums = [v for c in PRIM for v in out[c]] + ([sv[2], 1 - sv[1]] if sv else [None, None]) out["score"] = float(np.mean(nums)) if all(v is not None for v in nums) else None return out
def stovehist(m): if not (NM / "stovehist" / f"q_cv0_{m}.npz").exists(): m = "ref_" + m # span-0 references: refs_stovehist.sbatch output r = {} for grp, spl in (("cv", SPL[1:]), ("tune", ["tune"])): qs = [np.load(NM / "stovehist" / f"q_{s}_{m}.npz") for s in spl if (NM / "stovehist" / f"q_{s}_{m}.npz").exists()] if len(qs) < len(spl): r[grp] = None; continue c = np.concatenate([np.where(z["qg"] > z["qb"], 1., np.where(z["qg"] == z["qb"], .5, 0.)) for z in qs]) cl = np.array(["P", "T"])[np.concatenate([z["cls"] for z in qs])] # build_stovehist: 0 = P, 1 = T r[grp] = {"acc": float(c.mean()) if len(c) else None, "n": int(len(c)), **{f"acc_{k}": (float(c[cl == k].mean()) if (cl == k).any() else None) for k in np.unique(cl).tolist()}, **{f"n_{k}": int((cl == k).sum()) for k in np.unique(cl).tolist()}} return r
RES = {}for key, (ev, svd, pre, suf, seeds) in FAM.items(): runs = {} for sd in seeds: rx = re.compile(re.escape(f"{pre}_s{sd}") + r"_s(\d+)" + re.escape(suf) + "$") ms = sorted(((int(rx.match(p.name).group(1)), p.name) for p in ev.iterdir() if p.is_dir() and rx.match(p.name))) if ev.exists() else [] xs = [(st, row(ev, svd, m)["score"], m) for st, m in ms]; xs = [x for x in xs if x[1] is not None] if not xs: runs[sd] = None; continue top = max(x[1] for x in xs); b = [x for x in xs if x[1] >= top - .005][0] runs[sd] = {"step": b[0], "model": b[2], "row": row(ev, svd, b[2]), "sh": stovehist(b[2]), "all": [(x[0], x[1]) for x in xs]} RES[key] = runs
f = lambda v: "-" if v is None else f"{v:.2f}"mean = lambda vs: None if (not vs or any(v is None for v in vs)) else float(np.mean(vs))HDR = "| model | space | span | seeds (step) | " + " | ".join(c for c, _, _ in COLS) + " | PAN | STOVE | bP>bS | **score** | 3-seed | stovehist CV (P/T) |"L = ["# V7_NONMARKOV -- short visual history (span 0 / 1 s / 3 s); cells TUNE/CV-mean, stove TUNE; TEST closed", "", HDR, "|" + "---|" * (len(COLS) + 10)]for (mdl, sp, span), runs in sorted(RES.items(), key=lambda kv: (kv[0][1], kv[0][0], kv[0][2])): pr = [runs.get(s) for s in (0, 1)] if any(p is None for p in pr): L.append(f"| {mdl} | {sp} | {span} | pending | " + " | ".join("-" for _ in COLS) + " | - | - | - | - | - | - |"); continue cells = " | ".join(f"{f(mean([p['row'][c][0] for p in pr]))}/{f(mean([p['row'][c][1] for p in pr]))}" for c, _, _ in COLS) sv = [p["row"]["stove"] for p in pr]; svm = tuple(np.mean(sv, 0)) if all(s is not None for s in sv) else (None,) * 3 sc = mean([p["row"]["score"] for p in pr]); ex = runs.get(2) sc3 = mean([p["row"]["score"] for p in pr + [ex]]) if ex else None shs = [p["sh"].get("cv") for p in pr] shtxt = "-" if any(s is None for s in shs) else (f"{f(mean([s['acc'] for s in shs]))} ({f(mean([s.get('acc_P') for s in shs]))}/" f"{f(mean([s.get('acc_T') for s in shs]))}; n {shs[0]['n']})") L.append(f"| {mdl} | {sp} | {span} | " + ", ".join(f"s{s}@{runs[s]['step'] // 1000}k" for s in (0, 1)) + f" | {cells} | " f"{f(svm[0])} | {f(svm[1])} | {f(svm[2])} | **{f(sc)}** | {f(sc3)} | {shtxt} |")L += ["", "Per-run step curves (score):", ""]for (mdl, sp, span), runs in sorted(RES.items(), key=lambda kv: (kv[0][1], kv[0][0], kv[0][2])): for sd, r in runs.items(): if r: L.append(f"- {mdl} {sp} {span} s{sd}: pick {r['step'] // 1000}k; " + ", ".join(f"{s // 1000}k {v:.3f}" for s, v in r["all"]))json.dump({f"{k[0]}|{k[1]}|{k[2]}": v for k, v in RES.items()}, open(NM / "select.json", "w"), indent=1, default=float)open(ST / "v7_nonmarkov_table.md", "w").write("\n".join(L) + "\n")print("\n".join(L))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224#!/usr/bin/env python"""V7_DINOWM2 trainer (torchrun DDP, one run per 8-GPU job). See dw2_common.py for the model / data definition.
Fixed recipe (owner 2026-11-22): batch 1024 = micro 128 x 8 GPUs (no accumulation), 100k steps, AdamW lr 3e-4 wd .01,constant lr (official), no grad clipping (grad norm logged; --clip only if the loss diverges), EMA .995 (evaluatedweights), bf16 autocast, ckpts at 20/40/60/80/100k (+ resume ckpt.pt every 2k). TRAIN split only; in-trainingdiagnostics on TUNE (teacher-forced next-macro MSE, 10-macro rollout MSE at the chunk end vs the copy baseline)."""import argparse, copy, json, os, sys, threading, queue, timefrom pathlib import Pathimport numpy as npimport torch, torch.nn as nn, torch.nn.functional as Fimport torch.distributed as distsys.path.insert(0, str(Path(__file__).resolve().parent))import nm_dw2 as NMH # V7_NONMARKOV history helpers (imports dinowm2/dw2_common)W = NMH.W
ap = argparse.ArgumentParser()ap.add_argument("--space", required=True, choices=list(W.SPACES)); ap.add_argument("--seed", type=int, default=0)ap.add_argument("--out", required=True)ap.add_argument("--steps", type=int, default=100000); ap.add_argument("--batch", type=int, default=1024)ap.add_argument("--micro", type=int, default=0, help="per-GPU batch (default batch/world; must equal it: no accumulation)")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("--clip", type=float, default=0.0)ap.add_argument("--save_at", default="20000,40000,60000,80000,100000"); ap.add_argument("--resume_every", type=int, default=2000)ap.add_argument("--eval_every", type=int, default=2500); ap.add_argument("--log_every", type=int, default=100)ap.add_argument("--n_eval", type=int, default=512); ap.add_argument("--workers", type=int, default=4)ap.add_argument("--compile", type=int, default=1); ap.add_argument("--grad_ckpt", type=int, default=0)ap.add_argument("--warmup", type=int, default=0, help="linear lr warmup steps (0 = official constant lr; contingency only)")ap.add_argument("--nhist", type=int, default=W.NH, help="history frames (official 3; owner arm 1)")ap.add_argument("--hist_index", required=True, help="V7_NONMARKOV history rows npy: slices (t-2D, t-D, t)")ap.add_argument("--wandb", type=int, default=1); ap.add_argument("--tag", default="", help="W&B name/id suffix (e.g. clip1)")args = ap.parse_args()
dist.init_process_group("nccl" if torch.cuda.is_available() else "gloo")rank, world = dist.get_rank(), dist.get_world_size(); lrank = int(os.environ.get("LOCAL_RANK", 0))dev = torch.device(f"cuda:{lrank}" if torch.cuda.is_available() else "cpu")if dev.type == "cuda": torch.cuda.set_device(dev)micro = args.micro or args.batch // worldassert micro * world == args.batch, f"no grad accumulation: micro {micro} x world {world} != batch {args.batch}"out = Path(args.out); out.mkdir(parents=True, exist_ok=True)if (out / "DONE").exists(): print("[dw2] DONE exists, skip", out); raise SystemExit(0)torch.backends.cuda.matmul.allow_tf32 = True; torch.backends.cudnn.allow_tf32 = TrueS = W.SPACES[args.space]; M = W.load_meta()
# ---------------------------------------------------------------- stats (rank 0 fits once per space; atomic)NHh = args.nhistassert NHh == 3, "V7_NONMARKOV: 3 history slices"HI, LAGS = NMH.load_hist(args.hist_index)if rank == 0 and not Path(S["stats"]).exists(): t0 = time.time(); (W.write_rsm_stats(args.space) if "rsm" in S else W.fit_stats(args.space, M)); print(f"[dw2] fitted stats {S['stats']} in {time.time()-t0:.0f}s", flush=True)dist.barrier()norm = W.TokNorm(S["stats"]).to(dev)tok = W.load_tok(args.space, M["N"]); assert tok.shape == (M["N"], S["n_tok"], 384), tok.shapePRg = torch.from_numpy(M["pr"]).to(dev); Ag = torch.from_numpy(M["act"]).to(dev)
# ---------------------------------------------------------------- samplerstr_rows = W.rows_of(M, M["train_eps"]); tr_rows = tr_rows[tr_rows + W.FS <= M["ep_to"][M["row_ep"][tr_rows]] - 1]tu_rows = W.rows_of(M, M["tune_eps"])tu_ok = tu_rows[tu_rows + W.FS * W.NMAC <= M["ep_to"][M["row_ep"][tu_rows]] - 1]ev_rows = np.sort(np.random.RandomState(123).choice(tu_ok, args.n_eval, replace=False))
def gather(t): fr, valid, ar = NMH.frame_index_hist(M, t, HI, LAGS) # [B,6] = 3 inputs + 3 own(+5) targets u, inv = np.unique(fr.ravel(), return_inverse=True) T = torch.from_numpy(np.asarray(tok[u]))[torch.from_numpy(inv)].view(len(t), 2 * NHh, S["n_tok"], 384) return T, torch.from_numpy(fr), torch.from_numpy(valid), torch.from_numpy(ar)
def producer(q, seed): rng = np.random.RandomState(seed) while True: q.put(gather(np.sort(rng.choice(tr_rows, micro))))
q = queue.Queue(maxsize=3 * args.workers)for k in range(args.workers): threading.Thread(target=producer, args=(q, 100000 * args.seed + 1000 * rank + k), daemon=True).start()
def to_batch(T, fr, valid, ar): T = T.to(dev, non_blocking=True); fr = fr.to(dev); ar = ar.to(dev) tz = norm(T) # [B,4,n,d] p = PRg[fr] # [B,4,10] a = Ag[ar].reshape(len(fr), NHh, -1) # [B,nh,50] return tz, p, a, valid.to(dev)
# ---------------------------------------------------------------- model / opt / ematorch.manual_seed(args.seed); np.random.seed(args.seed)net = W.DW2(S["n_tok"], n_hist=NHh, grad_ckpt=bool(args.grad_ckpt)).to(dev)ema = copy.deepcopy(net).eval()for p_ in ema.parameters(): p_.requires_grad_(False)opt = torch.optim.AdamW(net.parameters(), lr=args.lr, weight_decay=args.wd)step0, hist = 0, []if (out / "ckpt.pt").exists(): ck = torch.load(out / "ckpt.pt", map_location="cpu", weights_only=False) net.load_state_dict(ck["net"]); ema.load_state_dict(ck["ema"]); opt.load_state_dict(ck["opt"]) step0, hist = ck["step"], ck["hist"] if rank == 0: print(f"[dw2] RESUMED from ckpt.pt step {step0}", flush=True)nparam = sum(p_.numel() for p_ in net.parameters())
class Fwd(nn.Module): # DDP forward = encode + teacher-forced predict def __init__(self, m): super().__init__(); self.m = m def forward(self, tz, p, a): z = self.m.encode(tz, p) return self.m.predict(z[:, :NHh], a), z[:, NHh:].detach()
fwd = nn.parallel.DistributedDataParallel(Fwd(net), device_ids=[lrank] if dev.type == "cuda" else None)if args.compile and dev.type == "cuda": fwd = torch.compile(fwd, dynamic=False)
def train_loss(tz, p, a, valid): pred, tgt = fwd(tz, p, a) se = (pred.float() - tgt.float()) ** 2 vm = valid.float(); den = vm.sum().clamp(min=1) tot = (se.mean((-1, -2)) * vm).sum() / den vis = (se[..., :384].mean((-1, -2)) * vm).sum() / den; prs = (se[..., 384:].mean((-1, -2)) * vm).sum() / den return tot, vis, prs
@torch.no_grad()def evaluate(model): model.eval(); res = {"tf_vis": 0.0, "tf_pr": 0.0, "ro_vis": 0.0, "ro_pr": 0.0, "copy_vis": 0.0, "copy_pr": 0.0}; n = 0 for i in range(0, len(ev_rows), 64): t = ev_rows[i:i + 64] T, fr, valid, ar = gather(t) with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev.type == "cuda"): tz, p, a, vd = to_batch(T, fr, valid, ar) z = model.encode(tz, p); pred = model.predict(z[:, :NHh], a)[:, -1].float(); tgt = z[:, -1].float() res["tf_vis"] += float(((pred[..., :384] - tgt[..., :384]) ** 2).mean()) * len(t) res["tf_pr"] += float(((pred[..., 384:] - tgt[..., 384:]) ** 2).mean()) * len(t) # 10-macro rollout from t with the logged chunk t..t+49, compare to the real frame t+50 tt = torch.from_numpy(t).to(dev) cand = Ag[tt[:, None] + torch.arange(W.FS * W.NMAC, device=dev)[None]].reshape(len(t), W.NMAC, -1) e_ = M["row_ep"][t]; lo_ = M["ep_from"][e_] enc_rows = lambda r: model.encode(norm(torch.from_numpy(np.asarray(tok[r])).to(dev))[:, None], PRg[torch.from_numpy(r).to(dev)][:, None])[:, 0] act_rows = lambda r: Ag[torch.from_numpy(r).to(dev)[:, None] + torch.arange(W.FS, device=dev)[None]].reshape(len(r), -1) ro = NMH.rollout_hist(model, enc_rows, act_rows, t, lo_, LAGS, z[:, NHh - 1], cand)[:, -1].float() T50 = torch.from_numpy(np.asarray(tok[t + W.FS * W.NMAC])).to(dev) z50 = model.encode(norm(T50)[:, None], PRg[tt + W.FS * W.NMAC][:, None])[:, 0].float() z0 = z[:, NHh - 1].float() for nm, x in (("ro", ro), ("copy", z0)): res[nm + "_vis"] += float(((x[..., :384] - z50[..., :384]) ** 2).mean()) * len(t) res[nm + "_pr"] += float(((x[..., 384:] - z50[..., 384:]) ** 2).mean()) * len(t) n += len(t) model.train() return {k: v / n for k, v in res.items()}
def save_ckpt(path, step, extra=None): blob = {"model": "dinowm_v2", "space": args.space, "net": net.state_dict(), "ema": ema.state_dict(), "step": step, "arch": dict(n_tok=S["n_tok"], d_tok=384, pr_dim=10, pr_emb=10, a_in=W.FS * 10, a_emb=W.FS * 10, n_hist=NHh, depth=6, heads=16, dim_head=64, mlp=2048, dropout=0.1, emb_dropout=0.0, frameskip=W.FS, n_macro_per_chunk=W.NMAC, cams=S["cams"], hist_index=args.hist_index, hist_lags=LAGS), "norm": {k: v for k, v in np.load(S["stats"]).items()}, "tok_path": str(S["tok"]), "stats_path": str(S["stats"]), "act_norm": {"min": M["amin"].tolist(), "max": M["amax"].tolist(), "rule": "a_n = 2 (a - min)/(max - min) - 1"}, "proprio_norm": "jm cache feat_stats.npz [1536:] z-score, clip 10", "config": vars(args), "hist": hist} if extra: blob.update(extra) tmp = Path(str(path) + ".tmp"); torch.save(blob, tmp); tmp.rename(path)
wb = Noneif rank == 0 and args.wandb and os.environ.get("RSM_WANDB_ENTITY"): try: import wandb wb = wandb.init(entity=os.environ["RSM_WANDB_ENTITY"], project=os.environ.get("RSM_WANDB_PROJECT", "rsm_rise"), name=f"real_cooking_v7/DINOWM2_{args.space}{args.tag and '_'+args.tag}_s{args.seed}", config=vars(args) | {"nparam": nparam}, tags=["cooking_v7", "dinowm_v2", "nonmarkov", f"space_{args.space}", f"h{args.nhist}"], resume="allow", id=f"dw2v7{args.space}{args.tag}s{args.seed}", dir=str(out)) (out / "wandb_url.txt").write_text(wb.url + "\n") except Exception as e: print("[dw2] wandb init failed:", e, flush=True); wb = Noneif rank == 0: print(f"[dw2] space {args.space} seed {args.seed} world {world} micro {micro} n_tok {S['n_tok']} params {nparam/1e6:.2f}M " f"train rows {len(tr_rows)} tune eval rows {len(ev_rows)} step0 {step0}", flush=True)save_at = {int(s) for s in args.save_at.split(",")}t_last, n_since = time.time(), 0net.train()for step in range(step0 + 1, args.steps + 1): T, fr, valid, ar = q.get() with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev.type == "cuda"): tz, p, a, vd = to_batch(T, fr, valid, ar) loss, lv, lp = train_loss(tz, p, a, vd) if args.warmup > 0: for g_ in opt.param_groups: g_["lr"] = args.lr * min(1.0, step / args.warmup) opt.zero_grad(set_to_none=True); loss.backward() gn = torch.nn.utils.clip_grad_norm_(net.parameters(), args.clip if args.clip > 0 else float("inf")) opt.step() with torch.no_grad(): for pe_, pn_ in zip(ema.parameters(), net.parameters()): pe_.lerp_(pn_, 1 - args.ema) n_since += 1 if not torch.isfinite(loss): print(f"[dw2] NON-FINITE loss at step {step}", flush=True); raise SystemExit(5) if step % args.log_every == 0 and rank == 0: dt = (time.time() - t_last) / n_since; t_last, n_since = time.time(), 0 rec = {"step": step, "loss": float(loss), "loss_vis": float(lv), "loss_pr": float(lp), "gradnorm": float(gn), "s_per_step": dt, "qsize": q.qsize()} print("[dw2]", json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in rec.items()}), flush=True) if wb: wb.log({f"train/{k}": v for k, v in rec.items() if k != "step"}, step=step) if step % args.eval_every == 0 or step == args.steps: if rank == 0: m = evaluate(ema); m["step"] = step; hist.append(m) print("[dw2] EVAL", json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in m.items()}), flush=True) if wb: wb.log({f"tune/{k}": v for k, v in m.items() if k != "step"}, step=step) dist.barrier() if rank == 0 and (step % args.resume_every == 0 or step in save_at): save_ckpt(out / "ckpt.pt", step, {"opt": opt.state_dict()}) if step in save_at: save_ckpt(out / f"ckpt_s{step}.pt", step); print(f"[dw2] saved ckpt_s{step}.pt", flush=True) if step % args.resume_every == 0: dist.barrier()if rank == 0: json.dump({"hist": hist, "config": vars(args)}, open(out / "history.json", "w"), indent=1) (out / "DONE").write_text(json.dumps(hist[-1] if hist else {})) if wb: wb.finish()dist.barrier(); dist.destroy_process_group()print("[dw2] exit", rank, flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232#!/usr/bin/env python"""V7_NONMARKOV space-C copy of train_dw2_nm.py + --x-noise exactly as V7_FAIRC fairc/train_dw2_xn.py: N(0, x_noise^2) on thez-scored CONDITIONING history tokens + proprio z (all 3 history slices) fed to encode->predict; targets = encode of the CLEAN frames.Eval / rollouts noise-free.
V7_DINOWM2 trainer (torchrun DDP, one run per 8-GPU job). See dw2_common.py for the model / data definition.
Fixed recipe (owner 2026-11-22): batch 1024 = micro 128 x 8 GPUs (no accumulation), 100k steps, AdamW lr 3e-4 wd .01,constant lr (official), no grad clipping (grad norm logged; --clip only if the loss diverges), EMA .995 (evaluatedweights), bf16 autocast, ckpts at 20/40/60/80/100k (+ resume ckpt.pt every 2k). TRAIN split only; in-trainingdiagnostics on TUNE (teacher-forced next-macro MSE, 10-macro rollout MSE at the chunk end vs the copy baseline)."""import argparse, copy, json, os, sys, threading, queue, timefrom pathlib import Pathimport numpy as npimport torch, torch.nn as nn, torch.nn.functional as Fimport torch.distributed as distsys.path.insert(0, str(Path(__file__).resolve().parent))import nm_dw2 as NMH # V7_NONMARKOV history helpers (imports dinowm2/dw2_common)W = NMH.W
ap = argparse.ArgumentParser()ap.add_argument("--space", required=True, choices=list(W.SPACES)); ap.add_argument("--seed", type=int, default=0)ap.add_argument("--out", required=True)ap.add_argument("--steps", type=int, default=100000); ap.add_argument("--batch", type=int, default=1024)ap.add_argument("--micro", type=int, default=0, help="per-GPU batch (default batch/world; must equal it: no accumulation)")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("--clip", type=float, default=0.0)ap.add_argument("--save_at", default="20000,40000,60000,80000,100000"); ap.add_argument("--resume_every", type=int, default=2000)ap.add_argument("--eval_every", type=int, default=2500); ap.add_argument("--log_every", type=int, default=100)ap.add_argument("--n_eval", type=int, default=512); ap.add_argument("--workers", type=int, default=4)ap.add_argument("--compile", type=int, default=1); ap.add_argument("--grad_ckpt", type=int, default=0)ap.add_argument("--warmup", type=int, default=0, help="linear lr warmup steps (0 = official constant lr; contingency only)")ap.add_argument("--nhist", type=int, default=W.NH, help="history frames (official 3; owner arm 1)")ap.add_argument("--x-noise", type=float, default=0.0, help="V7_FAIRC semantics: noise on the conditioning state, targets clean")ap.add_argument("--hist_index", required=True, help="V7_NONMARKOV history rows npy: slices (t-2D, t-D, t)")ap.add_argument("--wandb", type=int, default=1); ap.add_argument("--tag", default="", help="W&B name/id suffix (e.g. clip1)")args = ap.parse_args()
dist.init_process_group("nccl" if torch.cuda.is_available() else "gloo")rank, world = dist.get_rank(), dist.get_world_size(); lrank = int(os.environ.get("LOCAL_RANK", 0))dev = torch.device(f"cuda:{lrank}" if torch.cuda.is_available() else "cpu")if dev.type == "cuda": torch.cuda.set_device(dev)micro = args.micro or args.batch // worldassert micro * world == args.batch, f"no grad accumulation: micro {micro} x world {world} != batch {args.batch}"out = Path(args.out); out.mkdir(parents=True, exist_ok=True)if (out / "DONE").exists(): print("[dw2] DONE exists, skip", out); raise SystemExit(0)torch.backends.cuda.matmul.allow_tf32 = True; torch.backends.cudnn.allow_tf32 = TrueS = W.SPACES[args.space]; M = W.load_meta()
# ---------------------------------------------------------------- stats (rank 0 fits once per space; atomic)NHh = args.nhistassert NHh == 3, "V7_NONMARKOV: 3 history slices"HI, LAGS = NMH.load_hist(args.hist_index)if rank == 0 and not Path(S["stats"]).exists(): t0 = time.time(); (W.write_rsm_stats(args.space) if "rsm" in S else W.fit_stats(args.space, M)); print(f"[dw2] fitted stats {S['stats']} in {time.time()-t0:.0f}s", flush=True)dist.barrier()norm = W.TokNorm(S["stats"]).to(dev)tok = W.load_tok(args.space, M["N"]); assert tok.shape == (M["N"], S["n_tok"], 384), tok.shapePRg = torch.from_numpy(M["pr"]).to(dev); Ag = torch.from_numpy(M["act"]).to(dev)
# ---------------------------------------------------------------- samplerstr_rows = W.rows_of(M, M["train_eps"]); tr_rows = tr_rows[tr_rows + W.FS <= M["ep_to"][M["row_ep"][tr_rows]] - 1]tu_rows = W.rows_of(M, M["tune_eps"])tu_ok = tu_rows[tu_rows + W.FS * W.NMAC <= M["ep_to"][M["row_ep"][tu_rows]] - 1]ev_rows = np.sort(np.random.RandomState(123).choice(tu_ok, args.n_eval, replace=False))
def gather(t): fr, valid, ar = NMH.frame_index_hist(M, t, HI, LAGS) # [B,6] = 3 inputs + 3 own(+5) targets u, inv = np.unique(fr.ravel(), return_inverse=True) T = torch.from_numpy(np.asarray(tok[u]))[torch.from_numpy(inv)].view(len(t), 2 * NHh, S["n_tok"], 384) return T, torch.from_numpy(fr), torch.from_numpy(valid), torch.from_numpy(ar)
def producer(q, seed): rng = np.random.RandomState(seed) while True: q.put(gather(np.sort(rng.choice(tr_rows, micro))))
q = queue.Queue(maxsize=3 * args.workers)for k in range(args.workers): threading.Thread(target=producer, args=(q, 100000 * args.seed + 1000 * rank + k), daemon=True).start()
def to_batch(T, fr, valid, ar): T = T.to(dev, non_blocking=True); fr = fr.to(dev); ar = ar.to(dev) tz = norm(T) # [B,4,n,d] p = PRg[fr] # [B,4,10] a = Ag[ar].reshape(len(fr), NHh, -1) # [B,nh,50] return tz, p, a, valid.to(dev)
# ---------------------------------------------------------------- model / opt / ematorch.manual_seed(args.seed); np.random.seed(args.seed)net = W.DW2(S["n_tok"], n_hist=NHh, grad_ckpt=bool(args.grad_ckpt)).to(dev)ema = copy.deepcopy(net).eval()for p_ in ema.parameters(): p_.requires_grad_(False)opt = torch.optim.AdamW(net.parameters(), lr=args.lr, weight_decay=args.wd)step0, hist = 0, []if (out / "ckpt.pt").exists(): ck = torch.load(out / "ckpt.pt", map_location="cpu", weights_only=False) net.load_state_dict(ck["net"]); ema.load_state_dict(ck["ema"]); opt.load_state_dict(ck["opt"]) step0, hist = ck["step"], ck["hist"] if rank == 0: print(f"[dw2] RESUMED from ckpt.pt step {step0}", flush=True)nparam = sum(p_.numel() for p_ in net.parameters())
class Fwd(nn.Module): # DDP forward = encode + teacher-forced predict def __init__(self, m): super().__init__(); self.m = m def forward(self, tz, p, a, tzn, pn): # tzn/pn: noisy history inputs (== tz/p[:, :NHh] if x_noise 0) z = self.m.encode(tz, p) return self.m.predict(self.m.encode(tzn, pn), a), z[:, NHh:].detach()
fwd = nn.parallel.DistributedDataParallel(Fwd(net), device_ids=[lrank] if dev.type == "cuda" else None)if args.compile and dev.type == "cuda": fwd = torch.compile(fwd, dynamic=False)
def train_loss(tz, p, a, valid): tzn, pn = tz[:, :NHh], p[:, :NHh] if args.x_noise > 0: tzn = tzn + args.x_noise * torch.randn_like(tzn); pn = pn + args.x_noise * torch.randn_like(pn) pred, tgt = fwd(tz, p, a, tzn, pn) se = (pred.float() - tgt.float()) ** 2 vm = valid.float(); den = vm.sum().clamp(min=1) tot = (se.mean((-1, -2)) * vm).sum() / den vis = (se[..., :384].mean((-1, -2)) * vm).sum() / den; prs = (se[..., 384:].mean((-1, -2)) * vm).sum() / den return tot, vis, prs
@torch.no_grad()def evaluate(model): model.eval(); res = {"tf_vis": 0.0, "tf_pr": 0.0, "ro_vis": 0.0, "ro_pr": 0.0, "copy_vis": 0.0, "copy_pr": 0.0}; n = 0 for i in range(0, len(ev_rows), 64): t = ev_rows[i:i + 64] T, fr, valid, ar = gather(t) with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev.type == "cuda"): tz, p, a, vd = to_batch(T, fr, valid, ar) z = model.encode(tz, p); pred = model.predict(z[:, :NHh], a)[:, -1].float(); tgt = z[:, -1].float() res["tf_vis"] += float(((pred[..., :384] - tgt[..., :384]) ** 2).mean()) * len(t) res["tf_pr"] += float(((pred[..., 384:] - tgt[..., 384:]) ** 2).mean()) * len(t) # 10-macro rollout from t with the logged chunk t..t+49, compare to the real frame t+50 tt = torch.from_numpy(t).to(dev) cand = Ag[tt[:, None] + torch.arange(W.FS * W.NMAC, device=dev)[None]].reshape(len(t), W.NMAC, -1) e_ = M["row_ep"][t]; lo_ = M["ep_from"][e_] enc_rows = lambda r: model.encode(norm(torch.from_numpy(np.asarray(tok[r])).to(dev))[:, None], PRg[torch.from_numpy(r).to(dev)][:, None])[:, 0] act_rows = lambda r: Ag[torch.from_numpy(r).to(dev)[:, None] + torch.arange(W.FS, device=dev)[None]].reshape(len(r), -1) ro = NMH.rollout_hist(model, enc_rows, act_rows, t, lo_, LAGS, z[:, NHh - 1], cand)[:, -1].float() T50 = torch.from_numpy(np.asarray(tok[t + W.FS * W.NMAC])).to(dev) z50 = model.encode(norm(T50)[:, None], PRg[tt + W.FS * W.NMAC][:, None])[:, 0].float() z0 = z[:, NHh - 1].float() for nm, x in (("ro", ro), ("copy", z0)): res[nm + "_vis"] += float(((x[..., :384] - z50[..., :384]) ** 2).mean()) * len(t) res[nm + "_pr"] += float(((x[..., 384:] - z50[..., 384:]) ** 2).mean()) * len(t) n += len(t) model.train() return {k: v / n for k, v in res.items()}
def save_ckpt(path, step, extra=None): blob = {"model": "dinowm_v2", "space": args.space, "net": net.state_dict(), "ema": ema.state_dict(), "step": step, "arch": dict(n_tok=S["n_tok"], d_tok=384, pr_dim=10, pr_emb=10, a_in=W.FS * 10, a_emb=W.FS * 10, n_hist=NHh, depth=6, heads=16, dim_head=64, mlp=2048, dropout=0.1, emb_dropout=0.0, frameskip=W.FS, n_macro_per_chunk=W.NMAC, cams=S["cams"], hist_index=args.hist_index, hist_lags=LAGS), "norm": {k: v for k, v in np.load(S["stats"]).items()}, "tok_path": str(S["tok"]), "stats_path": str(S["stats"]), "act_norm": {"min": M["amin"].tolist(), "max": M["amax"].tolist(), "rule": "a_n = 2 (a - min)/(max - min) - 1"}, "proprio_norm": "jm cache feat_stats.npz [1536:] z-score, clip 10", "config": vars(args), "hist": hist} if extra: blob.update(extra) tmp = Path(str(path) + ".tmp"); torch.save(blob, tmp); tmp.rename(path)
wb = Noneif rank == 0 and args.wandb and os.environ.get("RSM_WANDB_ENTITY"): try: import wandb wb = wandb.init(entity=os.environ["RSM_WANDB_ENTITY"], project=os.environ.get("RSM_WANDB_PROJECT", "rsm_rise"), name=f"real_cooking_v7/DINOWM2_{args.space}{args.tag and '_'+args.tag}_s{args.seed}", config=vars(args) | {"nparam": nparam}, tags=["cooking_v7", "dinowm_v2", "nonmarkov", f"xnoise{args.x_noise}", f"space_{args.space}", f"h{args.nhist}"], resume="allow", id=f"dw2v7{args.space}{args.tag}s{args.seed}", dir=str(out)) (out / "wandb_url.txt").write_text(wb.url + "\n") except Exception as e: print("[dw2] wandb init failed:", e, flush=True); wb = Noneif rank == 0: print(f"[dw2] space {args.space} seed {args.seed} world {world} micro {micro} n_tok {S['n_tok']} params {nparam/1e6:.2f}M " f"train rows {len(tr_rows)} tune eval rows {len(ev_rows)} step0 {step0}", flush=True)save_at = {int(s) for s in args.save_at.split(",")}t_last, n_since = time.time(), 0net.train()for step in range(step0 + 1, args.steps + 1): T, fr, valid, ar = q.get() with torch.autocast("cuda", dtype=torch.bfloat16, enabled=dev.type == "cuda"): tz, p, a, vd = to_batch(T, fr, valid, ar) loss, lv, lp = train_loss(tz, p, a, vd) if args.warmup > 0: for g_ in opt.param_groups: g_["lr"] = args.lr * min(1.0, step / args.warmup) opt.zero_grad(set_to_none=True); loss.backward() gn = torch.nn.utils.clip_grad_norm_(net.parameters(), args.clip if args.clip > 0 else float("inf")) opt.step() with torch.no_grad(): for pe_, pn_ in zip(ema.parameters(), net.parameters()): pe_.lerp_(pn_, 1 - args.ema) n_since += 1 if not torch.isfinite(loss): print(f"[dw2] NON-FINITE loss at step {step}", flush=True); raise SystemExit(5) if step % args.log_every == 0 and rank == 0: dt = (time.time() - t_last) / n_since; t_last, n_since = time.time(), 0 rec = {"step": step, "loss": float(loss), "loss_vis": float(lv), "loss_pr": float(lp), "gradnorm": float(gn), "s_per_step": dt, "qsize": q.qsize()} print("[dw2]", json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in rec.items()}), flush=True) if wb: wb.log({f"train/{k}": v for k, v in rec.items() if k != "step"}, step=step) if step % args.eval_every == 0 or step == args.steps: if rank == 0: m = evaluate(ema); m["step"] = step; hist.append(m) print("[dw2] EVAL", json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in m.items()}), flush=True) if wb: wb.log({f"tune/{k}": v for k, v in m.items() if k != "step"}, step=step) dist.barrier() if rank == 0 and (step % args.resume_every == 0 or step in save_at): save_ckpt(out / "ckpt.pt", step, {"opt": opt.state_dict()}) if step in save_at: save_ckpt(out / f"ckpt_s{step}.pt", step); print(f"[dw2] saved ckpt_s{step}.pt", flush=True) if step % args.resume_every == 0: dist.barrier()if rank == 0: json.dump({"hist": hist, "config": vars(args)}, open(out / "history.json", "w"), indent=1) (out / "DONE").write_text(json.dumps(hist[-1] if hist else {})) if wb: wb.finish()dist.barrier(); dist.destroy_process_group()print("[dw2] exit", rank, flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121#!/usr/bin/env python"""V7_IQLMATCH trainer: chunk-level (SMDP) IQL critic on RSM's input diet. Spec: status/real/V7_IQLMATCH.md run 1.usage: train.py --space A|B|C --seed S --out runs/v7_iqlmatch/<space>/iqlm_<space>_s<S> [--steps 200000] [--smoke]Resumable: last.pt (every 10k) holds nets + optimisers + RNG; DONE marker when finished."""import argparse, json, sys, time, hashlibfrom pathlib import Pathimport numpy as np, torchimport torch.nn.functional as Fnsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/iqlmatch")import common as C # V7_IQLMATCH common (unchanged); V7_NONMARKOV adds --hist_index here only
ap = argparse.ArgumentParser()ap.add_argument("--space", required=True, choices=list(C.SPACES)); ap.add_argument("--seed", type=int, required=True)ap.add_argument("--out", required=True); ap.add_argument("--steps", type=int, default=200000); ap.add_argument("--smoke", action="store_true")ap.add_argument("--hist_index", required=True, help="V7_NONMARKOV: s = H(t) = [x_t | x_t - x_{t-D} | x_t - x_{t-2D}]")a = ap.parse_args()OUT = Path(a.out); OUT.mkdir(parents=True, exist_ok=True)if (OUT / "DONE").exists(): print("[iqlm] DONE exists", OUT); sys.exit(0)CKS = [20000, 40000, 60000, 80000, 100000, 120000, 160000, 200000]if a.smoke: a.steps = 600; CKS = [300, 600]cfg = dict(space=a.space, seed=a.seed, steps=a.steps, ckpts=CKS, d_s=3 * 1546, hist_index=a.hist_index, d_a=C.CHUNK * C.AD, chunk=C.CHUNK, gamma=C.GAMMA, expectile=0.9, tau=0.005, lr=3e-4, batch=1024, width=512, depth=3, layernorm=True, reward="reward_shaped2", cache=str(C.SPACES[a.space][0]), feat_stats=str(C.SPACES[a.space][1]), action_norm=str(C.NORM), split=str(C.SPLIT), readout="min_k critic_target_k(x, a_n)", state="H(t)=[x_t|x_t-x_{t-D}|x_t-x_{t-2D}], x=clip((cat[z,proprio]-mu)/max(sd,.01),-10,10)", action=f"raw {C.CHUNK}x10 chunk -> 2(a-min)/(max-min)-1, flat time-major", target=f"r_chunk + gamma^{C.CHUNK} V(s_t+{C.CHUNK}); at episode end: terminal(5/6/7) r_chunk, else r_chunk + gamma^n V(s_T-1)")json.dump(cfg, open(OUT / "config.json", "w"), indent=1)dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")torch.manual_seed(a.seed); np.random.seed(a.seed)
t0 = time.time()ef, et = C.meta(); train_eps, tune_eps = C.split_eps()row_ep = np.repeat(np.arange(len(ef)), et - ef)X = torch.from_numpy(C.states(a.space)).to(dev)_HI = torch.from_numpy(np.load(a.hist_index).astype(np.int64)).to(dev); assert _HI.shape == (len(X), 2)X = torch.cat([X, X - X[_HI[:, 0]], X - X[_HI[:, 1]]], 1); del _HI # H(t) for every rowan = C.ActNorm(); act = np.load(C.CACHE_A / "act.f32.npy")ACTN = torch.from_numpy((2 * (act - an.lo) / (an.hi - an.lo) - 1).astype(np.float32)).to(dev)
def tens(eps): R, RC, NX, DC = C.transitions(eps) CH = C.chunk_rows(R, et[row_ep[R]]) return [torch.from_numpy(v).to(dev) for v in (R, CH, RC, NX, DC)]
TR = tens(train_eps); TU = tens(tune_eps)assert set(row_ep[TR[0].cpu().numpy()]) == set(train_eps) and not set(train_eps) & set(tune_eps)print(f"[iqlm] {a.space} s{a.seed}: X {tuple(X.shape)} train {len(TR[0])} tune {len(TU[0])} frames; " f"r_chunk mean {TR[2].mean():.3f} [{TR[2].min():.2f},{TR[2].max():.2f}] done {(TR[4] == 0).sum().item()} " f"load {time.time() - t0:.0f}s dev {dev}", flush=True)rng = torch.Generator(device=dev); rng.manual_seed(a.seed)tu_idx = torch.randperm(len(TU[0]), generator=torch.Generator().manual_seed(0))[:20000].to(dev)
crit = C.Critic(cfg["d_s"]).to(dev); targ = C.Critic(cfg["d_s"]).to(dev); targ.load_state_dict(crit.state_dict())for p in targ.parameters(): p.requires_grad_(False)vnet = C.mlp(cfg["d_s"]).to(dev)oq = torch.optim.Adam(crit.parameters(), lr=3e-4); ov = torch.optim.Adam(vnet.parameters(), lr=3e-4)step = 0if (OUT / "last.pt").exists(): ck = torch.load(OUT / "last.pt", map_location=dev, weights_only=False) crit.load_state_dict(ck["critic"]); targ.load_state_dict(ck["critic_target"]); vnet.load_state_dict(ck["value"]) oq.load_state_dict(ck["opt_q"]); ov.load_state_dict(ck["opt_v"]); rng.set_state(ck["rng"]); step = ck["step"] print(f"[iqlm] resumed at step {step}", flush=True)
def batch(D, idx): R, CH, RC, NX, DC = D s = X[R[idx]]; ac = ACTN[CH[idx]].reshape(len(idx), -1); s2 = X[NX[idx]] return s, ac, RC[idx], s2, DC[idx]
def losses(s, ac, rc, s2, dc): with torch.no_grad(): qt = targ.qmin(s, ac); vn = vnet(s2).squeeze(-1); y = rc + dc * vn v = vnet(s).squeeze(-1); u = qt - v lv = (torch.abs(0.9 - (u < 0).float()) * u ** 2).mean() q1, q2 = crit(s, ac); lq = Fn.mse_loss(q1, y) + Fn.mse_loss(q2, y) return lv, lq, dict(q=qt.mean().item(), v=v.mean().item(), y=y.mean().item())
def save(path, full): d = {"critic_target": targ.state_dict(), "critic": crit.state_dict(), "value": vnet.state_dict(), "config": cfg, "step": step} if full: d.update(opt_q=oq.state_dict(), opt_v=ov.state_dict(), rng=rng.get_state()) torch.save(d, str(path) + ".tmp"); Path(str(path) + ".tmp").rename(path)
hist = open(OUT / "history.jsonl", "a"); tl = time.time()while step < a.steps: idx = torch.randint(0, len(TR[0]), (1024,), device=dev, generator=rng) lv, lq, st = losses(*batch(TR, idx)) ov.zero_grad(set_to_none=True); lv.backward(); ov.step() oq.zero_grad(set_to_none=True); lq.backward(); oq.step() with torch.no_grad(): for pt, pc in zip(targ.parameters(), crit.parameters()): pt.mul_(1 - 0.005).add_(pc, alpha=0.005) step += 1 if step % 1000 == 0 or step == a.steps: rec = dict(step=step, lv=lv.item(), lq=lq.item(), **st, sec=round(time.time() - t0, 1)) if step % 10000 == 0 or step in CKS: with torch.no_grad(): vals = [losses(*batch(TU, tu_idx[i:i + 4096])) for i in range(0, len(tu_idx), 4096)] rec.update(tune_lv=float(np.mean([v[0].item() for v in vals])), tune_lq=float(np.mean([v[1].item() for v in vals])), tune_q=float(np.mean([v[2]["q"] for v in vals]))) hist.write(json.dumps(rec) + "\n"); hist.flush() if step % 10000 == 0 or step == a.steps or a.smoke: print(f"[iqlm] {json.dumps(rec)} ({(time.time() - tl) / 1000 * 1e3:.1f} ms/step)", flush=True) tl = time.time() if step in CKS: save(OUT / f"ckpt_s{step}.pt", False) if step % 10000 == 0 or step == a.steps: save(OUT / "last.pt", True)hist.close()man = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(OUT.glob("ckpt_s*.pt"))}json.dump(man, open(OUT / "ckpt_sha256.json", "w"), indent=1)(OUT / "DONE").write_text(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + "\n")print(f"[iqlm] done {OUT} {time.time() - t0:.0f}s", flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124#!/usr/bin/env python"""V7_NONMARKOV space-C copy of train_iql_nm.py + --x-noise exactly as V7_FAIRC fairc/train_iql_xn.py (noise on the whole H(t)).V7_IQLMATCH trainer: chunk-level (SMDP) IQL critic on RSM's input diet. Spec: status/real/V7_IQLMATCH.md run 1.usage: train.py --space A|B|C --seed S --out runs/v7_iqlmatch/<space>/iqlm_<space>_s<S> [--steps 200000] [--smoke]Resumable: last.pt (every 10k) holds nets + optimisers + RNG; DONE marker when finished."""import argparse, json, sys, time, hashlibfrom pathlib import Pathimport numpy as np, torchimport torch.nn.functional as Fnsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/iqlmatch")import common as C # V7_IQLMATCH common (unchanged); V7_NONMARKOV adds --hist_index here only
ap = argparse.ArgumentParser()ap.add_argument("--space", required=True, choices=list(C.SPACES)); ap.add_argument("--seed", type=int, required=True)ap.add_argument("--out", required=True); ap.add_argument("--steps", type=int, default=200000); ap.add_argument("--smoke", action="store_true")ap.add_argument("--x-noise", type=float, default=0.0)ap.add_argument("--hist_index", required=True, help="V7_NONMARKOV: s = H(t) = [x_t | x_t - x_{t-D} | x_t - x_{t-2D}]")a = ap.parse_args()OUT = Path(a.out); OUT.mkdir(parents=True, exist_ok=True)if (OUT / "DONE").exists(): print("[iqlm] DONE exists", OUT); sys.exit(0)CKS = [20000, 40000, 60000, 80000, 100000, 120000, 160000, 200000]if a.smoke: a.steps = 600; CKS = [300, 600]cfg = dict(space=a.space, seed=a.seed, steps=a.steps, ckpts=CKS, d_s=3 * 1546, hist_index=a.hist_index, x_noise=a.x_noise, x_noise_rule="N(0,x_noise^2) on s=H(t) for Q(s,a), V(s) regression; targets clean", d_a=C.CHUNK * C.AD, chunk=C.CHUNK, gamma=C.GAMMA, expectile=0.9, tau=0.005, lr=3e-4, batch=1024, width=512, depth=3, layernorm=True, reward="reward_shaped2", cache=str(C.SPACES[a.space][0]), feat_stats=str(C.SPACES[a.space][1]), action_norm=str(C.NORM), split=str(C.SPLIT), readout="min_k critic_target_k(x, a_n)", state="H(t)=[x_t|x_t-x_{t-D}|x_t-x_{t-2D}], x=clip((cat[z,proprio]-mu)/max(sd,.01),-10,10)", action=f"raw {C.CHUNK}x10 chunk -> 2(a-min)/(max-min)-1, flat time-major", target=f"r_chunk + gamma^{C.CHUNK} V(s_t+{C.CHUNK}); at episode end: terminal(5/6/7) r_chunk, else r_chunk + gamma^n V(s_T-1)")json.dump(cfg, open(OUT / "config.json", "w"), indent=1)dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")torch.manual_seed(a.seed); np.random.seed(a.seed)
t0 = time.time()ef, et = C.meta(); train_eps, tune_eps = C.split_eps()row_ep = np.repeat(np.arange(len(ef)), et - ef)X = torch.from_numpy(C.states(a.space)).to(dev)_HI = torch.from_numpy(np.load(a.hist_index).astype(np.int64)).to(dev); assert _HI.shape == (len(X), 2)X = torch.cat([X, X - X[_HI[:, 0]], X - X[_HI[:, 1]]], 1); del _HI # H(t) for every rowan = C.ActNorm(); act = np.load(C.CACHE_A / "act.f32.npy")ACTN = torch.from_numpy((2 * (act - an.lo) / (an.hi - an.lo) - 1).astype(np.float32)).to(dev)
def tens(eps): R, RC, NX, DC = C.transitions(eps) CH = C.chunk_rows(R, et[row_ep[R]]) return [torch.from_numpy(v).to(dev) for v in (R, CH, RC, NX, DC)]
TR = tens(train_eps); TU = tens(tune_eps)assert set(row_ep[TR[0].cpu().numpy()]) == set(train_eps) and not set(train_eps) & set(tune_eps)print(f"[iqlm] {a.space} s{a.seed}: X {tuple(X.shape)} train {len(TR[0])} tune {len(TU[0])} frames; " f"r_chunk mean {TR[2].mean():.3f} [{TR[2].min():.2f},{TR[2].max():.2f}] done {(TR[4] == 0).sum().item()} " f"load {time.time() - t0:.0f}s dev {dev}", flush=True)rng = torch.Generator(device=dev); rng.manual_seed(a.seed)tu_idx = torch.randperm(len(TU[0]), generator=torch.Generator().manual_seed(0))[:20000].to(dev)
crit = C.Critic(cfg["d_s"]).to(dev); targ = C.Critic(cfg["d_s"]).to(dev); targ.load_state_dict(crit.state_dict())for p in targ.parameters(): p.requires_grad_(False)vnet = C.mlp(cfg["d_s"]).to(dev)oq = torch.optim.Adam(crit.parameters(), lr=3e-4); ov = torch.optim.Adam(vnet.parameters(), lr=3e-4)step = 0if (OUT / "last.pt").exists(): ck = torch.load(OUT / "last.pt", map_location=dev, weights_only=False) crit.load_state_dict(ck["critic"]); targ.load_state_dict(ck["critic_target"]); vnet.load_state_dict(ck["value"]) oq.load_state_dict(ck["opt_q"]); ov.load_state_dict(ck["opt_v"]); rng.set_state(ck["rng"]); step = ck["step"] print(f"[iqlm] resumed at step {step}", flush=True)
def batch(D, idx): R, CH, RC, NX, DC = D s = X[R[idx]]; ac = ACTN[CH[idx]].reshape(len(idx), -1); s2 = X[NX[idx]] return s, ac, RC[idx], s2, DC[idx]
def losses(s, ac, rc, s2, dc, xn=0.0): with torch.no_grad(): qt = targ.qmin(s, ac); vn = vnet(s2).squeeze(-1); y = rc + dc * vn sn = s + xn * torch.randn(s.shape, device=s.device, generator=rng) if xn > 0 else s v = vnet(sn).squeeze(-1); u = qt - v lv = (torch.abs(0.9 - (u < 0).float()) * u ** 2).mean() q1, q2 = crit(sn, ac); lq = Fn.mse_loss(q1, y) + Fn.mse_loss(q2, y) return lv, lq, dict(q=qt.mean().item(), v=v.mean().item(), y=y.mean().item())
def save(path, full): d = {"critic_target": targ.state_dict(), "critic": crit.state_dict(), "value": vnet.state_dict(), "config": cfg, "step": step} if full: d.update(opt_q=oq.state_dict(), opt_v=ov.state_dict(), rng=rng.get_state()) torch.save(d, str(path) + ".tmp"); Path(str(path) + ".tmp").rename(path)
hist = open(OUT / "history.jsonl", "a"); tl = time.time()while step < a.steps: idx = torch.randint(0, len(TR[0]), (1024,), device=dev, generator=rng) lv, lq, st = losses(*batch(TR, idx), xn=a.x_noise) ov.zero_grad(set_to_none=True); lv.backward(); ov.step() oq.zero_grad(set_to_none=True); lq.backward(); oq.step() with torch.no_grad(): for pt, pc in zip(targ.parameters(), crit.parameters()): pt.mul_(1 - 0.005).add_(pc, alpha=0.005) step += 1 if step % 1000 == 0 or step == a.steps: rec = dict(step=step, lv=lv.item(), lq=lq.item(), **st, sec=round(time.time() - t0, 1)) if step % 10000 == 0 or step in CKS: with torch.no_grad(): vals = [losses(*batch(TU, tu_idx[i:i + 4096])) for i in range(0, len(tu_idx), 4096)] rec.update(tune_lv=float(np.mean([v[0].item() for v in vals])), tune_lq=float(np.mean([v[1].item() for v in vals])), tune_q=float(np.mean([v[2]["q"] for v in vals]))) hist.write(json.dumps(rec) + "\n"); hist.flush() if step % 10000 == 0 or step == a.steps or a.smoke: print(f"[iqlm] {json.dumps(rec)} ({(time.time() - tl) / 1000 * 1e3:.1f} ms/step)", flush=True) tl = time.time() if step in CKS: save(OUT / f"ckpt_s{step}.pt", False) if step % 10000 == 0 or step == a.steps: save(OUT / "last.pt", True)hist.close()man = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(OUT.glob("ckpt_s*.pt"))}json.dump(man, open(OUT / "ckpt_sha256.json", "w"), indent=1)(OUT / "DONE").write_text(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + "\n")print(f"[iqlm] done {OUT} {time.time() - t0:.0f}s", flush=True)rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/merge_verify.pyAdded+60
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/mislabel_report.pyAdded+41
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/model.pyAdded+528
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pack.pyAdded+278
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/paired_test.pyAdded+55
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/parl_rsm.pyAdded+305
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pooled_test.pyAdded+25
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_actcon.pyAdded+95
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_action_info.pyAdded+97
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_crn.pyAdded+105
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits.pyAdded+46
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits2.pyAdded+39
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_perturb.pyAdded+81
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_pessimism.pyAdded+73
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_qf.pyAdded+76
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/proposer_bias_diag.pyAdded+105
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/q_vs_return_diag.pyAdded+85
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/recheck_encoding.pyAdded+157
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reencode_rollouts.pyAdded+121
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report.pyAdded+96
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report_arms.pyAdded+95
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rerender_rollouts.pyAdded+318
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reward_diag.pyAdded+56
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rsm_main.pyAdded+325
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/run_ope.pyAdded+171
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/subgoals_from_npz.pyAdded+24
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/sweep_horizon.pyAdded+140
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_dwm.pyAdded+262
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_lewm_port.pyAdded+143
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/their_trainer_control.pyAdded+46
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/thr_test.pyAdded+32
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_goal_clf.pyAdded+122
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_lewm.pyAdded+244
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm.pyAdded+1287
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm_dwm.pyAdded+765
rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/verify_successes.pyAdded+97
rsm_rise/scripts/real/v7/nonmarkov/rsm_nm_qall.pyAdded+187
rsm_rise/scripts/real/v7/nonmarkov/run_eval_dw_nm.shAdded+35
rsm_rise/scripts/real/v7/nonmarkov/run_eval_iql_nm.shAdded+33
rsm_rise/scripts/real/v7/nonmarkov/run_eval_rsm_nm.shAdded+27
rsm_rise/scripts/real/v7/nonmarkov/score_iql_nm.pyAdded+105
rsm_rise/scripts/real/v7/nonmarkov/smoke.sbatchAdded+61
rsm_rise/scripts/real/v7/nonmarkov/smoke2.sbatchAdded+30
rsm_rise/scripts/real/v7/nonmarkov/smokeC.sbatchAdded+30
rsm_rise/scripts/real/v7/nonmarkov/smoke_rsmnm.sbatchAdded+23
rsm_rise/scripts/real/v7/nonmarkov/table.pyAdded+122
rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nm.pyAdded+224
rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nmxn.pyAdded+232
rsm_rise/scripts/real/v7/nonmarkov/train_iql_nm.pyAdded+121
rsm_rise/scripts/real/v7/nonmarkov/train_iql_nmxn.pyAdded+124